コード例 #1
0
        public async Task GetHandledDHCPv6PacketByScopeId()
        {
            Random random = new Random();

            Guid  scopeId = random.NextGuid();
            Int32 amount  = random.Next(10, 250);
            List <DHCPv6PacketHandledEntry> response = new List <DHCPv6PacketHandledEntry>();

            DHCPv6RootScope rootScope = GetRootScope();

            rootScope.Load(new[] { new DHCPv6ScopeAddedEvent {
                                       Instructions = new DHCPv6ScopeCreateInstruction
                                       {
                                           Id = scopeId,
                                       }
                                   } });

            Mock <IDHCPv6ReadStore> readStoreMock = new Mock <IDHCPv6ReadStore>(MockBehavior.Strict);

            readStoreMock.Setup(x => x.GetHandledDHCPv6PacketByScopeId(scopeId, amount)).ReturnsAsync(response).Verifiable();

            var controller   = new DHCPv6StatisticsController(rootScope, readStoreMock.Object);
            var actionResult = await controller.GetHandledDHCPv6PacketByScopeId(scopeId, amount);

            var result = actionResult.EnsureOkObjectResult <IEnumerable <DHCPv6PacketHandledEntry> >(true);

            Assert.NotNull(result);
            Assert.Equal(response, result);

            readStoreMock.Verify();
        }
コード例 #2
0
        public void GetScopesAsList()
        {
            Random random = new Random();

            var         events          = new List <DomainEvent>();
            Int32       rootScopeAmount = random.Next(10, 30);
            List <Guid> rootScopeIds    = new List <Guid>(rootScopeAmount);

            for (int i = 0; i < rootScopeAmount; i++)
            {
                Guid        scopeId = Guid.NewGuid();
                IPv6Address start   = random.GetIPv6Address();
                IPv6Address end     = start + 100;

                events.Add(new DHCPv6ScopeAddedEvent(new DHCPv6ScopeCreateInstruction
                {
                    Id   = scopeId,
                    Name = random.GetAlphanumericString(),
                    AddressProperties = new DHCPv6ScopeAddressProperties(start, end),
                }));

                rootScopeIds.Add(scopeId);

                GenerateScopeTree(
                    random.NextDouble(), random,
                    new List <Guid> {
                    scopeId
                }, events);
            }

            var scopeResolverMock = new Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> >(MockBehavior.Strict);

            scopeResolverMock.Setup(x => x.InitializeResolver(It.IsAny <CreateScopeResolverInformation>())).Returns(Mock.Of <IScopeResolver <DHCPv6Packet, IPv6Address> >());

            Mock <ILoggerFactory> factoryMock = new Mock <ILoggerFactory>(MockBehavior.Strict);

            factoryMock.Setup(x => x.CreateLogger(It.IsAny <String>())).Returns(Mock.Of <ILogger <DHCPv6RootScope> >());

            DHCPv6RootScope rootScope = new DHCPv6RootScope(random.NextGuid(), scopeResolverMock.Object, factoryMock.Object);

            rootScope.Load(events);

            var controller = new DHCPv6ScopeController(
                Mock.Of <IMediator>(MockBehavior.Strict),
                Mock.Of <IScopeResolverManager <DHCPv6Packet, IPv6Address> >(MockBehavior.Strict),
                rootScope);
            var actionResult = controller.GetScopesAsList();
            var result       = actionResult.EnsureOkObjectResult <IEnumerable <DHCPv6ScopeItem> >(true);

            Assert.Equal(events.Count, result.Count());
            for (int i = 0; i < events.Count; i++)
            {
                var scope  = result.ElementAt(i);
                var @event = (DHCPv6ScopeAddedEvent)events[i];
                Assert.Equal(@event.Instructions.Name, scope.Name);
                Assert.Equal(@event.Instructions.Id, scope.Id);
                Assert.Equal(@event.Instructions.AddressProperties.Start.ToString(), scope.StartAddress);
                Assert.Equal(@event.Instructions.AddressProperties.End.ToString(), scope.EndAddress);
            }
        }
コード例 #3
0
        public async Task <DHCPv6RootScope> GetRootScope()
        {
            DHCPv6RootScope rootScope = new DHCPv6RootScope(_rootScopeid, Provider.GetRequiredService <IScopeResolverManager <DHCPv6Packet, IPv6Address> >(), Provider.GetRequiredService <ILoggerFactory>());

            PseudoDHCPv6RootScope pseudoRootScope = new PseudoDHCPv6RootScope();
            await EventStore.HydrateAggragate(pseudoRootScope);

            List <DomainEvent> eventsToApply = new();

            foreach (var scopeId in pseudoRootScope.ScopeIds)
            {
                var events = await EventStore.GetEvents <PseudoDHCPv6Scope>(scopeId, 100);

                eventsToApply.AddRange(events);
            }

            foreach (var leaseId in pseudoRootScope.LeaseIds)
            {
                var events = await EventStore.GetEvents <PseudoDHCPv6Lease>(leaseId, 100);

                eventsToApply.AddRange(events);
            }

            rootScope.Load(eventsToApply.OrderBy(x => x.Timestamp));
            return(rootScope);
        }
コード例 #4
0
        public void HandleRequest_OnlyPrefix_LeaseFound_LeaseIsPending()
        {
            Random random = new Random();

            UInt32      prefixId             = random.NextUInt32();
            Byte        prefixLength         = (Byte)random.Next(20, 60);
            IPv6Address prefixNetworkAddress = IPv6Address.FromString("fd01::0");

            var packet = GetRequestPacket(random, out IPv6Address leasedAddress, out DUID clientDuid, out UInt32 iaId, false, new DHCPv6PacketIdentityAssociationPrefixDelegationOption(prefixId, TimeSpan.FromSeconds(random.Next()), TimeSpan.FromSeconds(random.Next()), new DHCPv6PacketSuboption[] {
                new DHCPv6PacketIdentityAssociationPrefixDelegationSuboption(TimeSpan.FromSeconds(random.Next()), TimeSpan.FromSeconds(random.Next()), prefixLength, prefixNetworkAddress, Array.Empty <DHCPv6PacketSuboption>())
            }));

            var resolverInformations = GetMockupResolver(packet, out Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> > scopeResolverMock);

            Guid scopeId = random.NextGuid();
            Guid leaseId = random.NextGuid();

            DHCPv6RootScope rootScope = GetRootScope(scopeResolverMock);

            rootScope.Load(new List <DomainEvent> {
                new DHCPv6ScopeEvents.DHCPv6ScopeAddedEvent(
                    new DHCPv6ScopeCreateInstruction
                {
                    AddressProperties = new DHCPv6ScopeAddressProperties(
                        IPv6Address.FromString("fe80::0"),
                        IPv6Address.FromString("fe80::ff"),
                        new List <IPv6Address> {
                        IPv6Address.FromString("fe80::1")
                    },
                        preferredLifeTime: TimeSpan.FromDays(0.5),
                        validLifeTime: TimeSpan.FromDays(1),
                        addressAllocationStrategy: DHCPv6ScopeAddressProperties.AddressAllocationStrategies.Next),
                    ResolverInformation = resolverInformations,
                    Name = "Testscope",
                    Id   = scopeId,
                }),
                new DHCPv6LeaseCreatedEvent
                {
                    EntityId                      = leaseId,
                    Address                       = leasedAddress,
                    ClientIdentifier              = clientDuid,
                    IdentityAssocationId          = iaId,
                    ScopeId                       = scopeId,
                    StartedAt                     = DateTime.UtcNow,
                    ValidUntil                    = DateTime.UtcNow.AddDays(1),
                    HasPrefixDelegation           = true,
                    PrefixLength                  = prefixLength,
                    IdentityAssocationIdForPrefix = prefixId,
                    DelegatedNetworkAddress       = prefixNetworkAddress,
                },
            });

            DHCPv6Packet result = rootScope.HandleRequest(packet, GetServerPropertiesResolver());

            CheckErrorPacket(packet, leasedAddress, 0, result, DHCPv6PrefixDelegation.FromValues(prefixNetworkAddress, new IPv6SubnetMask(new IPv6SubnetMaskIdentifier(prefixLength)), prefixId), DHCPv6StatusCodes.NoAddrsAvail);

            CheckEventAmount(1, rootScope);
            CheckHandeledEvent(0, packet, result, rootScope, scopeId, DHCPv6RequestHandledEvent.RequestErrors.LeasePendingButOnlyPrefixRequested);
        }
コード例 #5
0
        public void GetLeaseById()
        {
            Random          random    = new Random();
            DHCPv6RootScope rootScope = GetRootScope();

            Guid scopeId = Guid.NewGuid();
            List <DomainEvent> events = new List <DomainEvent>
            {
                new DHCPv6ScopeAddedEvent(new DHCPv6ScopeCreateInstruction
                {
                    Id = scopeId,
                }),
            };

            Int32          leaseAmount = random.Next(3, 10);
            HashSet <Guid> existingIds = new HashSet <Guid>();

            for (int i = 0; i < leaseAmount; i++)
            {
                Guid leaseId = Guid.NewGuid();

                events.Add(new DHCPv6LeaseCreatedEvent
                {
                    ScopeId          = scopeId,
                    EntityId         = leaseId,
                    Address          = random.GetIPv6Address(),
                    ClientIdentifier = new UUIDDUID(random.NextGuid()),
                });

                existingIds.Add(leaseId);
            }

            rootScope.Load(events);

            DHCPv6Scope scope = rootScope.GetRootScopes().First();

            foreach (Guid leaseId in existingIds)
            {
                DHCPv6Lease lease = scope.Leases.GetLeaseById(leaseId);
                Assert.True(lease != DHCPv6Lease.Empty);
            }

            Int32 notExisitngAmount = random.Next(30, 100);

            for (int i = 0; i < notExisitngAmount; i++)
            {
                Guid id = Guid.NewGuid();
                if (existingIds.Contains(id) == true)
                {
                    continue;
                }

                DHCPv6Lease lease = scope.Leases.GetLeaseById(id);
                Assert.True(lease == DHCPv6Lease.Empty);
            }
        }
コード例 #6
0
        public void HandleConfirm_LeaseNotFound(Boolean withAddress, Boolean withPrefix)
        {
            Random random = new Random();

            var packet = GetRelayedConfirmPacket(random, out IPv6Address leasedAddress, out DUID _, out UInt32 iaId, out DHCPv6PrefixDelegation prefix, withAddress, withPrefix);

            var resolverInformations = GetMockupResolver(packet, out Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> > scopeResolverMock);

            Guid     scopeId        = random.NextGuid();
            Guid     leaseId        = random.NextGuid();
            DateTime leaseCreatedAt = DateTime.UtcNow;

            DHCPv6RootScope rootScope = GetRootScope(scopeResolverMock);

            rootScope.Load(new List <DomainEvent> {
                new DHCPv6ScopeEvents.DHCPv6ScopeAddedEvent(
                    new DHCPv6ScopeCreateInstruction
                {
                    AddressProperties = new DHCPv6ScopeAddressProperties(
                        IPv6Address.FromString("fe80::0"),
                        IPv6Address.FromString("fe80::ff"),
                        new List <IPv6Address> {
                        IPv6Address.FromString("fe80::1")
                    },
                        t1: DHCPv6TimeScale.FromDouble(0.5),
                        t2: DHCPv6TimeScale.FromDouble(0.75),
                        preferredLifeTime: TimeSpan.FromDays(0.5),
                        validLifeTime: TimeSpan.FromDays(1),
                        reuseAddressIfPossible: true),
                    ResolverInformation = resolverInformations,
                    Name = "Testscope",
                    Id   = scopeId,
                }),
                new DHCPv6LeaseCreatedEvent
                {
                    EntityId                      = leaseId,
                    Address                       = leasedAddress,
                    ClientIdentifier              = new UUIDDUID(random.NextGuid()),
                    IdentityAssocationId          = iaId,
                    ScopeId                       = scopeId,
                    StartedAt                     = leaseCreatedAt,
                    ValidUntil                    = DateTime.UtcNow.AddDays(1),
                    HasPrefixDelegation           = withPrefix,
                    PrefixLength                  = withPrefix == false ? (Byte)0 : prefix.Mask.Identifier,
                    DelegatedNetworkAddress       = withPrefix == false ? IPv6Address.Empty :  prefix.NetworkAddress,
                    IdentityAssocationIdForPrefix = withPrefix == false ? 0 : prefix.IdentityAssociation,
                },
            });

            DHCPv6Packet result = rootScope.HandleConfirm(packet, GetServerPropertiesResolver());

            Assert.Equal(DHCPv6Packet.Empty, result);

            CheckEventAmount(1, rootScope);
            CheckHandeledEvent(0, packet, result, rootScope, scopeId, DHCPv6ConfirmHandledEvent.ConfirmErrors.LeaseNotFound);
        }
コード例 #7
0
        public async Task Handle_HasNoChildren(Boolean requestedToDeleteChildrenAsWell)
        {
            Random random = new Random();

            Guid id = random.NextGuid();

            String resolverName = random.GetAlphanumericString();

            Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> > scopeResolverMock = new Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> >();

            scopeResolverMock.Setup(x => x.InitializeResolver(It.Is <CreateScopeResolverInformation>(y =>
                                                                                                     y.Typename == resolverName
                                                                                                     ))).Returns(Mock.Of <IScopeResolver <DHCPv6Packet, IPv6Address> >()).Verifiable();

            Mock <ILoggerFactory> factoryMock = new Mock <ILoggerFactory>(MockBehavior.Strict);

            factoryMock.Setup(x => x.CreateLogger(It.IsAny <String>())).Returns(Mock.Of <ILogger <DHCPv6RootScope> >());

            DHCPv6RootScope rootScope = new DHCPv6RootScope(random.NextGuid(), scopeResolverMock.Object, factoryMock.Object);

            rootScope.Load(new[] {
                new DHCPv6ScopeAddedEvent
                {
                    Instructions = new DHCPv6ScopeCreateInstruction
                    {
                        Id = id,
                        ResolverInformation = new CreateScopeResolverInformation
                        {
                            Typename = resolverName,
                        }
                    }
                }
            });


            Mock <IDHCPv6StorageEngine> storageMock = new Mock <IDHCPv6StorageEngine>(MockBehavior.Strict);

            storageMock.Setup(x => x.Save(rootScope)).ReturnsAsync(true).Verifiable();

            var command = new DeleteDHCPv6ScopeCommand(id, requestedToDeleteChildrenAsWell);

            var handler = new DeleteDHCPv6ScopeCommandHandler(storageMock.Object, rootScope,
                                                              Mock.Of <ILogger <DeleteDHCPv6ScopeCommandHandler> >());

            Boolean result = await handler.Handle(command, CancellationToken.None);

            Assert.True(result);

            Assert.Single(rootScope.GetChanges());

            storageMock.Verify();
        }
コード例 #8
0
        public void HandleRenew_OnlyPrefix(Boolean isUnicast)
        {
            Random random = new Random();

            UInt32      prefixId             = random.NextUInt32();
            Byte        prefixLength         = (Byte)random.Next(34, 64);
            IPv6Address prefixNetworkAddress = IPv6Address.FromString("fd01::0");

            DHCPv6PacketOption[] options = new DHCPv6PacketOption[] {
                new DHCPv6PacketIdentityAssociationPrefixDelegationOption(prefixId, TimeSpan.FromSeconds(random.Next()), TimeSpan.FromSeconds(random.Next()), new DHCPv6PacketSuboption[] {
                    new DHCPv6PacketIdentityAssociationPrefixDelegationSuboption(TimeSpan.FromSeconds(random.Next()), TimeSpan.FromSeconds(random.Next()), prefixLength, prefixNetworkAddress, Array.Empty <DHCPv6PacketSuboption>())
                })
            };

            var packet = isUnicast == true?
                         GetRenewPacket(random, out IPv6Address _, out DUID _, out UInt32 _, false, options) :
                             GetRelayedRenewPacket(random, out IPv6Address _, out DUID _, out UInt32 _, false, options);

            var resolverInformations = GetMockupResolver(packet, out Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> > scopeResolverMock);

            Guid scopeId = random.NextGuid();

            DHCPv6RootScope rootScope = GetRootScope(scopeResolverMock);

            rootScope.Load(new List <DomainEvent> {
                new DHCPv6ScopeEvents.DHCPv6ScopeAddedEvent(
                    new DHCPv6ScopeCreateInstruction
                {
                    AddressProperties = new DHCPv6ScopeAddressProperties(
                        IPv6Address.FromString("fe80::01"),
                        IPv6Address.FromString("fe80::ff"),
                        new List <IPv6Address> {
                        IPv6Address.FromString("fe80::02")
                    },
                        preferredLifeTime: TimeSpan.FromDays(0.5),
                        validLifeTime: TimeSpan.FromDays(1),
                        reuseAddressIfPossible: false,
                        prefixDelgationInfo: DHCPv6PrefixDelgationInfo.FromValues(IPv6Address.FromString("2140:1::0"), new IPv6SubnetMaskIdentifier(32), new IPv6SubnetMaskIdentifier(prefixLength)),
                        addressAllocationStrategy: DHCPv6ScopeAddressProperties.AddressAllocationStrategies.Next),
                    ResolverInformation = resolverInformations,
                    Name = "Testscope",
                    Id   = scopeId,
                }),
            });

            DHCPv6Packet result = rootScope.HandleRenew(packet, GetServerPropertiesResolver());

            CheckErrorPacket(packet, IPv6Address.Empty, 0, result, DHCPv6PrefixDelegation.FromValues(prefixNetworkAddress, new IPv6SubnetMask(new IPv6SubnetMaskIdentifier(prefixLength)), prefixId), DHCPv6StatusCodes.NoBinding);
            CheckEventAmount(1, rootScope);

            CheckHandeledEvent(0, packet, result, rootScope, scopeId, DHCPv6RenewHandledEvent.RenewErrors.OnlyPrefixIsNotAllowed);
        }
コード例 #9
0
        public async Task Handle_ScopeNotFound()
        {
            Random random = new();

            Guid scopeId  = random.NextGuid();
            Guid parentId = random.NextGuid();

            String name        = random.GetAlphanumericString();
            String description = random.GetAlphanumericString();

            String resolverName = random.GetAlphanumericString();

            Mock <IScopeResolver <DHCPv6Packet, IPv6Address> > resolverMock = new Mock <IScopeResolver <DHCPv6Packet, IPv6Address> >(MockBehavior.Strict);

            Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> > scopeResolverMock = new Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> >();

            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 <DHCPv6RootScope> >());

            DHCPv6RootScope rootScope = new DHCPv6RootScope(random.NextGuid(), scopeResolverMock.Object, factoryMock.Object);

            rootScope.Load(new DomainEvent[] {
                new DHCPv6ScopeAddedEvent {
                    Instructions = new DHCPv6ScopeCreateInstruction
                    {
                        Name                = random.GetAlphanumericString(),
                        Description         = random.GetAlphanumericString(),
                        Id                  = parentId,
                        ParentId            = null,
                        ResolverInformation = new CreateScopeResolverInformation
                        {
                            Typename = resolverName,
                        },
                        ScopeProperties   = new DHCPv6ScopeProperties(),
                        AddressProperties = DHCPv6ScopeAddressProperties.Empty,
                    }
                },
            });

            var     command = new UpdateDHCPv6ScopeParentCommand(scopeId, parentId);
            var     handler = new UpdateDHCPv6ScopeParentCommandHandler(Mock.Of <IDHCPv6StorageEngine>(MockBehavior.Strict), rootScope, Mock.Of <ILogger <UpdateDHCPv6ScopeParentCommandHandler> >());
            Boolean result  = await handler.Handle(command, CancellationToken.None);

            Assert.False(result);

            scopeResolverMock.Verify();
        }
コード例 #10
0
        public void IsActive()
        {
            Random          random    = new Random();
            DHCPv6RootScope rootScope = GetRootScope();

            Guid scopeId = Guid.NewGuid();

            List <DomainEvent> events = new List <DomainEvent>
            {
                new DHCPv6ScopeAddedEvent(new DHCPv6ScopeCreateInstruction
                {
                    Id = scopeId,
                }),
            };

            Int32 leaseAmount = random.Next(10, 30);
            Dictionary <Guid, Boolean> expectedResults = new Dictionary <Guid, bool>();

            for (int i = 0; i < leaseAmount; i++)
            {
                Guid leaseId = Guid.NewGuid();

                events.Add(new DHCPv6LeaseCreatedEvent
                {
                    ScopeId          = scopeId,
                    EntityId         = leaseId,
                    Address          = random.GetIPv6Address(),
                    ClientIdentifier = new UUIDDUID(random.NextGuid()),
                });

                Boolean addressIsActive = random.NextDouble() > 0.5;
                if (addressIsActive == true)
                {
                    events.Add(new DHCPv6LeaseActivatedEvent(leaseId));
                }

                expectedResults.Add(leaseId, addressIsActive);
            }

            rootScope.Load(events);

            DHCPv6Scope scope = rootScope.GetRootScopes().First();

            foreach (var item in expectedResults)
            {
                DHCPv6Lease lease  = scope.Leases.GetLeaseById(item.Key);
                Boolean     actual = lease.IsActive();
                Assert.Equal(item.Value, actual);
            }
        }
コード例 #11
0
        public void GetSuspenedAddresses()
        {
            Random          random    = new Random();
            DHCPv6RootScope rootScope = GetRootScope();

            Guid scopeId = Guid.NewGuid();

            List <DomainEvent> events = new List <DomainEvent>
            {
                new DHCPv6ScopeAddedEvent(new DHCPv6ScopeCreateInstruction
                {
                    Id = scopeId,
                }),
            };

            Int32 leaseAmount = random.Next(30, 60);
            List <IPv6Address> expectedUsedAddress = new List <IPv6Address>();

            for (int i = 0; i < leaseAmount; i++)
            {
                Guid        leaseId = Guid.NewGuid();
                IPv6Address address = random.GetIPv6Address();

                events.Add(new DHCPv6LeaseCreatedEvent
                {
                    ScopeId          = scopeId,
                    EntityId         = leaseId,
                    Address          = address,
                    ClientIdentifier = new UUIDDUID(random.NextGuid()),
                });

                Boolean shouldBeSuspended = random.NextDouble() > 0.5;
                if (shouldBeSuspended == true)
                {
                    events.Add(new DHCPv6AddressSuspendedEvent(
                                   leaseId,
                                   address, DateTime.UtcNow.AddHours(12)));

                    expectedUsedAddress.Add(address);
                }
            }

            rootScope.Load(events);

            DHCPv6Scope        scope           = rootScope.GetRootScopes().First();
            List <IPv6Address> actualAddresses = scope.Leases.GetSuspendedAddresses().ToList();

            Assert.Equal(expectedUsedAddress.OrderBy(x => x), actualAddresses.OrderBy(x => x));
        }
コード例 #12
0
        public void LimitLeasesPerClient()
        {
            Random          random    = new Random();
            DHCPv6RootScope rootScope = GetRootScope();

            Guid scopeId          = Guid.NewGuid();
            DUID clientIdentifier = new UUIDDUID(random.NextGuid());

            List <DomainEvent> events = new List <DomainEvent>
            {
                new DHCPv6ScopeAddedEvent(new DHCPv6ScopeCreateInstruction
                {
                    Id = scopeId,
                }),
            };

            Int32 leaseAmount = random.Next(20, 40);

            for (int i = 0; i < leaseAmount; i++)
            {
                Guid leaseId = Guid.NewGuid();

                events.Add(new DHCPv6LeaseCreatedEvent
                {
                    ScopeId          = scopeId,
                    EntityId         = leaseId,
                    Address          = random.GetIPv6Address(),
                    ClientIdentifier = clientIdentifier
                });
                events.Add(new DHCPv6LeaseActivatedEvent
                {
                    ScopeId  = scopeId,
                    EntityId = leaseId,
                });
                events.Add(new DHCPv6LeaseRevokedEvent
                {
                    ScopeId  = scopeId,
                    EntityId = leaseId,
                });
            }

            rootScope.Load(events);

            DHCPv6Scope scope  = rootScope.GetRootScopes().First();
            var         leases = scope.Leases.GetAllLeases();

            Assert.Empty(leases);
        }
コード例 #13
0
        public void GetChildScopes()
        {
            Random random = new Random();

            GenerateScopeTree(random, out Dictionary <Guid, List <Guid> > directChildRelations, out Dictionary <Guid, List <Guid> > allChildRelations, out List <DomainEvent> events);

            DHCPv6RootScope rootScope = GetRootScope();

            rootScope.Load(events);

            foreach (var item in directChildRelations)
            {
                DHCPv6Scope scope = rootScope.GetScopeById(item.Key);
                IEnumerable <DHCPv6Scope> childScopes = scope.GetChildScopes();

                List <Guid> childScopesId = childScopes.Select(x => x.Id).ToList();

                Assert.Equal(item.Value.OrderBy(x => x), childScopesId.OrderBy(x => x));
            }
        }
コード例 #14
0
        protected DHCPv6RootScope GetRootScope(Random random, out DHCPv6Packet packet)
        {
            packet = GetSolicitPacket(random, out _, out _);
            var resolverInformations = GetMockupResolver(packet, out Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> > scopeResolverMock);

            Guid scopeId = random.NextGuid();

            Mock <ILoggerFactory> factoryMock = new Mock <ILoggerFactory>(MockBehavior.Strict);

            factoryMock.Setup(x => x.CreateLogger(It.IsAny <String>())).Returns(Mock.Of <ILogger <DHCPv6RootScope> >());

            var rootScope = new DHCPv6RootScope(Guid.NewGuid(), scopeResolverMock.Object, factoryMock.Object);

            rootScope.Load(new List <DomainEvent> {
                new DHCPv6ScopeEvents.DHCPv6ScopeAddedEvent(
                    new DHCPv6ScopeCreateInstruction
                {
                    AddressProperties = new DHCPv6ScopeAddressProperties(
                        IPv6Address.FromString("fe80::0"),
                        IPv6Address.FromString("fe80::ff"),
                        new List <IPv6Address> {
                        IPv6Address.FromString("fe80::1")
                    },
                        t1: DHCPv6TimeScale.FromDouble(0.25),
                        t2: DHCPv6TimeScale.FromDouble(0.75),
                        preferredLifeTime: TimeSpan.FromDays(0.5),
                        validLifeTime: TimeSpan.FromDays(1),
                        rapitCommitEnabled: true,
                        addressAllocationStrategy: DHCPv6ScopeAddressProperties.AddressAllocationStrategies.Next,
                        prefixDelgationInfo: DHCPv6PrefixDelgationInfo.FromValues(
                            IPv6Address.FromString("2a64:40::0"), new IPv6SubnetMaskIdentifier(64), new IPv6SubnetMaskIdentifier(64))
                        ),
                    ResolverInformation = resolverInformations,
                    Name = "Testscope",
                    Id   = scopeId,
                })
            });

            return(rootScope);
        }
コード例 #15
0
        public void HandleRelease_ScopeNotFound_ByAddress()
        {
            Random random = new Random();

            var packet = GetReleasePacket(random, out _, out _, out _, true);

            var resolverInformations = GetMockupResolver(packet, out Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> > scopeResolverMock);

            Guid scopeId = random.NextGuid();

            DHCPv6RootScope rootScope = GetRootScope(scopeResolverMock);

            rootScope.Load(new List <DomainEvent> {
                new DHCPv6ScopeEvents.DHCPv6ScopeAddedEvent(
                    new DHCPv6ScopeCreateInstruction
                {
                    AddressProperties = new DHCPv6ScopeAddressProperties(
                        IPv6Address.FromString("fe80::10"),
                        IPv6Address.FromString("fe80::ff"),
                        new List <IPv6Address> {
                        IPv6Address.FromString("fe80::12")
                    },
                        preferredLifeTime: TimeSpan.FromDays(0.5),
                        validLifeTime: TimeSpan.FromDays(1),
                        reuseAddressIfPossible: false,
                        addressAllocationStrategy: DHCPv6ScopeAddressProperties.AddressAllocationStrategies.Next),
                    ResolverInformation = resolverInformations,
                    Name = "Testscope",
                    Id   = scopeId,
                }),
            });

            DHCPv6Packet result = rootScope.HandleRelease(packet, GetServerPropertiesResolver());

            Assert.Equal(DHCPv6Packet.Empty, result);

            //CheckErrorPacket(leasedAddress, iaId, result, DHCPv6PrefixDelegation.None,DHCPv6StatusCodes.NoBinding);
            CheckEventAmount(1, rootScope);
            CheckHandeledEvent(0, packet, result, rootScope, null, DHCPv6ReleaseHandledEvent.ReleaseError.ScopeNotFound);
        }
コード例 #16
0
        public void GetChildIds()
        {
            Random random = new Random();

            GenerateScopeTree(random, out Dictionary <Guid, List <Guid> > directChildRelations, out Dictionary <Guid, List <Guid> > allChildRelations, out List <DomainEvent> events);

            DHCPv6RootScope rootScope = GetRootScope();

            rootScope.Load(events);

            foreach (var item in directChildRelations)
            {
                DHCPv6Scope        scope           = rootScope.GetScopeById(item.Key);
                IEnumerable <Guid> actualDirectIds = scope.GetChildIds(true);

                Assert.Equal(item.Value.OrderBy(x => x), actualDirectIds.OrderBy(x => x));

                IEnumerable <Guid> allChildIds = scope.GetChildIds(false);

                Assert.Equal(allChildRelations[item.Key].OrderBy(x => x), allChildIds.OrderBy(x => x));
            }
        }
コード例 #17
0
        public void HandleRebind_ScopeFound_ButPseudoResolverUsed()
        {
            Random random = new Random();

            var packet = GetRelayedRebindPacket(random, out IPv6Address _, out _, out _, true);
            var resolverInformations = GetMockupPseudoResolver(out Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> > scopeResolverMock);

            Guid scopeId = random.NextGuid();


            DHCPv6RootScope rootScope = GetRootScope(scopeResolverMock);

            rootScope.Load(new List <DomainEvent> {
                new DHCPv6ScopeEvents.DHCPv6ScopeAddedEvent(
                    new DHCPv6ScopeCreateInstruction
                {
                    AddressProperties = new DHCPv6ScopeAddressProperties(
                        IPv6Address.FromString("fe80::01"),
                        IPv6Address.FromString("fe80::ff"),
                        new List <IPv6Address> {
                        IPv6Address.FromString("fe80::02")
                    },
                        preferredLifeTime: TimeSpan.FromDays(0.5),
                        validLifeTime: TimeSpan.FromDays(1),
                        reuseAddressIfPossible: false,
                        addressAllocationStrategy: DHCPv6ScopeAddressProperties.AddressAllocationStrategies.Next),
                    ResolverInformation = resolverInformations,
                    Name = "Testscope",
                    Id   = scopeId,
                }),
            });

            DHCPv6Packet result = rootScope.HandleRebind(packet, GetServerPropertiesResolver());

            Assert.Equal(DHCPv6Packet.Empty, result);

            CheckEventAmount(1, rootScope);
            CheckHandeledEvent(0, packet, result, rootScope, null, DHCPv6RebindHandledEvent.RebindErrors.ScopeNotFound);
        }
コード例 #18
0
        public void IsCancelable()
        {
            Random          random    = new Random();
            DHCPv6RootScope rootScope = GetRootScope();

            Guid scopeId = Guid.NewGuid();

            rootScope.Load(new[] {
                new DHCPv6ScopeAddedEvent(new DHCPv6ScopeCreateInstruction
                {
                    Id = scopeId,
                })
            });

            Dictionary <DHCPv6Lease, Boolean> expectedResults =
                AddEventsForCancelableLeases(random, scopeId, rootScope);

            foreach (var item in expectedResults)
            {
                DHCPv6Lease lease  = item.Key;
                Boolean     actual = lease.IsCancelable();
                Assert.Equal(item.Value, actual);
            }
        }
コード例 #19
0
        public void HandleRequest_LeaseFound_LeaseIsPending(Boolean withPrefixDelegation)
        {
            Random random = new Random();

            UInt32      prefixId             = random.NextUInt32();
            Byte        prefixLength         = (Byte)random.Next(20, 60);
            IPv6Address prefixNetworkAddress = IPv6Address.FromString("fd01::0");

            DHCPv6PacketOption[] options = Array.Empty <DHCPv6PacketOption>();
            if (withPrefixDelegation == true)
            {
                options = new DHCPv6PacketOption[] {
                    new DHCPv6PacketIdentityAssociationPrefixDelegationOption(prefixId, TimeSpan.FromSeconds(random.Next()), TimeSpan.FromSeconds(random.Next()), Array.Empty <DHCPv6PacketSuboption>())
                };
            }

            var packet = GetRequestPacket(random, out IPv6Address _, out DUID clientDuid, out UInt32 iaId, true, options);
            var resolverInformations = GetMockupResolver(packet, out Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> > scopeResolverMock);

            Guid        scopeId       = random.NextGuid();
            Guid        leaseId       = random.NextGuid();
            IPv6Address leasedAddress = IPv6Address.FromString("fe80::2");

            DHCPv6RootScope rootScope = GetRootScope(scopeResolverMock);

            rootScope.Load(new List <DomainEvent> {
                new DHCPv6ScopeEvents.DHCPv6ScopeAddedEvent(
                    new DHCPv6ScopeCreateInstruction
                {
                    AddressProperties = new DHCPv6ScopeAddressProperties(
                        IPv6Address.FromString("fe80::0"),
                        IPv6Address.FromString("fe80::ff"),
                        new List <IPv6Address> {
                        IPv6Address.FromString("fe80::1")
                    },
                        t1: DHCPv6TimeScale.FromDouble(0.5),
                        t2: DHCPv6TimeScale.FromDouble(0.75),
                        preferredLifeTime: TimeSpan.FromDays(0.5),
                        validLifeTime: TimeSpan.FromDays(1),
                        addressAllocationStrategy: DHCPv6ScopeAddressProperties.AddressAllocationStrategies.Next),
                    ResolverInformation = resolverInformations,
                    Name = "Testscope",
                    Id   = scopeId,
                }),
                new DHCPv6LeaseCreatedEvent
                {
                    EntityId                      = leaseId,
                    Address                       = leasedAddress,
                    ClientIdentifier              = clientDuid,
                    IdentityAssocationId          = iaId,
                    ScopeId                       = scopeId,
                    StartedAt                     = DateTime.UtcNow,
                    ValidUntil                    = DateTime.UtcNow.AddDays(1),
                    HasPrefixDelegation           = withPrefixDelegation,
                    PrefixLength                  = prefixLength,
                    IdentityAssocationIdForPrefix = prefixId,
                    DelegatedNetworkAddress       = prefixNetworkAddress,
                }
            });

            DHCPv6Packet result = rootScope.HandleRequest(packet, GetServerPropertiesResolver());

            CheckPacket(packet, leasedAddress, iaId, result, DHCPv6PacketTypes.REPLY, withPrefixDelegation == false ? DHCPv6PrefixDelegation.None : DHCPv6PrefixDelegation.FromValues(prefixNetworkAddress, new IPv6SubnetMask(new IPv6SubnetMaskIdentifier(prefixLength)), prefixId));

            CheckEventAmount(2, rootScope);
            CheckLeaseActivatedEvent(0, scopeId, leaseId, rootScope);
            CheckHandeledEvent(1, packet, result, rootScope, scopeId, DHCPv6RequestHandledEvent.RequestErrors.NoError);
        }
コード例 #20
0
        public void DHCPv6Scope_ScopePropertiesInherientce()
        {
            Random random = new Random();

            Byte onylGrandParentOptionIdentifier   = 47;
            Byte onlyParentOptionIdentifier        = 55;
            Byte onlyChildOptionIdentifier         = 90;
            Byte overridenByParentOptionIdentifier = 100;
            Byte overridenByChildOptionIdentifier  = 110;
            Byte deletedByChildOptionIdentifier    = 140;

            Dictionary <Byte, String> inputs = new Dictionary <byte, String>
            {
                { onylGrandParentOptionIdentifier, random.GetAlphanumericString() },
                { onlyParentOptionIdentifier, random.GetAlphanumericString() },
                { onlyChildOptionIdentifier, random.GetAlphanumericString() },
                { overridenByParentOptionIdentifier, random.GetAlphanumericString() },
                { overridenByChildOptionIdentifier, random.GetAlphanumericString() },
                { deletedByChildOptionIdentifier, random.GetAlphanumericString() },
            };

            DHCPv6ScopeProperties grantParentProperties = new DHCPv6ScopeProperties(
                new DHCPv6TextScopeProperty(onylGrandParentOptionIdentifier, inputs[onylGrandParentOptionIdentifier]),
                new DHCPv6TextScopeProperty(overridenByParentOptionIdentifier, random.GetAlphanumericString()),
                new DHCPv6TextScopeProperty(overridenByChildOptionIdentifier, random.GetAlphanumericString()),
                new DHCPv6TextScopeProperty(deletedByChildOptionIdentifier, random.GetAlphanumericString())
                );

            DHCPv6ScopeProperties parentProperties = new DHCPv6ScopeProperties(
                new DHCPv6TextScopeProperty(onlyParentOptionIdentifier, inputs[onlyParentOptionIdentifier]),
                new DHCPv6TextScopeProperty(overridenByParentOptionIdentifier, inputs[overridenByParentOptionIdentifier]),
                new DHCPv6TextScopeProperty(deletedByChildOptionIdentifier, random.GetAlphanumericString())
                );

            DHCPv6ScopeProperties childProperties = new DHCPv6ScopeProperties(
                new DHCPv6TextScopeProperty(onlyChildOptionIdentifier, inputs[onlyChildOptionIdentifier]),
                new DHCPv6TextScopeProperty(overridenByChildOptionIdentifier, inputs[overridenByChildOptionIdentifier])
                );

            childProperties.RemoveFromInheritance(deletedByChildOptionIdentifier);

            DHCPv6ScopeProperties expectedProperties = new DHCPv6ScopeProperties(
                new DHCPv6TextScopeProperty(onylGrandParentOptionIdentifier, inputs[onylGrandParentOptionIdentifier]),
                new DHCPv6TextScopeProperty(onlyParentOptionIdentifier, inputs[onlyParentOptionIdentifier]),
                new DHCPv6TextScopeProperty(onlyChildOptionIdentifier, inputs[onlyChildOptionIdentifier]),
                new DHCPv6TextScopeProperty(overridenByParentOptionIdentifier, inputs[overridenByParentOptionIdentifier]),
                new DHCPv6TextScopeProperty(overridenByChildOptionIdentifier, inputs[overridenByChildOptionIdentifier])
                );

            Guid grantParentId = Guid.NewGuid();
            Guid parentId      = Guid.NewGuid();
            Guid childId       = Guid.NewGuid();

            List <DomainEvent> events = new List <DomainEvent>
            {
                new DHCPv6ScopeAddedEvent(new DHCPv6ScopeCreateInstruction
                {
                    Id = grantParentId,
                    ScopeProperties = grantParentProperties,
                }),
                new DHCPv6ScopeAddedEvent(new DHCPv6ScopeCreateInstruction
                {
                    Id              = parentId,
                    ParentId        = grantParentId,
                    ScopeProperties = parentProperties,
                }),
                new DHCPv6ScopeAddedEvent(new DHCPv6ScopeCreateInstruction
                {
                    Id              = childId,
                    ParentId        = parentId,
                    ScopeProperties = childProperties,
                }),
            };

            DHCPv6RootScope rootScope = GetRootScope();

            rootScope.Load(events);

            var scope            = rootScope.GetScopeById(childId);
            var actualProperties = scope.GetScopeProperties();

            Assert.Equal(expectedProperties, actualProperties);
        }
コード例 #21
0
        public void DHCPv6Scope_AddressPropertiesInherientce()
        {
            Random random = new Random();

            for (int i = 0; i < 100; i++)
            {
                IPv6Address        grantParentStart             = random.GetIPv6Address();
                IPv6Address        grantParentEnd               = random.GetIPv6AddressGreaterThan(grantParentStart);
                List <IPv6Address> grantParentExcludedAddresses = random.GetIPv6AddressesBetween(grantParentStart, grantParentEnd);

                DHCPv6TimeScale grantParentT1 = DHCPv6TimeScale.FromDouble(0.2);
                DHCPv6TimeScale grantParentT2 = DHCPv6TimeScale.FromDouble(0.6);
                TimeSpan        grantParentPreferredLifeTime = TimeSpan.FromMinutes(random.Next(10, 30));
                TimeSpan        grantParentValuidLifeTime    = TimeSpan.FromMinutes(random.Next(40, 60));

                Boolean grantParentReuseAddressIfPossible = random.NextBoolean();
                var     grantParentAllocationStrategy     = DHCPv6ScopeAddressProperties.AddressAllocationStrategies.Next;

                Boolean grantParentSupportDirectUnicast = random.NextBoolean();
                Boolean grantParentAcceptDecline        = random.NextBoolean();
                Boolean grantParentInformsAreAllowd     = random.NextBoolean();

                DHCPv6ScopeAddressProperties grantParentProperties = new DHCPv6ScopeAddressProperties(
                    grantParentStart, grantParentEnd, grantParentExcludedAddresses,
                    grantParentT1, grantParentT2,
                    grantParentPreferredLifeTime, grantParentValuidLifeTime,
                    grantParentReuseAddressIfPossible, grantParentAllocationStrategy,
                    grantParentInformsAreAllowd, grantParentAcceptDecline, grantParentInformsAreAllowd,
                    null, DHCPv6PrefixDelgationInfo.FromValues(IPv6Address.FromString("2001:e68:5423:5ffd::0"), new IPv6SubnetMaskIdentifier(64), new IPv6SubnetMaskIdentifier(70)));

                IPv6Address        parentStart             = random.GetIPv6Address();
                IPv6Address        parentEnd               = random.GetIPv6AddressGreaterThan(parentStart);
                List <IPv6Address> parentExcludedAddresses = random.GetIPv6AddressesBetween(parentStart, parentEnd);

                TimeSpan?       parentPreferedLifeTime = null;
                TimeSpan?       parentValuidLifetime   = null;
                DHCPv6TimeScale parentT1 = DHCPv6TimeScale.FromDouble(0.3);
                DHCPv6TimeScale parentT2 = null;

                Boolean?parentReuseAddressIfPossible = null;
                DHCPv6ScopeAddressProperties.AddressAllocationStrategies?parentAllocationStrategy = null;

                Boolean?parentSupportDirectUnicast = null;
                Boolean?parentAcceptDecline        = null;
                Boolean?parentInformsAreAllowd     = null;

                if (random.NextBoolean() == true)
                {
                    parentPreferedLifeTime = TimeSpan.FromMinutes(random.Next());
                }
                if (random.NextBoolean() == true)
                {
                    parentValuidLifetime = TimeSpan.FromMinutes(random.Next());
                }

                if (random.NextBoolean() == true)
                {
                    parentReuseAddressIfPossible = random.NextBoolean();
                }
                if (random.NextBoolean() == true)
                {
                    parentAllocationStrategy = DHCPv6ScopeAddressProperties.AddressAllocationStrategies.Random;
                }
                if (random.NextBoolean() == true)
                {
                    parentSupportDirectUnicast = random.NextBoolean();
                }
                if (random.NextBoolean() == true)
                {
                    parentAcceptDecline = random.NextBoolean();
                }
                if (random.NextBoolean() == true)
                {
                    parentInformsAreAllowd = random.NextBoolean();
                }

                DHCPv6ScopeAddressProperties parentProperties = new DHCPv6ScopeAddressProperties(
                    parentStart, parentEnd, parentExcludedAddresses,
                    parentT1, parentT2,
                    parentPreferedLifeTime, parentValuidLifetime,
                    parentReuseAddressIfPossible, parentAllocationStrategy,
                    parentInformsAreAllowd, parentAcceptDecline, parentInformsAreAllowd,
                    null, DHCPv6PrefixDelgationInfo.FromValues(IPv6Address.FromString("2001:e68:5423:5ffe::0"), new IPv6SubnetMaskIdentifier(64), new IPv6SubnetMaskIdentifier(70))
                    );

                IPv6Address        childStart             = random.GetIPv6Address();
                IPv6Address        childEnd               = random.GetIPv6AddressGreaterThan(childStart);
                List <IPv6Address> childExcludedAddresses = random.GetIPv6AddressesBetween(childStart, childEnd);

                DHCPv6TimeScale childT1 = null;
                DHCPv6TimeScale childT2 = DHCPv6TimeScale.FromDouble(0.9);

                TimeSpan?childPreferredLifeTime = null;
                TimeSpan?childValidLifeTime     = null;

                Boolean?childReuseAddressIfPossible = null;
                DHCPv6ScopeAddressProperties.AddressAllocationStrategies?childAllocationStrategy = null;

                Boolean?childSupportDirectUnicast = random.NextDouble() > 0.5;
                Boolean?childAcceptDecline        = random.NextDouble() > 0.5;
                Boolean?childInformsAreAllowd     = random.NextDouble() > 0.5;

                if (random.NextBoolean() == true)
                {
                    childPreferredLifeTime = TimeSpan.FromMinutes(random.Next());
                }
                if (random.NextBoolean() == true)
                {
                    childValidLifeTime = TimeSpan.FromMinutes(random.Next());
                }
                if (random.NextBoolean() == true)
                {
                    childReuseAddressIfPossible = random.NextBoolean();
                }
                if (random.NextBoolean() == true)
                {
                    childAllocationStrategy = DHCPv6ScopeAddressProperties.AddressAllocationStrategies.Random;
                }
                if (random.NextBoolean() == true)
                {
                    childSupportDirectUnicast = random.NextBoolean();
                }
                if (random.NextBoolean() == true)
                {
                    childAcceptDecline = random.NextBoolean();
                }
                if (random.NextBoolean() == true)
                {
                    childInformsAreAllowd = random.NextBoolean();
                }

                var childPrefixDelegationInfo = DHCPv6PrefixDelgationInfo.FromValues(IPv6Address.FromString("2001:e68:5423:5ffe::0"), new IPv6SubnetMaskIdentifier(64), new IPv6SubnetMaskIdentifier(70));

                DHCPv6ScopeAddressProperties childProperties = new DHCPv6ScopeAddressProperties(
                    childStart, childEnd, childExcludedAddresses,
                    childT1, childT2,
                    childPreferredLifeTime, childValidLifeTime,
                    childReuseAddressIfPossible, childAllocationStrategy,
                    childSupportDirectUnicast, childAcceptDecline, childInformsAreAllowd,
                    null, childPrefixDelegationInfo
                    );

                Guid grantParentId = Guid.NewGuid();
                Guid parentId      = Guid.NewGuid();
                Guid childId       = Guid.NewGuid();

                List <DomainEvent> events = new List <DomainEvent>
                {
                    new DHCPv6ScopeAddedEvent(new DHCPv6ScopeCreateInstruction
                    {
                        Id = grantParentId,
                        AddressProperties = grantParentProperties,
                    }),
                    new DHCPv6ScopeAddedEvent(new DHCPv6ScopeCreateInstruction
                    {
                        Id                = parentId,
                        ParentId          = grantParentId,
                        AddressProperties = parentProperties,
                    }),
                    new DHCPv6ScopeAddedEvent(new DHCPv6ScopeCreateInstruction
                    {
                        Id                = childId,
                        ParentId          = parentId,
                        AddressProperties = childProperties,
                    }),
                };

                DHCPv6RootScope rootScope = GetRootScope();
                rootScope.Load(events);

                DHCPv6Scope scope = rootScope.GetScopeById(childId);
                DHCPv6ScopeAddressProperties actualProperties = scope.GetAddressProperties();

                DHCPv6ScopeAddressProperties expectedProperties = new DHCPv6ScopeAddressProperties(
                    childStart, childEnd, grantParentExcludedAddresses.Union(parentExcludedAddresses).Union(childExcludedAddresses).Where(x => x.IsBetween(childStart, childEnd)),
                    childT1 ?? (parentT1 ?? grantParentT1),
                    childT2 ?? (parentT2 ?? grantParentT2),
                    childPreferredLifeTime.HasValue == true ? childPreferredLifeTime.Value : (parentPreferedLifeTime.HasValue == true ? parentPreferedLifeTime.Value : grantParentPreferredLifeTime),
                    childValidLifeTime.HasValue == true ? childValidLifeTime.Value : (parentValuidLifetime.HasValue == true ? parentValuidLifetime.Value : grantParentValuidLifeTime),
                    childReuseAddressIfPossible.HasValue == true ? childReuseAddressIfPossible.Value : (parentReuseAddressIfPossible.HasValue == true ? parentReuseAddressIfPossible.Value : grantParentReuseAddressIfPossible),
                    childAllocationStrategy.HasValue == true ? childAllocationStrategy.Value : (parentAllocationStrategy.HasValue == true ? parentAllocationStrategy.Value : grantParentAllocationStrategy),
                    childSupportDirectUnicast.HasValue == true ? childSupportDirectUnicast.Value : (parentSupportDirectUnicast.HasValue == true ? parentSupportDirectUnicast.Value : grantParentSupportDirectUnicast),
                    childAcceptDecline.HasValue == true ? childAcceptDecline.Value : (parentAcceptDecline.HasValue == true ? parentAcceptDecline.Value : grantParentAcceptDecline),
                    childInformsAreAllowd.HasValue == true ? childInformsAreAllowd.Value : (parentInformsAreAllowd.HasValue == true ? parentInformsAreAllowd.Value : grantParentInformsAreAllowd),
                    null,
                    childPrefixDelegationInfo
                    );

                Assert.Equal(expectedProperties, actualProperties);
            }
        }
コード例 #22
0
        public void TestNotifcationTriggerForSolicitMessages(Boolean reuse, Boolean prefixRequest, Boolean hadPrefix, Boolean shouldHaveOldBinding, Boolean shouldHaveNewBinding)
        {
            Random random = new Random();
            IPv6HeaderInformation headerInformation =
                new IPv6HeaderInformation(IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2"));

            DUID clientDuid = new UUIDDUID(random.NextGuid());

            UInt32 iaId = random.NextBoolean() == false?random.NextUInt32() : 0;

            IPv6Address leasedAddress = IPv6Address.FromString("fe80::5");

            UInt32 prefixIaId = random.NextBoolean() == false?random.NextUInt32() : 0;

            Byte exisitngPrefixLength = 62;
            DHCPv6PrefixDelegation existingDelegation = DHCPv6PrefixDelegation.FromValues(
                IPv6Address.FromString("2a4c::0"), new IPv6SubnetMask(new IPv6SubnetMaskIdentifier(exisitngPrefixLength)), prefixIaId);

            var packetOptions = new List <DHCPv6PacketOption>
            {
                new DHCPv6PacketIdentifierOption(DHCPv6PacketOptionTypes.ClientIdentifier, clientDuid),
                new DHCPv6PacketIdentityAssociationNonTemporaryAddressesOption(iaId, TimeSpan.Zero, TimeSpan.Zero, Array.Empty <DHCPv6PacketSuboption>()),
            };

            if (prefixRequest == true)
            {
                packetOptions.Add(
                    new DHCPv6PacketIdentityAssociationPrefixDelegationOption(prefixIaId, TimeSpan.Zero, TimeSpan.Zero, Array.Empty <DHCPv6PacketSuboption>()));
            }

            DHCPv6Packet innerPacket = DHCPv6Packet.AsInner(random.NextUInt16(),
                                                            DHCPv6PacketTypes.REBIND, packetOptions);

            DHCPv6Packet packet = DHCPv6RelayPacket.AsOuterRelay(headerInformation, true, 1, random.GetIPv6Address(), random.GetIPv6Address(),
                                                                 new DHCPv6PacketOption[] { new DHCPv6PacketByteArrayOption(DHCPv6PacketOptionTypes.InterfaceId, random.NextBytes(10)) }, innerPacket);

            CreateScopeResolverInformation resolverInformations = new CreateScopeResolverInformation {
                Typename = "something"
            };

            Mock <IScopeResolver <DHCPv6Packet, IPv6Address> > resolverMock = new Mock <IScopeResolver <DHCPv6Packet, IPv6Address> >(MockBehavior.Strict);

            resolverMock.Setup(x => x.PacketMeetsCondition(packet)).Returns(true);
            resolverMock.SetupGet(x => x.HasUniqueIdentifier).Returns(false);

            var scopeResolverMock = new Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> >(MockBehavior.Strict);

            scopeResolverMock.Setup(x => x.InitializeResolver(resolverInformations)).Returns(resolverMock.Object);

            Mock <ILoggerFactory> factoryMock = new Mock <ILoggerFactory>(MockBehavior.Strict);

            factoryMock.Setup(x => x.CreateLogger(It.IsAny <String>())).Returns(Mock.Of <ILogger <DHCPv6RootScope> >());

            var rootScope = new DHCPv6RootScope(Guid.NewGuid(), scopeResolverMock.Object, factoryMock.Object);

            Guid scopeId = random.NextGuid();
            Guid leaseId = random.NextGuid();

            var expetecNewLeaseAddress = IPv6Address.FromString("fe80::0");
            var events = new List <DomainEvent> {
                new DHCPv6ScopeEvents.DHCPv6ScopeAddedEvent(
                    new DHCPv6ScopeCreateInstruction
                {
                    AddressProperties = new DHCPv6ScopeAddressProperties(
                        IPv6Address.FromString("fe80::0"),
                        IPv6Address.FromString("fe80::ff"),
                        new List <IPv6Address> {
                        IPv6Address.FromString("fe80::1")
                    },
                        t1: DHCPv6TimeScale.FromDouble(0.5),
                        t2: DHCPv6TimeScale.FromDouble(0.75),
                        preferredLifeTime: TimeSpan.FromDays(0.5),
                        validLifeTime: TimeSpan.FromDays(1),
                        reuseAddressIfPossible: reuse,
                        prefixDelgationInfo: DHCPv6PrefixDelgationInfo.FromValues(existingDelegation.NetworkAddress, new IPv6SubnetMaskIdentifier(40), new IPv6SubnetMaskIdentifier(64)),
                        addressAllocationStrategy: DHCPv6ScopeAddressProperties.AddressAllocationStrategies.Next),
                    ResolverInformation = resolverInformations,
                    Name = "Testscope",
                    Id   = scopeId,
                }),
                new DHCPv6LeaseCreatedEvent
                {
                    EntityId                      = leaseId,
                    Address                       = leasedAddress,
                    ClientIdentifier              = clientDuid,
                    IdentityAssocationId          = iaId,
                    ScopeId                       = scopeId,
                    HasPrefixDelegation           = hadPrefix,
                    UniqueIdentiifer              = Array.Empty <Byte>(),
                    PrefixLength                  = hadPrefix == true ? exisitngPrefixLength : (Byte)0,
                    IdentityAssocationIdForPrefix = hadPrefix == true ? prefixIaId : (UInt32)0,
                    DelegatedNetworkAddress       = hadPrefix == true ? existingDelegation.NetworkAddress : IPv6Address.Empty,
                    StartedAt                     = DateTime.UtcNow.AddDays(-1),
                    ValidUntil                    = DateTime.UtcNow.AddDays(1),
                },
                new DHCPv6LeaseActivatedEvent
                {
                    EntityId = leaseId,
                    ScopeId  = scopeId,
                }
            };

            rootScope.Load(events);

            var serverPropertiesResolverMock = new Mock <IDHCPv6ServerPropertiesResolver>(MockBehavior.Strict);

            serverPropertiesResolverMock.Setup(x => x.GetServerDuid()).Returns(new UUIDDUID(Guid.NewGuid()));

            var _ = rootScope.HandleRebind(packet, serverPropertiesResolverMock.Object);

            if (shouldHaveNewBinding == false && shouldHaveOldBinding == false)
            {
                CheckEmptyTrigger(rootScope);
            }
            else
            {
                var trigger = CheckTrigger <PrefixEdgeRouterBindingUpdatedTrigger>(rootScope);

                Assert.Equal(scopeId, trigger.ScopeId);

                if (shouldHaveNewBinding == true)
                {
                    Assert.NotNull(trigger.NewBinding);

                    Assert.Equal(64, trigger.NewBinding.Mask.Identifier);
                    if (reuse == true)
                    {
                        Assert.Equal(leasedAddress, trigger.NewBinding.Host);
                    }
                    else
                    {
                        Assert.Equal(expetecNewLeaseAddress, trigger.NewBinding.Host);
                    }
                }
                else
                {
                    Assert.Null(trigger.NewBinding);
                }

                if (shouldHaveOldBinding == true)
                {
                    Assert.NotNull(trigger.OldBinding);

                    Assert.Equal(exisitngPrefixLength, trigger.OldBinding.Mask.Identifier);
                    Assert.Equal(existingDelegation.NetworkAddress, trigger.OldBinding.Prefix);
                    Assert.Equal(leasedAddress, trigger.OldBinding.Host);
                }
                else
                {
                    Assert.Null(trigger.OldBinding);
                }
            }
        }
コード例 #23
0
        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();

            IPv6Address start = random.GetIPv6Address();
            IPv6Address end   = start + 100;

            String resolverName = random.GetAlphanumericString();

            Mock <IScopeResolver <DHCPv6Packet, IPv6Address> > resolverMock = new Mock <IScopeResolver <DHCPv6Packet, IPv6Address> >(MockBehavior.Strict);

            resolverMock.Setup(x => x.GetValues()).Returns(new Dictionary <string, string>());
            Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> > scopeResolverMock = new Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> >();

            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 <DHCPv6RootScope> >());

            DHCPv6RootScope rootScope = new DHCPv6RootScope(random.NextGuid(), scopeResolverMock.Object, factoryMock.Object);

            rootScope.Load(new DomainEvent[] { new DHCPv6ScopeAddedEvent {
                                                   Instructions = new DHCPv6ScopeCreateInstruction
                                                   {
                                                       Name                = random.GetAlphanumericString(),
                                                       Description         = random.GetAlphanumericString(),
                                                       Id                  = scopeId,
                                                       ParentId            = null,
                                                       ResolverInformation = new CreateScopeResolverInformation
                                                       {
                                                           Typename = resolverName,
                                                       },
                                                       ScopeProperties   = new DHCPv6ScopeProperties(),
                                                       AddressProperties = DHCPv6ScopeAddressProperties.Empty,
                                                   }
                                               },
                                               new DHCPv6LeaseCreatedEvent
                                               {
                                                   EntityId                      = leaseId,
                                                   Address                       = start - 100,
                                                   ScopeId                       = scopeId,
                                                   HasPrefixDelegation           = true,
                                                   PrefixLength                  = 64,
                                                   ClientIdentifier              = new UUIDDUID(random.NextGuid()),
                                                   IdentityAssocationIdForPrefix = random.NextUInt32(),
                                                   DelegatedNetworkAddress       = IPv6Address.FromString("fc70::0"),
                                               },
                                               new DHCPv6LeaseActivatedEvent
                                               {
                                                   EntityId = leaseId,
                                                   ScopeId  = scopeId,
                                               } });

            Mock <IDHCPv6StorageEngine> storageMock = new Mock <IDHCPv6StorageEngine>(MockBehavior.Strict);

            storageMock.Setup(x => x.Save(rootScope)).ReturnsAsync(storeResult).Verifiable();

            var command = new UpdateDHCPv6ScopeCommand(scopeId, name, description, null,
                                                       useDynamicTime == false ? new DHCPv6ScopeAddressPropertyReqest
            {
                Start                     = start.ToString(),
                End                       = end.ToString(),
                ExcludedAddresses         = Array.Empty <String>(),
                AcceptDecline             = random.NextBoolean(),
                AddressAllocationStrategy = DHCPv6ScopeAddressPropertyReqest.AddressAllocationStrategies.Next,
                InformsAreAllowd          = random.NextBoolean(),
                RapitCommitEnabled        = random.NextBoolean(),
                ReuseAddressIfPossible    = random.NextBoolean(),
                SupportDirectUnicast      = random.NextBoolean(),
                PreferredLifeTime         = TimeSpan.FromDays(0.5),
                ValidLifeTime             = TimeSpan.FromDays(1),
                PrefixDelgationInfo       = new DHCPv6PrefixDelgationInfoRequest
                {
                    AssingedPrefixLength = 80,
                    Prefix       = "fe80::0",
                    PrefixLength = 64
                },
                T1 = 0.3,
                T2 = 0.65,
            } : new DHCPv6ScopeAddressPropertyReqest
            {
                Start                     = start.ToString(),
                End                       = end.ToString(),
                ExcludedAddresses         = Array.Empty <String>(),
                AcceptDecline             = random.NextBoolean(),
                AddressAllocationStrategy = DHCPv6ScopeAddressPropertyReqest.AddressAllocationStrategies.Next,
                InformsAreAllowd          = random.NextBoolean(),
                RapitCommitEnabled        = random.NextBoolean(),
                ReuseAddressIfPossible    = random.NextBoolean(),
                SupportDirectUnicast      = random.NextBoolean(),
                PrefixDelgationInfo       = new DHCPv6PrefixDelgationInfoRequest
                {
                    AssingedPrefixLength = 80,
                    Prefix       = "fe80::0",
                    PrefixLength = 64
                },
                DynamicRenewTime = new DHCPv6DynamicRenewTimeRequest
                {
                    Hours              = 5,
                    Minutes            = 10,
                    MinutesToEndOfLife = 45,
                    MinutesToRebound   = 35,
                },
            },
                                                       new CreateScopeResolverRequest
            {
                PropertiesAndValues = new Dictionary <String, String>(),
                Typename            = resolverName,
            },
                                                       new[] { new DHCPv6AddressListScopePropertyRequest
                                                               {
                                                                   OptionCode = 24,
                                                                   Type       = Beer.DaAPI.Core.Scopes.DHCPv6.ScopeProperties.DHCPv6ScopePropertyType.AddressList,
                                                                   Addresses  = random.GetIPv6Addresses().Select(x => x.ToString()).ToArray(),
                                                               },
                                                               new DHCPv6AddressListScopePropertyRequest
                                                               {
                                                                   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 == IPv6Address.FromString("fc70::0")
                                                                                 ))).Returns(Task.CompletedTask);
            var handler = new UpdateDHCPv6ScopeCommandHandler(storageMock.Object, serviceBusMock.Object, rootScope,
                                                              Mock.Of <ILogger <UpdateDHCPv6ScopeCommandHandler> >());

            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();


            if (storeResult == true)
            {
                serviceBusMock.Verify();
                Assert.Empty(rootScope.GetTriggers());
            }
            else
            {
                Assert.Single(rootScope.GetTriggers());
            }
        }
コード例 #24
0
        public void HandleRelease_NoLeaseFound(Boolean withPrefixDelegation, Boolean isUnicast)
        {
            Random random = new Random();

            UInt32      prefixId             = random.NextUInt32();
            Byte        prefixLength         = (Byte)random.Next(34, 64);
            IPv6Address prefixNetworkAddress = IPv6Address.FromString("fd01::0");

            DHCPv6PacketOption[] options = Array.Empty <DHCPv6PacketOption>();
            if (withPrefixDelegation == true)
            {
                options = new DHCPv6PacketOption[] {
                    new DHCPv6PacketIdentityAssociationPrefixDelegationOption(prefixId, TimeSpan.FromSeconds(random.Next()), TimeSpan.FromSeconds(random.Next()), new DHCPv6PacketSuboption[] {
                        new DHCPv6PacketIdentityAssociationPrefixDelegationSuboption(TimeSpan.FromSeconds(random.Next()), TimeSpan.FromSeconds(random.Next()), prefixLength, prefixNetworkAddress, Array.Empty <DHCPv6PacketSuboption>())
                    })
                };
            }

            var packet = isUnicast == true?
                         GetReleasePacket(random, out IPv6Address leasedAddress, out _, out UInt32 iaId, true, options) :
                             GetRelayedReleasePacket(random, out leasedAddress, out _, out iaId, true, options);

            var resolverInformations = GetMockupResolver(packet, out Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> > scopeResolverMock);

            Guid scopeId = random.NextGuid();
            Guid leaseId = random.NextGuid();

            DateTime leaseCreatedAt = DateTime.UtcNow;

            DHCPv6RootScope rootScope = GetRootScope(scopeResolverMock);

            rootScope.Load(new List <DomainEvent> {
                new DHCPv6ScopeEvents.DHCPv6ScopeAddedEvent(
                    new DHCPv6ScopeCreateInstruction
                {
                    AddressProperties = new DHCPv6ScopeAddressProperties(
                        IPv6Address.FromString("fe80::01"),
                        IPv6Address.FromString("fe80::ff"),
                        new List <IPv6Address> {
                        IPv6Address.FromString("fe80::02")
                    },
                        preferredLifeTime: TimeSpan.FromDays(0.5),
                        validLifeTime: TimeSpan.FromDays(1),
                        reuseAddressIfPossible: false,
                        prefixDelgationInfo: DHCPv6PrefixDelgationInfo.FromValues(IPv6Address.FromString("2140:1::0"), new IPv6SubnetMaskIdentifier(32), new IPv6SubnetMaskIdentifier(prefixLength)),
                        addressAllocationStrategy: DHCPv6ScopeAddressProperties.AddressAllocationStrategies.Next),
                    ResolverInformation = resolverInformations,
                    Name = "Testscope",
                    Id   = scopeId,
                }),
                new DHCPv6LeaseCreatedEvent
                {
                    EntityId                      = leaseId,
                    Address                       = leasedAddress,
                    ClientIdentifier              = new UUIDDUID(random.NextGuid()),
                    IdentityAssocationId          = iaId,
                    ScopeId                       = scopeId,
                    StartedAt                     = leaseCreatedAt,
                    ValidUntil                    = DateTime.UtcNow.AddDays(1),
                    HasPrefixDelegation           = withPrefixDelegation,
                    PrefixLength                  = prefixLength,
                    IdentityAssocationIdForPrefix = prefixId,
                    DelegatedNetworkAddress       = prefixNetworkAddress,
                },
                new DHCPv6LeaseActivatedEvent
                {
                    EntityId = leaseId,
                    ScopeId  = scopeId,
                }
            });

            DHCPv6Packet result = rootScope.HandleRelease(packet, GetServerPropertiesResolver());

            CheckErrorPacket(packet, leasedAddress, iaId, result, withPrefixDelegation == false ? DHCPv6PrefixDelegation.None : DHCPv6PrefixDelegation.FromValues(prefixNetworkAddress, new IPv6SubnetMask(new IPv6SubnetMaskIdentifier(prefixLength)), prefixId), DHCPv6StatusCodes.NoBinding);

            DHCPv6Lease lease = rootScope.GetScopeById(scopeId).Leases.GetLeaseById(leaseId);

            Assert.Equal(LeaseStates.Active, lease.State);

            CheckEventAmount(1, rootScope);
            CheckHandeledEvent(0, packet, result, rootScope, scopeId, DHCPv6ReleaseHandledEvent.ReleaseError.NoLeaseFound);
        }
コード例 #25
0
        public void GetUsedAddresses()
        {
            Random          random    = new Random();
            DHCPv6RootScope rootScope = GetRootScope();

            Guid scopeId = Guid.NewGuid();

            List <DomainEvent> events = new List <DomainEvent>
            {
                new DHCPv6ScopeAddedEvent(new DHCPv6ScopeCreateInstruction
                {
                    Id = scopeId,
                }),
            };

            Int32 leaseAmount = random.Next(30, 60);
            List <IPv6Address> expectedUsedAddress = new List <IPv6Address>();

            for (int i = 0; i < leaseAmount; i++)
            {
                Guid        leaseId = Guid.NewGuid();
                IPv6Address address = random.GetIPv6Address();

                events.Add(new DHCPv6LeaseCreatedEvent
                {
                    ScopeId          = scopeId,
                    EntityId         = leaseId,
                    Address          = address,
                    ClientIdentifier = new UUIDDUID(random.NextGuid()),
                });

                DomainEvent eventToAdd     = null;
                Boolean     addressIsInUse = true;
                Double      randomValue    = random.NextDouble();
                Double      possiblities   = 5.0;
                if (randomValue < 1 / possiblities)
                {
                    eventToAdd     = new DHCPv6LeaseReleasedEvent(leaseId, false);
                    addressIsInUse = false;
                }
                else if (randomValue < 2 / possiblities)
                {
                    eventToAdd     = new DHCPv6LeaseRevokedEvent(leaseId);
                    addressIsInUse = false;
                }
                else if (randomValue < 3 / possiblities)
                {
                    eventToAdd     = new DHCPv6AddressSuspendedEvent(leaseId, random.GetIPv6Address(), DateTime.UtcNow.AddHours(12));
                    addressIsInUse = false;
                }

                if (eventToAdd != null)
                {
                    events.Add(eventToAdd);
                }

                if (addressIsInUse == true)
                {
                    expectedUsedAddress.Add(address);
                }
            }

            rootScope.Load(events);

            DHCPv6Scope        scope           = rootScope.GetRootScopes().First();
            List <IPv6Address> actualAddresses = scope.Leases.GetUsedAddresses().ToList();

            Assert.Equal(expectedUsedAddress, actualAddresses);
        }
コード例 #26
0
        public async Task HandleRebind_LeaseFound_ReuseIsNotAllowed_TwoPackets(Boolean withPrefixDelegation)
        {
            Random random = new Random();

            UInt32 prefixId = random.NextBoolean() == false?random.NextUInt32() : 0;

            Byte        prefixLength         = (Byte)random.Next(34, 64);
            IPv6Address prefixNetworkAddress = IPv6Address.FromString("fd01::0");

            DHCPv6PacketOption[] options = Array.Empty <DHCPv6PacketOption>();
            if (withPrefixDelegation == true)
            {
                options = new DHCPv6PacketOption[] {
                    new DHCPv6PacketIdentityAssociationPrefixDelegationOption(prefixId, TimeSpan.FromSeconds(random.Next()), TimeSpan.FromSeconds(random.Next()), Array.Empty <DHCPv6PacketSuboption>())
                };
            }

            var packet = GetRelayedRebindPacket(random, out IPv6Address _, out DUID clientDuid, out UInt32 iaId, true, options);

            var resolverInformations = GetMockupResolver(packet, out Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> > scopeResolverMock);

            Guid        scopeId         = random.NextGuid();
            Guid        leaseId         = random.NextGuid();
            IPv6Address leasedAddress   = IPv6Address.FromString("fe80::01");
            IPv6Address expectedAddress = IPv6Address.FromString("fe80::03");

            DateTime leaseCreatedAt = DateTime.UtcNow.AddHours(-2);

            DHCPv6RootScope rootScope = GetRootScope(scopeResolverMock);

            rootScope.Load(new List <DomainEvent> {
                new DHCPv6ScopeEvents.DHCPv6ScopeAddedEvent(
                    new DHCPv6ScopeCreateInstruction
                {
                    AddressProperties = new DHCPv6ScopeAddressProperties(
                        IPv6Address.FromString("fe80::01"),
                        IPv6Address.FromString("fe80::ff"),
                        new List <IPv6Address> {
                        IPv6Address.FromString("fe80::02")
                    },
                        t1: DHCPv6TimeScale.FromDouble(0.5),
                        t2: DHCPv6TimeScale.FromDouble(0.75),
                        preferredLifeTime: TimeSpan.FromDays(0.5),
                        validLifeTime: TimeSpan.FromDays(1),
                        reuseAddressIfPossible: false,
                        prefixDelgationInfo: DHCPv6PrefixDelgationInfo.FromValues(IPv6Address.FromString("2140:1::0"), new IPv6SubnetMaskIdentifier(32), new IPv6SubnetMaskIdentifier(prefixLength)),
                        addressAllocationStrategy: DHCPv6ScopeAddressProperties.AddressAllocationStrategies.Next),
                    ResolverInformation = resolverInformations,
                    Name = "Testscope",
                    Id   = scopeId,
                }),
                new DHCPv6LeaseCreatedEvent
                {
                    EntityId                      = leaseId,
                    Address                       = leasedAddress,
                    ClientIdentifier              = clientDuid,
                    IdentityAssocationId          = iaId,
                    ScopeId                       = scopeId,
                    StartedAt                     = leaseCreatedAt,
                    ValidUntil                    = DateTime.UtcNow.AddDays(1),
                    HasPrefixDelegation           = withPrefixDelegation,
                    PrefixLength                  = prefixLength,
                    IdentityAssocationIdForPrefix = prefixId,
                    DelegatedNetworkAddress       = prefixNetworkAddress,
                },
                new DHCPv6LeaseActivatedEvent
                {
                    EntityId = leaseId,
                    ScopeId  = scopeId,
                }
            });

            Guid serverId = random.NextGuid();

            var revokedLease = rootScope.GetScopeById(scopeId).Leases.GetLeaseById(leaseId);

            DHCPv6Packet result = rootScope.HandleRebind(packet, GetServerPropertiesResolver(serverId));

            await Task.Delay(3000);

            DHCPv6Packet secondResult = rootScope.HandleRebind(packet, GetServerPropertiesResolver(serverId));

            Assert.Equal(result, secondResult);

            DHCPv6Lease lease = CheckLease(0, 1, expectedAddress, scopeId, rootScope, DateTime.UtcNow, clientDuid, iaId, false, withPrefixDelegation);

            CheckPacket(packet, expectedAddress, iaId, result, DHCPv6PacketTypes.REPLY, withPrefixDelegation == false ? DHCPv6PrefixDelegation.None : DHCPv6PrefixDelegation.FromValues(lease.PrefixDelegation.NetworkAddress, new IPv6SubnetMask(new IPv6SubnetMaskIdentifier(prefixLength)), prefixId));

            Assert.False(revokedLease.IsActive());
            Assert.Equal(LeaseStates.Revoked, revokedLease.State);

            CheckEventAmount(5, rootScope);
            CheckRevokedEvent(0, scopeId, leaseId, rootScope);
            CheckLeaseCreatedEvent(1, clientDuid, iaId, scopeId, rootScope, expectedAddress, lease);
            CheckLeaseActivatedEvent(2, scopeId, lease.Id, rootScope);

            CheckHandeledEvent(3, packet, result, rootScope, scopeId, DHCPv6RebindHandledEvent.RebindErrors.NoError);
            CheckHandeledEvent(4, packet, result, rootScope, scopeId, DHCPv6RebindHandledEvent.RebindErrors.NoError);
        }
コード例 #27
0
        public void GetLeasesByScope_OnlyDirect()
        {
            Random random    = new Random();
            Guid   scopeId   = random.NextGuid();
            String scopeName = "Testscope";

            DHCPv6LeaseOverview activeLeaseWithoutPrefix = new DHCPv6LeaseOverview
            {
                Address          = random.GetIPv6Address().ToString(),
                ClientIdentifier = new UUIDDUID(random.NextGuid()),
                ExpectedEnd      = DateTime.UtcNow.AddHours(random.Next(10, 20)),
                Started          = DateTime.UtcNow.AddHours(-random.Next(10, 20)),
                Id               = random.NextGuid(),
                Prefix           = null,
                UniqueIdentifier = random.NextBytes(10),
                State            = LeaseStates.Active,
                Scope            = new ScopeOverview
                {
                    Id   = scopeId,
                    Name = scopeName,
                }
            };

            DHCPv6LeaseOverview expiredLeaseWithPrefix = new DHCPv6LeaseOverview
            {
                Address          = random.GetIPv6Address().ToString(),
                ClientIdentifier = new UUIDDUID(random.NextGuid()),
                ExpectedEnd      = DateTime.UtcNow.AddHours(random.Next(10, 20)),
                Started          = DateTime.UtcNow.AddHours(-random.Next(10, 20)),
                Id     = random.NextGuid(),
                Prefix = new PrefixOverview
                {
                    Address = IPv6Address.FromString("fe70::").ToString(),
                    Mask    = 64,
                },
                UniqueIdentifier = Array.Empty <Byte>(),
                State            = LeaseStates.Inactive,
                Scope            = new ScopeOverview
                {
                    Id   = scopeId,
                    Name = scopeName,
                }
            };

            DHCPv6RootScope rootScope = GetRootScope();

            rootScope.Load(new List <DomainEvent> {
                new DHCPv6ScopeEvents.DHCPv6ScopeAddedEvent(
                    new DHCPv6ScopeCreateInstruction
                {
                    Name = scopeName,
                    Id   = scopeId,
                }),
                new DHCPv6LeaseCreatedEvent
                {
                    EntityId                      = expiredLeaseWithPrefix.Id,
                    Address                       = IPv6Address.FromString(expiredLeaseWithPrefix.Address.ToString()),
                    ClientIdentifier              = expiredLeaseWithPrefix.ClientIdentifier,
                    IdentityAssocationId          = random.NextUInt32(),
                    ScopeId                       = scopeId,
                    StartedAt                     = expiredLeaseWithPrefix.Started,
                    ValidUntil                    = expiredLeaseWithPrefix.ExpectedEnd,
                    HasPrefixDelegation           = true,
                    PrefixLength                  = expiredLeaseWithPrefix.Prefix.Mask,
                    DelegatedNetworkAddress       = IPv6Address.FromString(expiredLeaseWithPrefix.Prefix.Address),
                    IdentityAssocationIdForPrefix = random.NextUInt32(),
                    UniqueIdentiifer              = null
                },
                new DHCPv6LeaseActivatedEvent
                {
                    EntityId = expiredLeaseWithPrefix.Id,
                    ScopeId  = scopeId,
                },
                new DHCPv6LeaseExpiredEvent
                {
                    EntityId = expiredLeaseWithPrefix.Id,
                    ScopeId  = scopeId,
                },
                new DHCPv6LeaseCreatedEvent
                {
                    EntityId             = activeLeaseWithoutPrefix.Id,
                    Address              = IPv6Address.FromString(activeLeaseWithoutPrefix.Address.ToString()),
                    ClientIdentifier     = activeLeaseWithoutPrefix.ClientIdentifier,
                    IdentityAssocationId = random.NextUInt32(),
                    ScopeId              = scopeId,
                    StartedAt            = activeLeaseWithoutPrefix.Started,
                    ValidUntil           = activeLeaseWithoutPrefix.ExpectedEnd,
                    HasPrefixDelegation  = false,
                    UniqueIdentiifer     = activeLeaseWithoutPrefix.UniqueIdentifier
                },
                new DHCPv6LeaseActivatedEvent
                {
                    EntityId = activeLeaseWithoutPrefix.Id,
                    ScopeId  = scopeId,
                },
            });


            var controller = new DHCPv6LeaseController(rootScope, Mock.Of <ILogger <DHCPv6LeaseController> >());

            var actionResult = controller.GetLeasesByScope(scopeId);
            var result       = actionResult.EnsureOkObjectResult <IEnumerable <DHCPv6LeaseOverview> >(true);

            Assert.Equal(new[] { activeLeaseWithoutPrefix, expiredLeaseWithPrefix }, result, new LeaseOverviewEqualityComparer());
        }
コード例 #28
0
        public void IsAddressActive()
        {
            Random          random    = new Random();
            DHCPv6RootScope rootScope = GetRootScope();

            Guid scopeId = Guid.NewGuid();

            List <DomainEvent> events = new List <DomainEvent>
            {
                new DHCPv6ScopeAddedEvent(new DHCPv6ScopeCreateInstruction
                {
                    Id = scopeId,
                }),
            };

            Int32 leaseAmount = random.Next(30, 60);
            Dictionary <IPv6Address, Boolean> expectedUsedAddress = new Dictionary <IPv6Address, bool>();

            for (int i = 0; i < leaseAmount; i++)
            {
                Guid        leaseId = Guid.NewGuid();
                IPv6Address address = random.GetIPv6Address();

                events.Add(new DHCPv6LeaseCreatedEvent
                {
                    ScopeId          = scopeId,
                    EntityId         = leaseId,
                    Address          = address,
                    ClientIdentifier = new UUIDDUID(random.NextGuid()),
                });

                Boolean addressIsInUse = random.NextDouble() > 0.5;
                if (addressIsInUse == true)
                {
                    events.Add(new DHCPv6LeaseActivatedEvent(leaseId));
                }

                expectedUsedAddress.Add(address, addressIsInUse);
            }

            rootScope.Load(events);

            DHCPv6Scope scope = rootScope.GetRootScopes().First();

            foreach (var item in expectedUsedAddress)
            {
                Boolean actual = scope.Leases.IsAddressActive(item.Key);
                Assert.Equal(item.Value, actual);
            }

            Int32 notExistingAddressesAmount = random.Next(30, 50);

            for (int i = 0; i < notExistingAddressesAmount; i++)
            {
                IPv6Address notExisitingAddress = random.GetIPv6Address();
                if (expectedUsedAddress.ContainsKey(notExisitingAddress) == true)
                {
                    continue;
                }

                Boolean actual = scope.Leases.IsAddressActive(notExisitingAddress);
                Assert.False(actual);
            }
        }
コード例 #29
0
        public async Task GetDashboard()
        {
            Random random             = new Random();
            Guid   grantParentScopeId = random.NextGuid();
            Guid   parentScopeId      = random.NextGuid();
            Guid   childScopeId       = random.NextGuid();

            DHCPv6RootScope rootScope = GetDHCPv6RootScope();

            rootScope.Load(new List <DomainEvent>
            {
                new DHCPv6ScopeEvents.DHCPv6ScopeAddedEvent(
                    new DHCPv6ScopeCreateInstruction
                {
                    Name = "grant parent",
                    Id   = grantParentScopeId,
                }),
                new DHCPv6ScopeEvents.DHCPv6ScopeAddedEvent(
                    new DHCPv6ScopeCreateInstruction
                {
                    Name     = "parent",
                    Id       = parentScopeId,
                    ParentId = grantParentScopeId
                }),
                new DHCPv6ScopeEvents.DHCPv6ScopeAddedEvent(
                    new DHCPv6ScopeCreateInstruction
                {
                    Name     = "child",
                    Id       = childScopeId,
                    ParentId = parentScopeId
                }),
            });

            DHCPv4RootScope dhcpv4RootScope = GetDHCPv4RootScope();

            dhcpv4RootScope.Load(new List <DomainEvent>
            {
                new DHCPv4ScopeEvents.DHCPv4ScopeAddedEvent(
                    new DHCPv4ScopeCreateInstruction
                {
                    Name = "grant parent",
                    Id   = grantParentScopeId,
                }),
                new DHCPv4ScopeEvents.DHCPv4ScopeAddedEvent(
                    new DHCPv4ScopeCreateInstruction
                {
                    Name     = "parent",
                    Id       = parentScopeId,
                    ParentId = grantParentScopeId
                }),
                new DHCPv4ScopeEvents.DHCPv4ScopeAddedEvent(
                    new DHCPv4ScopeCreateInstruction
                {
                    Name     = "child",
                    Id       = childScopeId,
                    ParentId = parentScopeId
                }),
            });

            DashboardResponse response = new DashboardResponse
            {
                DHCPv6 = new DHCPOverview <DHCPv6LeaseEntry, DHCPv6PacketHandledEntry>
                {
                    ActiveInterfaces = random.Next(3, 10),
                },
                DHCPv4 = new DHCPOverview <DHCPv4LeaseEntry, DHCPv4PacketHandledEntry>
                {
                    ActiveInterfaces = random.Next(3, 10),
                },
            };

            Int32 expectedPipelineAmount = random.Next(3, 10);

            Mock <IDHCPv6ReadStore> readStoreMock = new Mock <IDHCPv6ReadStore>(MockBehavior.Strict);

            readStoreMock.Setup(x => x.GetDashboardOverview()).ReturnsAsync(response).Verifiable();

            Mock <INotificationEngine> notificationEngineMock = new Mock <INotificationEngine>(MockBehavior.Strict);

            notificationEngineMock.Setup(x => x.GetPipelineAmount()).Returns(expectedPipelineAmount).Verifiable();

            var controller   = new DashboardController(rootScope, dhcpv4RootScope, readStoreMock.Object, notificationEngineMock.Object);
            var actionResult = await controller.GetDashboard();

            var result = actionResult.EnsureOkObjectResult <DashboardResponse>(true);

            Assert.NotNull(result);
            Assert.NotNull(result.DHCPv6);
            Assert.NotNull(result.DHCPv4);

            Assert.Equal(3, result.DHCPv6.ScopeAmount);
            Assert.Equal(response.DHCPv6.ActiveInterfaces, result.DHCPv6.ActiveInterfaces);
            Assert.Equal(expectedPipelineAmount, result.AmountOfPipelines);

            Assert.Equal(3, result.DHCPv4.ScopeAmount);
            Assert.Equal(response.DHCPv4.ActiveInterfaces, result.DHCPv4.ActiveInterfaces);

            readStoreMock.Verify();
        }
コード例 #30
0
        public async Task Handle_WithChildren(Boolean requestedToDeleteChildrenAsWell)
        {
            Random random = new Random();

            Guid grantParentId = random.NextGuid();
            Guid parentId      = random.NextGuid();
            Guid childId       = random.NextGuid();

            String resolverName = random.GetAlphanumericString();

            Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> > scopeResolverMock = new Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> >();

            scopeResolverMock.Setup(x => x.InitializeResolver(It.Is <CreateScopeResolverInformation>(y =>
                                                                                                     y.Typename == resolverName
                                                                                                     ))).Returns(Mock.Of <IScopeResolver <DHCPv6Packet, IPv6Address> >()).Verifiable();

            Mock <ILoggerFactory> factoryMock = new Mock <ILoggerFactory>(MockBehavior.Strict);

            factoryMock.Setup(x => x.CreateLogger(It.IsAny <String>())).Returns(Mock.Of <ILogger <DHCPv6RootScope> >());

            DHCPv6RootScope rootScope = new DHCPv6RootScope(random.NextGuid(), scopeResolverMock.Object, factoryMock.Object);

            rootScope.Load(new[] {
                new DHCPv6ScopeAddedEvent
                {
                    Instructions = new DHCPv6ScopeCreateInstruction
                    {
                        Id = grantParentId,
                        ResolverInformation = new CreateScopeResolverInformation
                        {
                            Typename = resolverName,
                        },
                        AddressProperties = new DHCPv6ScopeAddressProperties(IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2")),
                    }
                },
                new DHCPv6ScopeAddedEvent
                {
                    Instructions = new DHCPv6ScopeCreateInstruction
                    {
                        Id                  = parentId,
                        ParentId            = grantParentId,
                        ResolverInformation = new CreateScopeResolverInformation
                        {
                            Typename = resolverName,
                        },
                        AddressProperties = new DHCPv6ScopeAddressProperties(IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2")),
                    }
                },
                new DHCPv6ScopeAddedEvent
                {
                    Instructions = new DHCPv6ScopeCreateInstruction
                    {
                        Id                  = childId,
                        ParentId            = parentId,
                        ResolverInformation = new CreateScopeResolverInformation
                        {
                            Typename = resolverName,
                        },
                        AddressProperties = new DHCPv6ScopeAddressProperties(IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2")),
                    }
                },
            });


            Mock <IDHCPv6StorageEngine> storageMock = new Mock <IDHCPv6StorageEngine>(MockBehavior.Strict);

            storageMock.Setup(x => x.Save(rootScope)).ReturnsAsync(true).Verifiable();

            var command = new DeleteDHCPv6ScopeCommand(parentId, requestedToDeleteChildrenAsWell);

            var handler = new DeleteDHCPv6ScopeCommandHandler(storageMock.Object, rootScope,
                                                              Mock.Of <ILogger <DeleteDHCPv6ScopeCommandHandler> >());

            Boolean result = await handler.Handle(command, CancellationToken.None);

            Assert.True(result);

            var changes = rootScope.GetChanges();

            if (requestedToDeleteChildrenAsWell == true)
            {
                Assert.Null(rootScope.GetScopeById(childId));
                Assert.Equal(2, changes.Count());

                var firstEvent = changes.ElementAt(0) as DHCPv6ScopeDeletedEvent;
                Assert.Equal(childId, firstEvent.EntityId);

                var secondEvent = changes.ElementAt(1) as DHCPv6ScopeDeletedEvent;
                Assert.Equal(parentId, secondEvent.EntityId);
            }
            else
            {
                Assert.Single(changes);
            }

            Assert.Null(rootScope.GetScopeById(parentId));
            Assert.NotNull(rootScope.GetScopeById(grantParentId));

            storageMock.Verify();
        }