Exemplo n.º 1
0
        public void DHCPv4Lease_IsCancelable()
        {
            Random          random    = new Random();
            DHCPv4RootScope rootScope = GetRootScope();

            Guid scopeId = Guid.NewGuid();

            rootScope.Load(new[] {
                new DHCPv4ScopeAddedEvent(new DHCPv4ScopeCreateInstruction
                {
                    Id = scopeId,
                }),
            });

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


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

            foreach (var item in expectedResults)
            {
                DHCPv4Lease lease  = item.Key;
                Boolean     actual = lease.IsCancelable();
                Assert.Equal(item.Value, actual);
            }
        }
Exemplo n.º 2
0
        public void TestInform_RootScopeAcceptInforms()
        {
            Random random = new Random();

            IPv4Address start         = random.GetIPv4Address();
            IPv4Address end           = random.GetIPv4AddressGreaterThan(start);
            IPv4Address sourceAddress = random.GetIPv4AddressBetween(start, end);

            DHCPv4Packet input = GetInformPacket(random, sourceAddress);

            DHCPv4RootScope rootScope = GetRootScope();

            Guid scopeId = Guid.NewGuid();

            rootScope.Load(new List <DomainEvent> {
                new DHCPv4ScopeAddedEvent(new DHCPv4ScopeCreateInstruction
                {
                    AddressProperties = new DHCPv4ScopeAddressProperties(start, end, new List <IPv4Address>(), informsAreAllowd: true),
                    Id = scopeId,
                })
            });

            DHCPv4Packet result = rootScope.HandleInform(input);

            DHCPv4InformHandledEvent domainEvent = TestResult <DHCPv4InformHandledEvent>(
                input, result, false, true, scopeId, rootScope);

            Assert.Equal(InformErros.NoError, domainEvent.Error);
        }
Exemplo n.º 3
0
        public async Task <DHCPv4RootScope> GetRootScope()
        {
            DHCPv4RootScope rootScope = new DHCPv4RootScope(_rootScopeid, Provider.GetRequiredService <IScopeResolverManager <DHCPv4Packet, IPv4Address> >(), Provider.GetRequiredService <ILoggerFactory>());

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

            List <DomainEvent> eventsToApply = new();

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

                eventsToApply.AddRange(events);
            }

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

                eventsToApply.AddRange(events);
            }

            rootScope.Load(eventsToApply.OrderBy(x => x.Timestamp));
            return(rootScope);
        }
Exemplo n.º 4
0
        public async Task GetHandledDHCPv4PacketByScopeId()
        {
            Random random = new Random();

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

            DHCPv4RootScope rootScope = GetRootScope();

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

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

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

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

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

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

            readStoreMock.Verify();
        }
Exemplo n.º 5
0
        public void HandleInform_InformsAreAllowed()
        {
            Random      random        = new Random();
            IPv4Address clientAddress = IPv4Address.FromString("192.168.178.10");

            IPv4HeaderInformation headerInformation =
                new IPv4HeaderInformation(clientAddress, IPv4Address.FromString("192.168.178.1"));

            Byte[] clientMacAdress = random.NextBytes(6);

            DHCPv4Packet requestPacket = new DHCPv4Packet(
                headerInformation, clientMacAdress, (UInt32)random.Next(),
                IPv4Address.Empty, IPv4Address.Empty, clientAddress,
                DHCPv4PacketFlags.Unicast,
                new DHCPv4PacketMessageTypeOption(DHCPv4MessagesTypes.Inform)
                );

            Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> > scopeResolverMock =
                new Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict);

            var resolverInformations = new CreateScopeResolverInformation
            {
                Typename = nameof(DHCPv4RelayAgentSubnetResolver),
            };

            Mock <IScopeResolver <DHCPv4Packet, IPv4Address> > resolverMock = new Mock <IScopeResolver <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict);

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

            Guid scopeId = random.NextGuid();

            DHCPv4RootScope rootScope = GetRootScope(scopeResolverMock);

            rootScope.Load(new List <DomainEvent> {
                new DHCPv4ScopeEvents.DHCPv4ScopeAddedEvent(
                    new DHCPv4ScopeCreateInstruction
                {
                    AddressProperties = new DHCPv4ScopeAddressProperties(
                        IPv4Address.FromString("192.168.178.1"),
                        IPv4Address.FromString("192.168.178.255"),
                        new List <IPv4Address> {
                        IPv4Address.FromString("192.168.178.1")
                    },
                        informsAreAllowd: true
                        ),
                    ResolverInformation = resolverInformations,
                    Name = "Testscope",
                    Id   = scopeId,
                })
            });

            DHCPv4Packet result = rootScope.HandleInform(requestPacket);

            CheckAcknowledgePacket(clientAddress, result);

            CheckEventAmount(1, rootScope);
            CheckHandeledEvent(0, InformErros.NoError, requestPacket, result, rootScope);
        }
Exemplo n.º 6
0
        public void DHCPv4Leases_GetLeaseById()
        {
            Random          random    = new Random();
            DHCPv4RootScope rootScope = GetRootScope();

            Guid scopeId = Guid.NewGuid();
            List <DomainEvent> events = new List <DomainEvent>
            {
                new DHCPv4ScopeAddedEvent(new DHCPv4ScopeCreateInstruction
                {
                    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 DHCPv4LeaseCreatedEvent
                {
                    ScopeId        = scopeId,
                    EntityId       = leaseId,
                    Address        = random.GetIPv4Address(),
                    ClientIdenfier = DHCPv4ClientIdentifier.FromHwAddress(random.NextBytes(6)).GetBytes(),
                });

                existingIds.Add(leaseId);
            }

            rootScope.Load(events);

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

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

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

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

                DHCPv4Lease lease = scope.Leases.GetLeaseById(id);
                Assert.True(lease == DHCPv4Lease.Empty);
            }
        }
Exemplo n.º 7
0
        public void TestInform_RandomScopeAcceptInforms()
        {
            Random random = new Random();

            IPv4Address start         = random.GetIPv4Address();
            IPv4Address end           = random.GetIPv4AddressGreaterThan(start);
            IPv4Address sourceAddress = random.GetIPv4AddressBetween(start, end);

            List <Tuple <IPv4Address, IPv4Address> > existingRanges = new List <Tuple <IPv4Address, IPv4Address> >
            {
                new Tuple <IPv4Address, IPv4Address>(start, end),
            };

            DHCPv4Packet input = GetInformPacket(random, sourceAddress);

            Int32 rootScopeAmount     = random.Next(3, 10);
            List <DomainEvent> events = new List <DomainEvent>();

            for (int i = 0; i < rootScopeAmount; i++)
            {
                Guid rootScopeId = Guid.NewGuid();
                Tuple <IPv4Address, IPv4Address> addressRange = random.GenerateUniqueAddressRange(existingRanges);

                events.Add(new DHCPv4ScopeAddedEvent(new DHCPv4ScopeCreateInstruction
                {
                    Id = rootScopeId,
                    AddressProperties = new DHCPv4ScopeAddressProperties
                                            (addressRange.Item1, addressRange.Item2, Array.Empty <IPv4Address>(), informsAreAllowd: true)
                }));

                GenerateScopeTree(
                    random.NextDouble(), random,
                    rootScopeId, existingRanges, events);
            }

            Int32 randomScopeIndex = random.Next(0, events.Count);
            DHCPv4ScopeAddedEvent corelatedScopeEvent = (DHCPv4ScopeAddedEvent)events[randomScopeIndex];

            corelatedScopeEvent.Instructions.AddressProperties = new DHCPv4ScopeAddressProperties
                                                                     (start, end, Array.Empty <IPv4Address>(), informsAreAllowd: true);

            Guid scopeId = corelatedScopeEvent.Instructions.Id;

            DHCPv4RootScope rootScope = GetRootScope();

            rootScope.Load(events);

            DHCPv4Packet result = rootScope.HandleInform(input);

            DHCPv4InformHandledEvent domainEvent = TestResult <DHCPv4InformHandledEvent>(
                input, result, false, true, scopeId, rootScope);

            Assert.Equal(InformErros.NoError, domainEvent.Error);
        }
Exemplo n.º 8
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 <DHCPv4Packet, IPv4Address> > resolverMock = new Mock <IScopeResolver <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict);

            Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> > scopeResolverMock = new Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> >();

            scopeResolverMock.Setup(x => x.InitializeResolver(It.Is <CreateScopeResolverInformation>(y =>
                                                                                                     y.Typename == resolverName
                                                                                                     ))).Returns(resolverMock.Object).Verifiable();

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

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

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

            rootScope.Load(new DomainEvent[] {
                new DHCPv4ScopeAddedEvent {
                    Instructions = new DHCPv4ScopeCreateInstruction
                    {
                        Name                = random.GetAlphanumericString(),
                        Description         = random.GetAlphanumericString(),
                        Id                  = parentId,
                        ParentId            = null,
                        ResolverInformation = new CreateScopeResolverInformation
                        {
                            Typename = resolverName,
                        },
                        ScopeProperties   = new DHCPv4ScopeProperties(),
                        AddressProperties = DHCPv4ScopeAddressProperties.Empty,
                    }
                },
            });

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

            Assert.False(result);

            scopeResolverMock.Verify();
        }
Exemplo n.º 9
0
        public async Task Handle_HasNoChildren(Boolean requestedToDeleteChildrenAsWell)
        {
            Random random = new Random();

            Guid id = random.NextGuid();

            String resolverName = random.GetAlphanumericString();

            Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> > scopeResolverMock = new Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> >();

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

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

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

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

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

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

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

            var command = new DeleteDHCPv4ScopeCommand(id, requestedToDeleteChildrenAsWell);

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

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

            Assert.True(result);

            Assert.Single(rootScope.GetChanges());

            storageMock.Verify();
        }
Exemplo n.º 10
0
        public void DHCPv4Lease_IsActive()
        {
            Random          random    = new Random();
            DHCPv4RootScope rootScope = GetRootScope();

            Guid scopeId = Guid.NewGuid();

            List <DomainEvent> events = new List <DomainEvent>
            {
                new DHCPv4ScopeAddedEvent(new DHCPv4ScopeCreateInstruction
                {
                    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 DHCPv4LeaseCreatedEvent
                {
                    ScopeId        = scopeId,
                    EntityId       = leaseId,
                    Address        = random.GetIPv4Address(),
                    ClientIdenfier = DHCPv4ClientIdentifier.FromHwAddress(random.NextBytes(6)).GetBytes(),
                });

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

                expectedResults.Add(leaseId, addressIsActive);
            }

            rootScope.Load(events);

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

            foreach (var item in expectedResults)
            {
                DHCPv4Lease lease  = scope.Leases.GetLeaseById(item.Key);
                Boolean     actual = lease.IsActive();
                Assert.Equal(item.Value, actual);
            }
        }
Exemplo n.º 11
0
        public void DHCPv4Leases_GetSuspenedAddresses()
        {
            Random          random    = new Random();
            DHCPv4RootScope rootScope = GetRootScope();

            Guid scopeId = Guid.NewGuid();

            List <DomainEvent> events = new List <DomainEvent>
            {
                new DHCPv4ScopeAddedEvent(new DHCPv4ScopeCreateInstruction
                {
                    Id = scopeId,
                }),
            };

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

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

                events.Add(new DHCPv4LeaseCreatedEvent
                {
                    ScopeId        = scopeId,
                    EntityId       = leaseId,
                    Address        = address,
                    ClientIdenfier = DHCPv4ClientIdentifier.FromHwAddress(random.NextBytes(6)).GetBytes(),
                });

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

                    expectedUsedAddress.Add(address);
                }
            }

            rootScope.Load(events);

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

            Assert.Equal(expectedUsedAddress.OrderBy(x => x), actualAddresses.OrderBy(x => x));
        }
Exemplo n.º 12
0
        public void DHCPv4Scope_GetChildScopes()
        {
            Random random = new Random();

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

            DHCPv4RootScope rootScope = GetRootScope();

            rootScope.Load(events);

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

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

                Assert.Equal(item.Value.OrderBy(x => x), childScopesId.OrderBy(x => x));
            }
        }
Exemplo n.º 13
0
        public void DHCPv4Scope_GetChildIds()
        {
            Random random = new Random();

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

            DHCPv4RootScope rootScope = GetRootScope();

            rootScope.Load(events);

            foreach (var item in directChildRelations)
            {
                DHCPv4Scope        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));
            }
        }
Exemplo n.º 14
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();

            IPv4Address start = random.GetIPv4Address();
            IPv4Address end   = start + 100;

            String resolverName = random.GetAlphanumericString();

            Mock <IScopeResolver <DHCPv4Packet, IPv4Address> > resolverMock = new Mock <IScopeResolver <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict);

            resolverMock.Setup(x => x.GetValues()).Returns(new Dictionary <String, String>());

            Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> > scopeResolverMock = new Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> >();

            scopeResolverMock.Setup(x => x.IsResolverInformationValid(It.Is <CreateScopeResolverInformation>(y =>
                                                                                                             y.Typename == resolverName
                                                                                                             ))).Returns(true).Verifiable();
            scopeResolverMock.Setup(x => x.InitializeResolver(It.Is <CreateScopeResolverInformation>(y =>
                                                                                                     y.Typename == resolverName
                                                                                                     ))).Returns(resolverMock.Object).Verifiable();

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

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

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

            rootScope.Load(new DomainEvent[] { new DHCPv4ScopeAddedEvent {
                                                   Instructions = new DHCPv4ScopeCreateInstruction
                                                   {
                                                       Name                = random.GetAlphanumericString(),
                                                       Description         = random.GetAlphanumericString(),
                                                       Id                  = scopeId,
                                                       ParentId            = null,
                                                       ResolverInformation = new CreateScopeResolverInformation
                                                       {
                                                           Typename = resolverName,
                                                       },
                                                       ScopeProperties   = new DHCPv4ScopeProperties(),
                                                       AddressProperties = DHCPv4ScopeAddressProperties.Empty,
                                                   }
                                               },
                                               new DHCPv4LeaseCreatedEvent
                                               {
                                                   EntityId       = leaseId,
                                                   Address        = start - 100,
                                                   ScopeId        = scopeId,
                                                   ClientIdenfier = DHCPv4ClientIdentifier.FromDuid(1, new UUIDDUID(random.NextGuid()), random.NextBytes(6)).GetBytes(),
                                               },
                                               new DHCPv4LeaseActivatedEvent
                                               {
                                                   EntityId = leaseId,
                                                   ScopeId  = scopeId,
                                               } });

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

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

            var command = new UpdateDHCPv4ScopeCommand(scopeId, name, description, null,
                                                       useDynamicTime == false ? new DHCPv4ScopeAddressPropertyReqest
            {
                Start                     = start.ToString(),
                End                       = end.ToString(),
                ExcludedAddresses         = Array.Empty <String>(),
                AcceptDecline             = random.NextBoolean(),
                AddressAllocationStrategy = DHCPv4ScopeAddressPropertyReqest.AddressAllocationStrategies.Next,
                InformsAreAllowd          = random.NextBoolean(),
                ReuseAddressIfPossible    = random.NextBoolean(),
                SupportDirectUnicast      = random.NextBoolean(),
                PreferredLifetime         = TimeSpan.FromDays(0.5),
                RenewalTime               = TimeSpan.FromDays(0.25),
                LeaseTime                 = TimeSpan.FromDays(1),
                MaskLength                = (Byte)random.Next(10, 29),
            } : new DHCPv4ScopeAddressPropertyReqest
            {
                Start                     = start.ToString(),
                End                       = end.ToString(),
                ExcludedAddresses         = Array.Empty <String>(),
                AcceptDecline             = random.NextBoolean(),
                AddressAllocationStrategy = DHCPv4ScopeAddressPropertyReqest.AddressAllocationStrategies.Next,
                InformsAreAllowd          = random.NextBoolean(),
                ReuseAddressIfPossible    = random.NextBoolean(),
                SupportDirectUnicast      = random.NextBoolean(),
                DynamicRenewTime          = new DHCPv4DynamicRenewTimeRequest
                {
                    Hours              = 5,
                    Minutes            = 10,
                    MinutesToEndOfLife = 45,
                    MinutesToRebound   = 35,
                },
                MaskLength = (Byte)random.Next(10, 29),
            }
                                                       ,
                                                       new CreateScopeResolverRequest
            {
                PropertiesAndValues = new Dictionary <String, String>(),
                Typename            = resolverName,
            },
                                                       new DHCPv4ScopePropertyRequest[] {
                new DHCPv4AddressListScopePropertyRequest
                {
                    OptionCode = 24,
                    Type       = DHCPv4ScopePropertyType.AddressList,
                    Addresses  = random.GetIPv4Addresses().Select(x => x.ToString()).ToArray(),
                },
                new DHCPv4AddressScopePropertyRequest
                {
                    OptionCode = 25,
                    Type       = DHCPv4ScopePropertyType.Address,
                    Address    = random.GetIPv4Address().ToString()
                },
                new DHCPv4BooleanScopePropertyRequest
                {
                    OptionCode = 26,
                    Type       = DHCPv4ScopePropertyType.Boolean,
                    Value      = random.NextBoolean()
                },
                new DHCPv4NumericScopePropertyRequest
                {
                    OptionCode  = 27,
                    Type        = DHCPv4ScopePropertyType.UInt16,
                    NumericType = DHCPv4NumericValueTypes.UInt16,
                    Value       = (UInt16)random.NextUInt16()
                },
                new DHCPv4TextScopePropertyRequest
                {
                    OptionCode = 28,
                    Type       = DHCPv4ScopePropertyType.Text,
                    Value      = random.GetAlphanumericString()
                },
                new DHCPv4TimeScopePropertyRequest
                {
                    OptionCode = 29,
                    Type       = DHCPv4ScopePropertyType.Time,
                    Value      = TimeSpan.FromSeconds(random.Next(10, 20))
                },
                new DHCPv4AddressListScopePropertyRequest
                {
                    OptionCode = 64,
                    MarkAsRemovedInInheritance = true,
                }
            }
                                                       );

            var serviceBusMock = new Mock <IServiceBus>(MockBehavior.Strict);

            serviceBusMock.Setup(x => x.Publish(It.Is <NewTriggerHappendMessage>(y => y.Triggers.Count() == 1 &&
                                                                                 ((PrefixEdgeRouterBindingUpdatedTrigger)y.Triggers.First()).OldBinding.Prefix == IPv4Address.FromString("fc70::0")
                                                                                 ))).Returns(Task.CompletedTask);
            var handler = new UpdateDHCPv4ScopeCommandHandler(storageMock.Object, serviceBusMock.Object, rootScope,
                                                              Mock.Of <ILogger <UpdateDHCPv4ScopeCommandHandler> >());

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

            Assert.Equal(storeResult, result);

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

            Assert.Equal(name, scope.Name);
            Assert.Equal(description, scope.Description);
            Assert.NotNull(scope.Resolver);
            Assert.Equal(start, scope.AddressRelatedProperties.Start);

            Assert.True(scope.Properties.IsMarkedAsRemovedFromInheritance(64));
            Assert.False(scope.Properties.IsMarkedAsRemovedFromInheritance(24));

            if (useDynamicTime == true)
            {
                Assert.True(scope.AddressRelatedProperties.UseDynamicRewnewTime);
                Assert.Equal(5, scope.AddressRelatedProperties.DynamicRenewTime.Hour);
            }
            else
            {
                Assert.False(scope.AddressRelatedProperties.UseDynamicRewnewTime);
            }

            scopeResolverMock.Verify();
            storageMock.Verify();

            serviceBusMock.Verify();
            Assert.Empty(rootScope.GetTriggers());
        }
Exemplo n.º 15
0
        public void TestInform_CheckReponsePacket()
        {
            Random random = new Random();

            IPv4Address start              = random.GetIPv4Address();
            IPv4Address end                = random.GetIPv4AddressGreaterThan(start);
            IPv4Address sourceAddress      = random.GetIPv4AddressBetween(start, end);
            IPv4Address destinationAddress = random.GetIPv4AddressBetween(start, end);

            DHCPv4Packet input = GetInformPacket(random, sourceAddress, destinationAddress);

            List <DHCPv4ScopeProperty> scopeProperties = random.GenerateProperties(new List <DHCPv4OptionTypes>
            {
                DHCPv4OptionTypes.RebindingTimeValue,
                DHCPv4OptionTypes.RenewalTimeValue,
                DHCPv4OptionTypes.IPAddressLeaseTime,
                DHCPv4OptionTypes.ServerIdentifier,
                DHCPv4OptionTypes.MessageType,
            });

            DHCPv4RootScope rootScope = GetRootScope();

            Guid scopeId = Guid.NewGuid();

            rootScope.Load(new List <DomainEvent> {
                new DHCPv4ScopeAddedEvent(new DHCPv4ScopeCreateInstruction
                {
                    AddressProperties = new DHCPv4ScopeAddressProperties(start, end, new List <IPv4Address>(),
                                                                         informsAreAllowd: true,
                                                                         renewalTime: TimeSpan.FromMinutes(random.Next(3, 10)),
                                                                         preferredLifetime: TimeSpan.FromMinutes(random.Next(20, 30)),
                                                                         leaseTime: TimeSpan.FromMinutes(random.Next(40, 60))
                                                                         ),
                    Id = scopeId,
                    ScopeProperties = new DHCPv4ScopeProperties(scopeProperties)
                })
            });

            DHCPv4Packet result = rootScope.HandleInform(input);

            Assert.NotEqual(DHCPv4Packet.Empty, result);

            Assert.Equal(sourceAddress, result.Header.Destionation);
            Assert.Equal(destinationAddress, result.Header.Source);

            Assert.Equal(DHCPv4MessagesTypes.Acknowledge, result.MessageType);
            Assert.Equal(input.ClientHardwareAddress, result.ClientHardwareAddress);
            Assert.Equal(input.HardwareAddressLength, result.HardwareAddressLength);
            Assert.Equal(input.HardwareType, result.HardwareType);

            Assert.Equal(0, result.Hops);
            Assert.Equal(0, result.SecondsElapsed);

            Assert.Equal(input.TransactionId, result.TransactionId);
            Assert.Equal(String.Empty, result.FileName);
            Assert.Equal(String.Empty, result.ServerHostname);

            Assert.Equal(DHCPv4PacketFlags.Unicast, result.Flags);
            Assert.Equal(DHCPv4PacketOperationCodes.BootReply, result.OpCode);

            Assert.Equal(IPv4Address.Empty, result.GatewayIPAdress);
            Assert.Equal(IPv4Address.Empty, result.YourIPAdress);
            Assert.Equal(IPv4Address.Empty, result.ServerIPAdress);
            Assert.Equal(input.ClientIPAdress, result.ClientIPAdress);

            Assert.Equal(input.ClientIPAdress, result.Header.Destionation);

            // no time values
            Assert.False(IsOptionPresentend(result, DHCPv4OptionTypes.RebindingTimeValue));
            Assert.False(IsOptionPresentend(result, DHCPv4OptionTypes.RenewalTimeValue));
            Assert.False(IsOptionPresentend(result, DHCPv4OptionTypes.IPAddressLeaseTime));

            // server identifier
            Assert.True(IsOptionPresentend(result, DHCPv4OptionTypes.ServerIdentifier));
            Assert.True(HasOptionThisIPv4Adress(result, DHCPv4OptionTypes.ServerIdentifier, destinationAddress));

            foreach (var item in scopeProperties)
            {
                Assert.True(IsOptionPresentend(result, item.OptionIdentifier));
                DHCPv4PacketOption existingOption = result.GetOptionByIdentifier(item.OptionIdentifier);
                Assert.NotEqual(DHCPv4PacketOption.NotPresented, existingOption);

                ChecKIfPropertyCorrelatesToOption(item, existingOption);
            }
        }
Exemplo n.º 16
0
        public void DHCPv4Leases_IsAddressActive()
        {
            Random          random    = new Random();
            DHCPv4RootScope rootScope = GetRootScope();

            Guid scopeId = Guid.NewGuid();

            List <DomainEvent> events = new List <DomainEvent>
            {
                new DHCPv4ScopeAddedEvent(new DHCPv4ScopeCreateInstruction
                {
                    Id = scopeId,
                }),
            };

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

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

                events.Add(new DHCPv4LeaseCreatedEvent
                {
                    ScopeId        = scopeId,
                    EntityId       = leaseId,
                    Address        = address,
                    ClientIdenfier = DHCPv4ClientIdentifier.FromHwAddress(random.NextBytes(6)).GetBytes(),
                });

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

                expectedUsedAddress.Add(address, addressIsInUse);
            }

            rootScope.Load(events);

            DHCPv4Scope 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++)
            {
                IPv4Address notExisitingAddress = random.GetIPv4Address();
                if (expectedUsedAddress.ContainsKey(notExisitingAddress) == true)
                {
                    continue;
                }

                Boolean actual = scope.Leases.IsAddressActive(notExisitingAddress);
                Assert.False(actual);
            }
        }
Exemplo n.º 17
0
        public void GetLeasesByScope_OnlyDirect()
        {
            Random random    = new Random();
            Guid   scopeId   = random.NextGuid();
            String scopeName = "Testscope";

            DHCPv4LeaseOverview activeLeaseWithoutPrefix = new DHCPv4LeaseOverview
            {
                Address          = random.GetIPv4Address().ToString(),
                MacAddress       = random.NextBytes(6),
                ExpectedEnd      = DateTime.UtcNow.AddHours(random.Next(10, 20)),
                Started          = DateTime.UtcNow.AddHours(-random.Next(10, 20)),
                Id               = random.NextGuid(),
                UniqueIdentifier = random.NextBytes(10),
                State            = LeaseStates.Active,
                Scope            = new DHCPv4ScopeOverview
                {
                    Id   = scopeId,
                    Name = scopeName,
                }
            };

            DHCPv4LeaseOverview expiredLeaseWithPrefix = new DHCPv4LeaseOverview
            {
                Address          = random.GetIPv4Address().ToString(),
                MacAddress       = random.NextBytes(6),
                ExpectedEnd      = DateTime.UtcNow.AddHours(random.Next(10, 20)),
                Started          = DateTime.UtcNow.AddHours(-random.Next(10, 20)),
                Id               = random.NextGuid(),
                UniqueIdentifier = Array.Empty <Byte>(),
                State            = LeaseStates.Inactive,
                Scope            = new DHCPv4ScopeOverview
                {
                    Id   = scopeId,
                    Name = scopeName,
                }
            };

            DHCPv4RootScope rootScope = GetRootScope();

            rootScope.Load(new List <DomainEvent> {
                new DHCPv4ScopeEvents.DHCPv4ScopeAddedEvent(
                    new DHCPv4ScopeCreateInstruction
                {
                    Name = scopeName,
                    Id   = scopeId,
                }),
                new DHCPv4LeaseCreatedEvent
                {
                    EntityId         = expiredLeaseWithPrefix.Id,
                    Address          = IPv4Address.FromString(expiredLeaseWithPrefix.Address.ToString()),
                    ClientIdenfier   = DHCPv4ClientIdentifier.FromHwAddress(expiredLeaseWithPrefix.MacAddress).GetBytes(),
                    ScopeId          = scopeId,
                    StartedAt        = expiredLeaseWithPrefix.Started,
                    ValidUntil       = expiredLeaseWithPrefix.ExpectedEnd,
                    UniqueIdentifier = null,
                },
                new DHCPv4LeaseActivatedEvent
                {
                    EntityId = expiredLeaseWithPrefix.Id,
                    ScopeId  = scopeId,
                },
                new DHCPv4LeaseExpiredEvent
                {
                    EntityId = expiredLeaseWithPrefix.Id,
                    ScopeId  = scopeId,
                },
                new DHCPv4LeaseCreatedEvent
                {
                    EntityId         = activeLeaseWithoutPrefix.Id,
                    Address          = IPv4Address.FromString(activeLeaseWithoutPrefix.Address.ToString()),
                    ClientIdenfier   = DHCPv4ClientIdentifier.FromHwAddress(activeLeaseWithoutPrefix.MacAddress).GetBytes(),
                    ScopeId          = scopeId,
                    StartedAt        = activeLeaseWithoutPrefix.Started,
                    ValidUntil       = activeLeaseWithoutPrefix.ExpectedEnd,
                    UniqueIdentifier = activeLeaseWithoutPrefix.UniqueIdentifier
                },
                new DHCPv4LeaseActivatedEvent
                {
                    EntityId = activeLeaseWithoutPrefix.Id,
                    ScopeId  = scopeId,
                },
            });;


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

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

            Assert.Equal(new[] { activeLeaseWithoutPrefix, expiredLeaseWithPrefix }, result, new LeaseOverviewEqualityComparer());
        }
Exemplo n.º 18
0
        public void HandleRelease_LeaseExists_AddressIsActive()
        {
            Random      random        = new Random();
            IPv4Address leasedAddress = IPv4Address.FromString("192.168.178.10");

            IPv4HeaderInformation headerInformation =
                new IPv4HeaderInformation(leasedAddress, IPv4Address.FromString("192.168.178.1"));

            Byte[] clientMacAdress = random.NextBytes(6);

            DHCPv4Packet requestPacket = new DHCPv4Packet(
                headerInformation, clientMacAdress, (UInt32)random.Next(),
                IPv4Address.Empty, IPv4Address.Empty, IPv4Address.Empty,
                DHCPv4PacketFlags.Unicast,
                new DHCPv4PacketMessageTypeOption(DHCPv4MessagesTypes.Release)
                );

            Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> > scopeResolverMock =
                new Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict);

            var resolverInformations = new CreateScopeResolverInformation
            {
                Typename = nameof(DHCPv4RelayAgentSubnetResolver),
            };

            Mock <IScopeResolver <DHCPv4Packet, IPv4Address> > resolverMock = new Mock <IScopeResolver <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict);

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

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

            DateTime        leaseCreatedAt = DateTime.UtcNow.AddHours(-1);
            DHCPv4RootScope rootScope      = GetRootScope(scopeResolverMock);

            rootScope.Load(new List <DomainEvent> {
                new DHCPv4ScopeEvents.DHCPv4ScopeAddedEvent(
                    new DHCPv4ScopeCreateInstruction
                {
                    AddressProperties = new DHCPv4ScopeAddressProperties(
                        IPv4Address.FromString("192.168.178.1"),
                        IPv4Address.FromString("192.168.178.255"),
                        new List <IPv4Address> {
                        IPv4Address.FromString("192.168.178.1")
                    },
                        leaseTime: TimeSpan.FromDays(1)
                        ),
                    ResolverInformation = resolverInformations,
                    Name = "Testscope",
                    Id   = scopeId,
                }),
                new DHCPv4LeaseCreatedEvent
                {
                    EntityId         = leaseId,
                    Address          = leasedAddress,
                    ClientIdenfier   = DHCPv4ClientIdentifier.FromHwAddress(clientMacAdress).GetBytes(),
                    ScopeId          = scopeId,
                    UniqueIdentifier = null,
                    StartedAt        = leaseCreatedAt,
                    ValidUntil       = DateTime.UtcNow.AddDays(1),
                },
                new DHCPv4LeaseActivatedEvent
                {
                    EntityId = leaseId,
                    ScopeId  = scopeId,
                },
            });
            DHCPv4Lease lease = rootScope.GetScopeById(scopeId).Leases.GetLeaseById(leaseId);

            DHCPv4Packet result = rootScope.HandleRelease(requestPacket);

            Assert.Equal(DHCPv4Packet.Empty, result);

            CheckIfLeaseIsRelease(lease);

            CheckEventAmount(2, rootScope);
            CheckLeaseReleasedEvent(0, scopeId, rootScope, leaseId);
            CheckHandeledEvent(1, ReleaseError.NoError, requestPacket, rootScope);
        }
Exemplo n.º 19
0
        public void DHCPv4Scope_AddressPropertiesInherientce()
        {
            Random random = new Random();

            for (int i = 0; i < 100; i++)
            {
                IPv4Address        grantParentStart             = random.GetIPv4Address();
                IPv4Address        grantParentEnd               = random.GetIPv4AddressGreaterThan(grantParentStart);
                List <IPv4Address> grantParentExcludedAddresses = random.GetIPv4AddressesBetween(grantParentStart, grantParentEnd);

                TimeSpan grantParentValidLifeTime                     = TimeSpan.FromMinutes(random.Next());
                TimeSpan grantParentPrefferedValidLifeTime            = TimeSpan.FromMinutes(random.Next());
                TimeSpan grantParentRenewalTimePrefferedValidLifeTime = TimeSpan.FromMinutes(random.Next());

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

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

                Byte grantParentSubnetMask = (Byte)random.Next(18, 25);

                DHCPv4ScopeAddressProperties grantParentProperties = new DHCPv4ScopeAddressProperties(
                    grantParentStart, grantParentEnd, grantParentExcludedAddresses,
                    grantParentRenewalTimePrefferedValidLifeTime, grantParentPrefferedValidLifeTime, grantParentValidLifeTime,
                    grantParentSubnetMask,
                    grantParentReuseAddressIfPossible, grantParentAllocationStrategy,
                    grantParentInformsAreAllowd, grantParentAcceptDecline, grantParentInformsAreAllowd);

                IPv4Address        parentStart             = random.GetIPv4Address();
                IPv4Address        parentEnd               = random.GetIPv4AddressGreaterThan(parentStart);
                List <IPv4Address> parentExcludedAddresses = random.GetIPv4AddressesBetween(parentStart, parentEnd);

                TimeSpan?parentValidLifeTime                     = null;
                TimeSpan?parentPrefferedValidLifeTime            = null;
                TimeSpan?parentRenewalTimePrefferedValidLifeTime = null;

                Byte?parentSubnetMask = null;

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

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

                if (random.NextBoolean() == true)
                {
                    parentValidLifeTime = TimeSpan.FromMinutes(random.Next());
                }
                if (random.NextBoolean() == true)
                {
                    parentPrefferedValidLifeTime = TimeSpan.FromMinutes(random.Next());
                }
                if (random.NextBoolean() == true)
                {
                    parentRenewalTimePrefferedValidLifeTime = TimeSpan.FromMinutes(random.Next());
                }
                if (random.NextBoolean() == true)
                {
                    parentSubnetMask = (Byte)random.Next(18, 25);
                }
                if (random.NextBoolean() == true)
                {
                    parentReuseAddressIfPossible = random.NextBoolean();
                }
                if (random.NextBoolean() == true)
                {
                    parentAllocationStrategy = DHCPv4ScopeAddressProperties.AddressAllocationStrategies.Random;
                }
                if (random.NextBoolean() == true)
                {
                    parentSupportDirectUnicast = random.NextBoolean();
                }
                if (random.NextBoolean() == true)
                {
                    parentAcceptDecline = random.NextBoolean();
                }
                if (random.NextBoolean() == true)
                {
                    parentInformsAreAllowd = random.NextBoolean();
                }

                DHCPv4ScopeAddressProperties parentProperties = new DHCPv4ScopeAddressProperties(
                    parentStart, parentEnd, parentExcludedAddresses,
                    parentRenewalTimePrefferedValidLifeTime, parentPrefferedValidLifeTime, parentValidLifeTime,
                    parentSubnetMask,
                    parentReuseAddressIfPossible, parentAllocationStrategy,
                    parentInformsAreAllowd, parentAcceptDecline, parentInformsAreAllowd);

                IPv4Address        childStart             = random.GetIPv4Address();
                IPv4Address        childEnd               = random.GetIPv4AddressGreaterThan(childStart);
                List <IPv4Address> childExcludedAddresses = random.GetIPv4AddressesBetween(childStart, childEnd);

                TimeSpan?childValidLifeTime                     = null;
                TimeSpan?childPrefferedValidLifeTime            = null;
                TimeSpan?childRenewalTimePrefferedValidLifeTime = null;

                Byte?childSubnetMask = null;


                Boolean?childReuseAddressIfPossible = null;
                DHCPv4ScopeAddressProperties.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)
                {
                    childValidLifeTime = TimeSpan.FromMinutes(random.Next());
                }
                if (random.NextBoolean() == true)
                {
                    childPrefferedValidLifeTime = TimeSpan.FromMinutes(random.Next());
                }
                if (random.NextBoolean() == true)
                {
                    childRenewalTimePrefferedValidLifeTime = TimeSpan.FromMinutes(random.Next());
                }
                if (random.NextBoolean() == true)
                {
                    childSubnetMask = (Byte)random.Next(18, 25);
                }
                if (random.NextBoolean() == true)
                {
                    childReuseAddressIfPossible = random.NextBoolean();
                }
                if (random.NextBoolean() == true)
                {
                    childAllocationStrategy = DHCPv4ScopeAddressProperties.AddressAllocationStrategies.Random;
                }
                if (random.NextBoolean() == true)
                {
                    childSupportDirectUnicast = random.NextBoolean();
                }
                if (random.NextBoolean() == true)
                {
                    childAcceptDecline = random.NextBoolean();
                }
                if (random.NextBoolean() == true)
                {
                    childInformsAreAllowd = random.NextBoolean();
                }

                DHCPv4ScopeAddressProperties childProperties = new DHCPv4ScopeAddressProperties(
                    childStart, childEnd, childExcludedAddresses,
                    childRenewalTimePrefferedValidLifeTime, childPrefferedValidLifeTime, childValidLifeTime,
                    childSubnetMask,
                    childReuseAddressIfPossible, childAllocationStrategy,
                    childSupportDirectUnicast, childAcceptDecline, childInformsAreAllowd);

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

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

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

                DHCPv4Scope scope = rootScope.GetScopeById(childId);
                DHCPv4ScopeAddressProperties actualProperties = scope.GetAddressProperties();

                DHCPv4ScopeAddressProperties expectedProperties = new DHCPv4ScopeAddressProperties(
                    childStart, childEnd, grantParentExcludedAddresses.Union(parentExcludedAddresses).Union(childExcludedAddresses).Where(x => x.IsBetween(childStart, childEnd)),
                    childRenewalTimePrefferedValidLifeTime.HasValue == true ? childRenewalTimePrefferedValidLifeTime.Value : (parentRenewalTimePrefferedValidLifeTime.HasValue == true ? parentRenewalTimePrefferedValidLifeTime.Value : grantParentRenewalTimePrefferedValidLifeTime),
                    childPrefferedValidLifeTime.HasValue == true ? childPrefferedValidLifeTime.Value : (parentPrefferedValidLifeTime.HasValue == true ? parentPrefferedValidLifeTime.Value : grantParentPrefferedValidLifeTime),
                    childValidLifeTime.HasValue == true ? childValidLifeTime.Value : (parentValidLifeTime.HasValue == true ? parentValidLifeTime.Value : grantParentValidLifeTime),
                    childSubnetMask.HasValue == true ? childSubnetMask.Value : (parentSubnetMask.HasValue == true ? parentSubnetMask.Value : grantParentSubnetMask),
                    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)
                    );

                Assert.Equal(expectedProperties, actualProperties);
            }
        }
Exemplo n.º 20
0
        public static Dictionary <DHCPv4Lease, Boolean> AddEventsForCancelableLeases(
            Random random,
            Guid scopeId,
            DHCPv4RootScope scope)
        {
            Dictionary <LeaseStates, Func <Guid, DHCPv4ScopeRelatedEvent> > cancalableStateBuilder = new Dictionary <LeaseStates, Func <Guid, DHCPv4ScopeRelatedEvent> >
            {
                { LeaseStates.Pending, (id) => null },
                { LeaseStates.Active, (id) => new DHCPv4LeaseActivatedEvent(id) },
            };

            Dictionary <LeaseStates, Func <Guid, DHCPv4ScopeRelatedEvent> > nonCancalableStateBuilder = new Dictionary <LeaseStates, Func <Guid, DHCPv4ScopeRelatedEvent> >
            {
                { LeaseStates.Inactive, (id) => new DHCPv4LeaseExpiredEvent(id) },
                { LeaseStates.Canceled, (id) => new DHCPv4LeaseCanceledEvent(id) },
                { LeaseStates.Released, (id) => new DHCPv4LeaseReleasedEvent(id) },
                { LeaseStates.Revoked, (id) => new DHCPv4LeaseRevokedEvent(id) },
            };

            Int32 leaseAmount = random.Next(20, 40);
            Dictionary <DHCPv4Lease, Boolean> expectedCancallations = new();

            for (int i = 0; i < leaseAmount; i++)
            {
                Guid leaseId = Guid.NewGuid();
                scope.Load(new[] {
                    new DHCPv4LeaseCreatedEvent
                    {
                        ScopeId        = scopeId,
                        EntityId       = leaseId,
                        ClientIdenfier = DHCPv4ClientIdentifier.FromHwAddress(random.NextBytes(6)).GetBytes(),
                        Address        = random.GetIPv4Address(),
                    }
                });

                DHCPv4Lease lease = scope.GetRootScopes().First().Leases.GetLeaseById(leaseId);

                Boolean shouldBeCancelable = random.NextDouble() > 0.5;
                Dictionary <LeaseStates, Func <Guid, DHCPv4ScopeRelatedEvent> > eventCreatorDict = null;
                if (shouldBeCancelable == true)
                {
                    eventCreatorDict = cancalableStateBuilder;
                }
                else
                {
                    eventCreatorDict = nonCancalableStateBuilder;
                }

                var entry = eventCreatorDict.ElementAt(random.Next(0, eventCreatorDict.Count));
                DHCPv4ScopeRelatedEvent stateChangingEvent = entry.Value(leaseId);
                if (stateChangingEvent != null)
                {
                    stateChangingEvent.ScopeId = scopeId;
                    scope.Load(new[] { stateChangingEvent });
                }

                expectedCancallations.Add(lease, shouldBeCancelable);
            }

            return(expectedCancallations);
        }
Exemplo n.º 21
0
        public void DHCPv4Lease_MatchesUniqueIdentiifer()
        {
            Random          random    = new Random();
            DHCPv4RootScope rootScope = GetRootScope();

            Guid scopeId = Guid.NewGuid();

            Byte[] uniqueIdentifier = random.NextBytes(10);

            List <DomainEvent> events = new List <DomainEvent>
            {
                new DHCPv4ScopeAddedEvent(new DHCPv4ScopeCreateInstruction
                {
                    Id = scopeId,
                }),
            };

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

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

                Byte[]  identifier  = null;
                Boolean matches     = false;
                Double  randomValue = random.NextDouble();
                if (randomValue > 0.75)
                {
                    identifier = uniqueIdentifier;
                    matches    = true;
                }
                else if (randomValue > 0.5)
                {
                    identifier = random.NextBytes(12);
                }
                else if (randomValue > 0.25)
                {
                    identifier = new byte[0];
                }

                events.Add(new DHCPv4LeaseCreatedEvent
                {
                    ScopeId          = scopeId,
                    EntityId         = leaseId,
                    UniqueIdentifier = identifier,
                    Address          = random.GetIPv4Address(),
                    ClientIdenfier   = DHCPv4ClientIdentifier.FromHwAddress(random.NextBytes(6)).GetBytes(),
                });

                expectedResults.Add(leaseId, matches);
            }

            rootScope.Load(events);

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

            foreach (var item in expectedResults)
            {
                DHCPv4Lease lease  = scope.Leases.GetLeaseById(item.Key);
                Boolean     actual = lease.MatchesUniqueIdentiifer(uniqueIdentifier);
                Assert.Equal(item.Value, actual);
            }
        }
Exemplo n.º 22
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 <DHCPv4Packet, IPv4Address> > scopeResolverMock = new Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> >();

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

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

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

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

            rootScope.Load(new[] {
                new DHCPv4ScopeAddedEvent
                {
                    Instructions = new DHCPv4ScopeCreateInstruction
                    {
                        Id = grantParentId,
                        ResolverInformation = new CreateScopeResolverInformation
                        {
                            Typename = resolverName,
                        },
                        AddressProperties = new DHCPv4ScopeAddressProperties(IPv4Address.FromString("192.168.0.1"), IPv4Address.FromString("192.168.0.20")),
                    }
                },
                new DHCPv4ScopeAddedEvent
                {
                    Instructions = new DHCPv4ScopeCreateInstruction
                    {
                        Id                  = parentId,
                        ParentId            = grantParentId,
                        ResolverInformation = new CreateScopeResolverInformation
                        {
                            Typename = resolverName,
                        },
                        AddressProperties = new DHCPv4ScopeAddressProperties(IPv4Address.FromString("192.168.0.5"), IPv4Address.FromString("192.168.0.8")),
                    }
                },
                new DHCPv4ScopeAddedEvent
                {
                    Instructions = new DHCPv4ScopeCreateInstruction
                    {
                        Id                  = childId,
                        ParentId            = parentId,
                        ResolverInformation = new CreateScopeResolverInformation
                        {
                            Typename = resolverName,
                        },
                        AddressProperties = new DHCPv4ScopeAddressProperties(IPv4Address.FromString("192.168.0.7"), IPv4Address.FromString("192.168.0.7")),
                    }
                },
            });


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

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

            var command = new DeleteDHCPv4ScopeCommand(parentId, requestedToDeleteChildrenAsWell);

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

            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 DHCPv4ScopeDeletedEvent;
                Assert.Equal(childId, firstEvent.EntityId);

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

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

            storageMock.Verify();
        }
Exemplo n.º 23
0
        public void DHCPv4Scope_ScopePropertiesInherientce()
        {
            Random random = new Random();

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

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

            DHCPv4ScopeProperties grantParentProperties = new DHCPv4ScopeProperties(
                new DHCPv4AddressScopeProperty(onylGrandParentOptionIdentifier, inputs[onylGrandParentOptionIdentifier]),
                new DHCPv4AddressScopeProperty(overridenByParentOptionIdentifier, random.GetIPv4Address()),
                new DHCPv4AddressScopeProperty(overridenByChildOptionIdentifier, random.GetIPv4Address())
                );

            DHCPv4ScopeProperties parentProperties = new DHCPv4ScopeProperties(
                new DHCPv4AddressScopeProperty(onlyParentOptionIdentifier, inputs[onlyParentOptionIdentifier]),
                new DHCPv4AddressScopeProperty(overridenByParentOptionIdentifier, inputs[overridenByParentOptionIdentifier])
                );

            DHCPv4ScopeProperties childProperties = new DHCPv4ScopeProperties(
                new DHCPv4AddressScopeProperty(onlyChildOptionIdentifier, inputs[onlyChildOptionIdentifier]),
                new DHCPv4AddressScopeProperty(overridenByChildOptionIdentifier, inputs[overridenByChildOptionIdentifier])
                );

            DHCPv4ScopeProperties expectedProperties = new DHCPv4ScopeProperties(
                new DHCPv4AddressScopeProperty(onylGrandParentOptionIdentifier, inputs[onylGrandParentOptionIdentifier]),
                new DHCPv4AddressScopeProperty(onlyParentOptionIdentifier, inputs[onlyParentOptionIdentifier]),
                new DHCPv4AddressScopeProperty(onlyChildOptionIdentifier, inputs[onlyChildOptionIdentifier]),
                new DHCPv4AddressScopeProperty(overridenByParentOptionIdentifier, inputs[overridenByParentOptionIdentifier]),
                new DHCPv4AddressScopeProperty(overridenByChildOptionIdentifier, inputs[overridenByChildOptionIdentifier])
                );

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

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

            DHCPv4RootScope rootScope = GetRootScope();

            rootScope.Load(events);

            DHCPv4Scope           scope            = rootScope.GetScopeById(childId);
            DHCPv4ScopeProperties actualProperties = scope.GetScopeProperties();

            Assert.Equal(expectedProperties, actualProperties);
        }
Exemplo n.º 24
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();
                IPv4Address start    = random.GetIPv4Address();
                IPv4Address end      = start + 100;
                var         excluded = new[] { start + 1, start + 3 };

                DHCPv4ScopeProperties properties = null;
                if (random.NextBoolean() == true)
                {
                    DHCPv4AddressListScopeProperty gwAddress = new(
                        DHCPv4OptionTypes.Router, new[] { start + 0, start + 30 });
                    properties = new DHCPv4ScopeProperties(gwAddress);
                }
                else
                {
                    properties = new();
                }

                events.Add(new DHCPv4ScopeAddedEvent(new DHCPv4ScopeCreateInstruction
                {
                    Id   = scopeId,
                    Name = random.GetAlphanumericString(),
                    AddressProperties = new DHCPv4ScopeAddressProperties(start, end, excluded,
                                                                         maskLength: random.NextBoolean() == true ? (Byte)random.Next(0, 32) : null),
                    ScopeProperties = properties
                }));

                rootScopeIds.Add(scopeId);

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

            var scopeResolverMock = new Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict);

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

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

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

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

            rootScope.Load(events);

            var controller = new DHCPv4ScopeController(
                Mock.Of <IMediator>(MockBehavior.Strict),
                Mock.Of <IScopeResolverManager <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict),
                rootScope);
            var actionResult = controller.GetScopesAsList();
            var result       = actionResult.EnsureOkObjectResult <IEnumerable <DHCPv4ScopeItem> >(true);

            Assert.Equal(events.Count, result.Count());
            for (int i = 0; i < events.Count; i++)
            {
                var scope  = result.ElementAt(i);
                var @event = (DHCPv4ScopeAddedEvent)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);
                Assert.Equal(@event.Instructions.AddressProperties.ExcludedAddresses.Select(x => x.ToString()).ToArray(), scope.ExcludedAddresses);
                Assert.Equal((@event.Instructions.ScopeProperties?.Properties ?? Array.Empty <DHCPv4ScopeProperty>()).Where(x => x.OptionIdentifier == (Byte)DHCPv4OptionTypes.Router).Cast <DHCPv4AddressListScopeProperty>().Select(x => x.Addresses.First().ToString()).FirstOrDefault(), scope.FirstGatewayAddress);
            }
        }
Exemplo n.º 25
0
        public void GetScopesAsTreeView()
        {
            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();
                IPv4Address start    = random.GetIPv4Address();
                IPv4Address end      = start + 100;
                var         excluded = new[] { start + 1, start + 3 };

                DHCPv4ScopeProperties properties = null;
                if (random.NextBoolean() == true)
                {
                    DHCPv4AddressListScopeProperty gwAddress = new(
                        DHCPv4OptionTypes.Router, new[] { start + 0, start + 30 });
                    properties = new DHCPv4ScopeProperties(gwAddress);
                }
                else
                {
                    properties = new();
                }

                events.Add(new DHCPv4ScopeAddedEvent(new DHCPv4ScopeCreateInstruction
                {
                    Id   = scopeId,
                    Name = random.GetAlphanumericString(),
                    AddressProperties = new DHCPv4ScopeAddressProperties(start, end, excluded,
                                                                         maskLength: random.NextBoolean() == true ? (Byte)random.Next(0, 32) : null),
                    ScopeProperties = properties
                }));

                rootScopeIds.Add(scopeId);

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

            var scopeResolverMock = new Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict);

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

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

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

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

            rootScope.Load(events);

            var controller = new DHCPv4ScopeController(
                Mock.Of <IMediator>(MockBehavior.Strict),
                Mock.Of <IScopeResolverManager <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict),
                rootScope);
            var actionResult = controller.GetScopesAsTreeView();
            var result       = actionResult.EnsureOkObjectResult <IEnumerable <DHCPv4ScopeTreeViewItem> >(true);

            Assert.Equal(rootScopeAmount, result.Count());
            Int32 index = 0;

            foreach (var item in rootScope.GetRootScopes())
            {
                var scope = result.ElementAt(index);

                CheckTreeItem(item, scope);

                index++;
            }
        }
Exemplo n.º 26
0
        public void DHCPv4Leases_GetUsedAddresses()
        {
            Random          random    = new Random();
            DHCPv4RootScope rootScope = GetRootScope();

            Guid scopeId = Guid.NewGuid();

            List <DomainEvent> events = new List <DomainEvent>
            {
                new DHCPv4ScopeAddedEvent(new DHCPv4ScopeCreateInstruction
                {
                    Id = scopeId,
                }),
            };

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

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

                events.Add(new DHCPv4LeaseCreatedEvent
                {
                    ScopeId        = scopeId,
                    EntityId       = leaseId,
                    Address        = address,
                    ClientIdenfier = DHCPv4ClientIdentifier.FromHwAddress(random.NextBytes(6)).GetBytes(),
                });

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

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

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

            rootScope.Load(events);

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

            Assert.Equal(expectedUsedAddress, actualAddresses);
        }
Exemplo n.º 27
0
        public void HandleRelease_LeaseExists_AddressIsActive_NotSentDiscover()
        {
            Random      random        = new Random();
            IPv4Address leasedAddress = IPv4Address.FromString("192.168.178.10");

            IPv4HeaderInformation headerInformation =
                new IPv4HeaderInformation(leasedAddress, IPv4Address.FromString("192.168.178.1"));

            Byte[] clientMacAdress = random.NextBytes(6);

            DHCPv4Packet requestPacket = new DHCPv4Packet(
                headerInformation, clientMacAdress, (UInt32)random.Next(),
                IPv4Address.Empty, IPv4Address.Empty, IPv4Address.Empty,
                DHCPv4PacketFlags.Unicast,
                new DHCPv4PacketMessageTypeOption(DHCPv4MessagesTypes.Release)
                );

            DHCPv4Packet discoverPacket = new DHCPv4Packet(
                headerInformation, clientMacAdress, (UInt32)random.Next(),
                IPv4Address.Empty, IPv4Address.Empty, IPv4Address.Empty,
                DHCPv4PacketFlags.Broadcast,
                new DHCPv4PacketMessageTypeOption(DHCPv4MessagesTypes.Discover),
                new DHCPv4PacketClientIdentifierOption(DHCPv4ClientIdentifier.FromIdentifierValue("random test client"))
                );

            Mock <IScopeResolver <DHCPv4Packet, IPv4Address> > resolverMock = new Mock <IScopeResolver <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict);

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

            Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> > scopeResolverMock =
                new Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict);

            var resolverInformations = new CreateScopeResolverInformation
            {
                Typename = nameof(DHCPv4RelayAgentSubnetResolver),
            };

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

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

            DateTime        leaseCreatedAt = DateTime.UtcNow.AddHours(-1);
            DHCPv4RootScope rootScope      = GetRootScope(scopeResolverMock);

            rootScope.Load(new List <DomainEvent> {
                new DHCPv4ScopeEvents.DHCPv4ScopeAddedEvent(
                    new DHCPv4ScopeCreateInstruction
                {
                    AddressProperties = new DHCPv4ScopeAddressProperties(
                        IPv4Address.FromString("192.168.178.1"),
                        IPv4Address.FromString("192.168.178.255"),
                        new List <IPv4Address> {
                        IPv4Address.FromString("192.168.178.1")
                    },
                        leaseTime: TimeSpan.FromDays(1),
                        renewalTime: TimeSpan.FromHours(12),
                        preferredLifetime: TimeSpan.FromHours(18),
                        reuseAddressIfPossible: true,
                        acceptDecline: true,
                        addressAllocationStrategy: DHCPv4ScopeAddressProperties.AddressAllocationStrategies.Next,
                        supportDirectUnicast: true,
                        maskLength: 24
                        ),
                    ResolverInformation = resolverInformations,
                    Name = "Testscope",
                    Id   = scopeId,
                }),
                new DHCPv4LeaseCreatedEvent
                {
                    EntityId         = leaseId,
                    Address          = leasedAddress,
                    ClientIdenfier   = DHCPv4ClientIdentifier.FromIdentifierValue("random test client").GetBytes(),
                    ScopeId          = scopeId,
                    UniqueIdentifier = null,
                    StartedAt        = leaseCreatedAt,
                    ValidUntil       = DateTime.UtcNow.AddDays(1),
                },
                new DHCPv4LeaseActivatedEvent
                {
                    EntityId = leaseId,
                    ScopeId  = scopeId,
                },
            });

            DHCPv4Lease existingLease = rootScope.GetScopeById(scopeId).Leases.GetLeaseById(leaseId);

            DHCPv4Packet releaseResult = rootScope.HandleRelease(requestPacket);

            Assert.Equal(DHCPv4Packet.Empty, releaseResult);

            CheckIfLeaseIsRelease(existingLease);

            CheckEventAmount(2, rootScope);
            CheckLeaseReleasedEvent(0, scopeId, rootScope, leaseId);
            CheckHandeledEvent(1, ReleaseError.NoError, requestPacket, rootScope);

            DHCPv4Packet discoveryResult    = rootScope.HandleDiscover(discoverPacket);
            IPv4Address  newAssignedAddress = IPv4Address.FromString("192.168.178.2");

            Assert.Equal(newAssignedAddress, discoveryResult.YourIPAdress);
        }
Exemplo n.º 28
0
        public void DHCPv4Lease_AddressesAreInUse()
        {
            Random          random    = new Random();
            DHCPv4RootScope rootScope = GetRootScope();

            Guid scopeId = Guid.NewGuid();

            rootScope.Load(new[] { new DHCPv4ScopeAddedEvent(new DHCPv4ScopeCreateInstruction
                {
                    Id = scopeId,
                }) });

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

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

                rootScope.Load(new[] {
                    new DHCPv4LeaseCreatedEvent
                    {
                        ScopeId        = scopeId,
                        EntityId       = leaseId,
                        Address        = random.GetIPv4Address(),
                        ClientIdenfier = DHCPv4ClientIdentifier.FromHwAddress(random.NextBytes(6)).GetBytes(),
                    }
                });

                leases.Add(leaseId, rootScope.GetRootScopes().First().Leases.GetLeaseById(leaseId));


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

                if (eventToAdd != null)
                {
                    rootScope.Load(new[] { eventToAdd });
                }

                expectedResults.Add(leaseId, addressIsInUse);
            }

            foreach (var item in expectedResults)
            {
                DHCPv4Lease lease  = leases[item.Key];
                Boolean     actual = lease.AddressIsInUse();
                Assert.Equal(item.Value, actual);
            }
        }
Exemplo n.º 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();
        }
Exemplo n.º 30
0
        public void HandleDecline_AcceptDecline_RequesAddressExits_LeaseExists_LeaseIsPending_AddressIsNotSuspended()
        {
            Random random = new Random();

            IPv4Address leasedAddress = IPv4Address.FromString("192.168.178.3");

            DHCPv4Packet requestPacket = GetDeclinePacket(random, leasedAddress);

            Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> > scopeResolverMock =
                new Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict);

            var resolverInformations = new CreateScopeResolverInformation
            {
                Typename = nameof(DHCPv4RelayAgentSubnetResolver),
            };

            Mock <IScopeResolver <DHCPv4Packet, IPv4Address> > resolverMock = new Mock <IScopeResolver <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict);

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

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

            DateTime        leaseCreatedAt = DateTime.UtcNow.AddHours(-1);
            DHCPv4RootScope rootScope      = GetRootScope(scopeResolverMock);

            rootScope.Load(new List <DomainEvent> {
                new DHCPv4ScopeEvents.DHCPv4ScopeAddedEvent(
                    new DHCPv4ScopeCreateInstruction
                {
                    AddressProperties = new DHCPv4ScopeAddressProperties(
                        IPv4Address.FromString("192.168.178.0"),
                        IPv4Address.FromString("192.168.178.100"),
                        new List <IPv4Address> {
                        IPv4Address.FromString("192.168.178.0")
                    },
                        leaseTime: TimeSpan.FromDays(1),
                        acceptDecline: true),
                    ResolverInformation = resolverInformations,
                    Name = "Testscope",
                    Id   = scopeId,
                }),
                new DHCPv4LeaseCreatedEvent
                {
                    EntityId         = leaseId,
                    Address          = leasedAddress,
                    ClientIdenfier   = DHCPv4ClientIdentifier.FromHwAddress(requestPacket.ClientHardwareAddress).GetBytes(),
                    ScopeId          = scopeId,
                    UniqueIdentifier = null,
                    StartedAt        = leaseCreatedAt,
                    ValidUntil       = DateTime.UtcNow.AddDays(1),
                },
            });

            DHCPv4Packet result = rootScope.HandleDecline(requestPacket);

            Assert.Equal(DHCPv4Packet.Empty, result);

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

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

            CheckEventAmount(2, rootScope);
            CheckDeclineEvent(0, leaseId, leasedAddress, scopeId, rootScope);
            CheckDeclinedEvent(1, DeclineErros.NoError, requestPacket, rootScope, scopeId);
        }