Search in sources :

Example 1 with DHCP

use of org.onlab.packet.DHCP in project onos by opennetworkinglab.

the class Dhcp4HandlerImpl method processDhcpPacket.

@Override
public void processDhcpPacket(PacketContext context, BasePacket payload) {
    checkNotNull(payload, "DHCP payload can't be null");
    checkState(payload instanceof DHCP, "Payload is not a DHCP");
    DHCP dhcpPayload = (DHCP) payload;
    if (!configured()) {
        log.warn("Missing default DHCP relay server config. Abort packet processing");
        return;
    }
    ConnectPoint inPort = context.inPacket().receivedFrom();
    checkNotNull(dhcpPayload, "Can't find DHCP payload");
    Ethernet packet = context.inPacket().parsed();
    DHCP.MsgType incomingPacketType = dhcpPayload.getOptions().stream().filter(dhcpOption -> dhcpOption.getCode() == OptionCode_MessageType.getValue()).map(DhcpOption::getData).map(data -> DHCP.MsgType.getType(data[0])).findFirst().orElse(null);
    checkNotNull(incomingPacketType, "Can't get message type from DHCP payload {}", dhcpPayload);
    Set<Interface> receivingInterfaces = interfaceService.getInterfacesByPort(inPort);
    // ignore the packets if dhcp client interface is not configured on onos.
    if (receivingInterfaces.isEmpty()) {
        log.warn("Virtual interface is not configured on {}", inPort);
        return;
    }
    switch(incomingPacketType) {
        case DHCPDISCOVER:
            // Add the gateway IP as virtual interface IP for server to understand
            // the lease to be assigned and forward the packet to dhcp server.
            List<InternalPacket> ethernetClientPacket = processDhcpPacketFromClient(context, packet, receivingInterfaces);
            for (InternalPacket internalPacket : ethernetClientPacket) {
                log.debug("DHCPDISCOVER from {} Forward to server", inPort);
                writeRequestDhcpRecord(inPort, packet, dhcpPayload);
                forwardPacket(internalPacket);
            }
            break;
        case DHCPOFFER:
            // reply to dhcp client.
            InternalPacket ethernetPacketOffer = processDhcpPacketFromServer(context, packet);
            if (ethernetPacketOffer != null) {
                writeResponseDhcpRecord(ethernetPacketOffer.getPacket(), dhcpPayload);
                sendResponseToClient(ethernetPacketOffer, dhcpPayload);
            }
            break;
        case DHCPREQUEST:
            // add the gateway ip as virtual interface ip for server to understand
            // the lease to be assigned and forward the packet to dhcp server.
            List<InternalPacket> ethernetPacketRequest = processDhcpPacketFromClient(context, packet, receivingInterfaces);
            for (InternalPacket internalPacket : ethernetPacketRequest) {
                log.debug("DHCPDISCOVER from {} Forward to server", inPort);
                writeRequestDhcpRecord(inPort, packet, dhcpPayload);
                forwardPacket(internalPacket);
            }
            break;
        case DHCPDECLINE:
            break;
        case DHCPACK:
            // reply to dhcp client.
            InternalPacket ethernetPacketAck = processDhcpPacketFromServer(context, packet);
            if (ethernetPacketAck != null) {
                writeResponseDhcpRecord(ethernetPacketAck.getPacket(), dhcpPayload);
                handleDhcpAck(ethernetPacketAck.getPacket(), dhcpPayload);
                sendResponseToClient(ethernetPacketAck, dhcpPayload);
            }
            break;
        case DHCPNAK:
            break;
        case DHCPRELEASE:
            // TODO: release the ip address from client
            break;
        case DHCPINFORM:
            break;
        case DHCPFORCERENEW:
            break;
        case DHCPLEASEQUERY:
            handleLeaseQueryMsg(context, packet, dhcpPayload);
            break;
        case DHCPLEASEACTIVE:
            handleLeaseQueryActivateMsg(packet, dhcpPayload);
            break;
        case DHCPLEASEUNASSIGNED:
        case DHCPLEASEUNKNOWN:
            handleLeaseQueryUnknown(packet, dhcpPayload);
            break;
        default:
            break;
    }
}
Also used : Ethernet(org.onlab.packet.Ethernet) ConnectPoint(org.onosproject.net.ConnectPoint) DHCP(org.onlab.packet.DHCP) Interface(org.onosproject.net.intf.Interface)

Example 2 with DHCP

use of org.onlab.packet.DHCP in project onos by opennetworkinglab.

the class Dhcp4HandlerImpl method setDhcpServerConfigs.

public void setDhcpServerConfigs(Collection<DhcpServerConfig> configs, List<DhcpServerInfo> serverInfoList) {
    if (configs.size() == 0) {
        // no config to update
        return;
    }
    Boolean isConfigValid = false;
    for (DhcpServerConfig serverConfig : configs) {
        if (serverConfig.getDhcpServerIp4().isPresent()) {
            isConfigValid = true;
            break;
        }
    }
    if (!isConfigValid) {
        log.warn("No IP V4 server address found.");
        // No IP V6 address found
        return;
    }
    // if (!serverInfoList.isEmpty()) {
    for (DhcpServerInfo oldServerInfo : serverInfoList) {
        log.info("In for (DhcpServerInfo oldServerInfo : serverInfoList) {");
        // remove old server info
        // DhcpServerInfo oldServerInfo = serverInfoList.remove(0);
        // stop monitoring gateway or server
        oldServerInfo.getDhcpGatewayIp4().ifPresent(gatewayIp -> {
            hostService.stopMonitoringIp(gatewayIp);
        });
        oldServerInfo.getDhcpServerIp4().ifPresent(serverIp -> {
            hostService.stopMonitoringIp(serverIp);
            cancelDhcpPacket(serverIp);
        });
    }
    // Create new server info according to the config
    serverInfoList.clear();
    for (DhcpServerConfig serverConfig : configs) {
        log.debug("Create new server info according to the config");
        DhcpServerInfo newServerInfo = new DhcpServerInfo(serverConfig, DhcpServerInfo.Version.DHCP_V4);
        checkState(newServerInfo.getDhcpServerConnectPoint().isPresent(), "Connect point not exists");
        checkState(newServerInfo.getDhcpServerIp4().isPresent(), "IP of DHCP server not exists");
        log.debug("DHCP server connect point: {}", newServerInfo.getDhcpServerConnectPoint().orElse(null));
        log.debug("DHCP server IP: {}", newServerInfo.getDhcpServerIp4().orElse(null));
        Ip4Address serverIp = newServerInfo.getDhcpServerIp4().get();
        Ip4Address ipToProbe;
        if (newServerInfo.getDhcpGatewayIp4().isPresent()) {
            ipToProbe = newServerInfo.getDhcpGatewayIp4().get();
        } else {
            ipToProbe = newServerInfo.getDhcpServerIp4().orElse(null);
        }
        log.info("Probe_IP {}", ipToProbe);
        String hostToProbe = newServerInfo.getDhcpGatewayIp4().map(ip -> "gateway").orElse("server");
        log.debug("Probing to resolve {} IP {}", hostToProbe, ipToProbe);
        hostService.startMonitoringIp(ipToProbe);
        Set<Host> hosts = hostService.getHostsByIp(ipToProbe);
        if (!hosts.isEmpty()) {
            Host host = hosts.iterator().next();
            newServerInfo.setDhcpConnectVlan(host.vlan());
            newServerInfo.setDhcpConnectMac(host.mac());
        }
        // Add new server info
        synchronized (this) {
            // serverInfoList.clear();
            serverInfoList.add(newServerInfo);
        }
        requestDhcpPacket(serverIp);
    }
}
Also used : DeviceService(org.onosproject.net.device.DeviceService) DefaultTrafficTreatment(org.onosproject.net.flow.DefaultTrafficTreatment) ConnectPoint(org.onosproject.net.ConnectPoint) ObjectiveError(org.onosproject.net.flowobjective.ObjectiveError) OptionCode_END(org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_END) IgnoreDhcpConfig(org.onosproject.dhcprelay.config.IgnoreDhcpConfig) Port(org.onosproject.net.Port) ApplicationId(org.onosproject.core.ApplicationId) DhcpRelayStore(org.onosproject.dhcprelay.store.DhcpRelayStore) Ip4Address(org.onlab.packet.Ip4Address) Deactivate(org.osgi.service.component.annotations.Deactivate) OptionCode_MessageType(org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_MessageType) Set(java.util.Set) MacAddress.valueOf(org.onlab.packet.MacAddress.valueOf) PacketService(org.onosproject.net.packet.PacketService) DhcpServerConfig(org.onosproject.dhcprelay.config.DhcpServerConfig) DeviceId(org.onosproject.net.DeviceId) LEARN_ROUTE_FROM_LEASE_QUERY_DEFAULT(org.onosproject.dhcprelay.OsgiPropertyConstants.LEARN_ROUTE_FROM_LEASE_QUERY_DEFAULT) Dictionary(java.util.Dictionary) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Pipeliner(org.onosproject.net.behaviour.Pipeliner) REMOVE(org.onosproject.net.flowobjective.Objective.Operation.REMOVE) HostProviderRegistry(org.onosproject.net.host.HostProviderRegistry) Tools(org.onlab.util.Tools) Host(org.onosproject.net.Host) RouteStore(org.onosproject.routeservice.RouteStore) ComponentContext(org.osgi.service.component.ComponentContext) LEARN_ROUTE_FROM_LEASE_QUERY(org.onosproject.dhcprelay.OsgiPropertyConstants.LEARN_ROUTE_FROM_LEASE_QUERY) HostListener(org.onosproject.net.host.HostListener) InterfaceService(org.onosproject.net.intf.InterfaceService) HostService(org.onosproject.net.host.HostService) Multimaps(com.google.common.collect.Multimaps) ArrayList(java.util.ArrayList) Component(org.osgi.service.component.annotations.Component) Lists(com.google.common.collect.Lists) TrafficSelector(org.onosproject.net.flow.TrafficSelector) CIRCUIT_ID(org.onlab.packet.dhcp.DhcpRelayAgentOption.RelayAgentInfoOptions.CIRCUIT_ID) OptionCode_CircuitID(org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_CircuitID) CircuitId(org.onlab.packet.dhcp.CircuitId) DhcpRelayAgentOption(org.onlab.packet.dhcp.DhcpRelayAgentOption) DefaultTrafficSelector(org.onosproject.net.flow.DefaultTrafficSelector) TpPort(org.onlab.packet.TpPort) ComponentConfigService(org.onosproject.cfg.ComponentConfigService) BasePacket(org.onlab.packet.BasePacket) Executor(java.util.concurrent.Executor) HostProvider(org.onosproject.net.host.HostProvider) VlanId(org.onlab.packet.VlanId) ProviderId(org.onosproject.net.provider.ProviderId) IPv4(org.onlab.packet.IPv4) DhcpRecord(org.onosproject.dhcprelay.store.DhcpRecord) Objective(org.onosproject.net.flowobjective.Objective) MacAddress(org.onlab.packet.MacAddress) DHCP(org.onlab.packet.DHCP) DefaultOutboundPacket(org.onosproject.net.packet.DefaultOutboundPacket) Route(org.onosproject.routeservice.Route) HostLocation(org.onosproject.net.HostLocation) Interface(org.onosproject.net.intf.Interface) CoreService(org.onosproject.core.CoreService) LoggerFactory(org.slf4j.LoggerFactory) Tools.groupedThreads(org.onlab.util.Tools.groupedThreads) ForwardingObjective(org.onosproject.net.flowobjective.ForwardingObjective) ByteBuffer(java.nio.ByteBuffer) Ethernet(org.onlab.packet.Ethernet) HostProviderService(org.onosproject.net.host.HostProviderService) HashMultimap(com.google.common.collect.HashMultimap) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DhcpServerInfo(org.onosproject.dhcprelay.api.DhcpServerInfo) ImmutableSet(com.google.common.collect.ImmutableSet) Device(org.onosproject.net.Device) Collection(java.util.Collection) Executors.newSingleThreadExecutor(java.util.concurrent.Executors.newSingleThreadExecutor) DefaultForwardingObjective(org.onosproject.net.flowobjective.DefaultForwardingObjective) InterfaceIpAddress(org.onosproject.net.host.InterfaceIpAddress) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) Preconditions.checkState(com.google.common.base.Preconditions.checkState) List(java.util.List) ObjectiveContext(org.onosproject.net.flowobjective.ObjectiveContext) PacketContext(org.onosproject.net.packet.PacketContext) Optional(java.util.Optional) HostDescription(org.onosproject.net.host.HostDescription) ADD(org.onosproject.net.flowobjective.Objective.Operation.ADD) Multimap(com.google.common.collect.Multimap) FlowObjectiveService(org.onosproject.net.flowobjective.FlowObjectiveService) DefaultHostDescription(org.onosproject.net.host.DefaultHostDescription) OutboundPacket(org.onosproject.net.packet.OutboundPacket) HostEvent(org.onosproject.net.host.HostEvent) Activate(org.osgi.service.component.annotations.Activate) HostId(org.onosproject.net.HostId) IpAddress(org.onlab.packet.IpAddress) TrafficTreatment(org.onosproject.net.flow.TrafficTreatment) Logger(org.slf4j.Logger) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) UDP(org.onlab.packet.UDP) DhcpHandler(org.onosproject.dhcprelay.api.DhcpHandler) DhcpOption(org.onlab.packet.dhcp.DhcpOption) ReferenceCardinality(org.osgi.service.component.annotations.ReferenceCardinality) Modified(org.osgi.service.component.annotations.Modified) PacketPriority(org.onosproject.net.packet.PacketPriority) Reference(org.osgi.service.component.annotations.Reference) Collections(java.util.Collections) DhcpServerConfig(org.onosproject.dhcprelay.config.DhcpServerConfig) Ip4Address(org.onlab.packet.Ip4Address) Host(org.onosproject.net.Host) DhcpServerInfo(org.onosproject.dhcprelay.api.DhcpServerInfo)

Example 3 with DHCP

use of org.onlab.packet.DHCP in project onos by opennetworkinglab.

the class Dhcp4HandlerImpl method processLeaseQueryFromServer.

/**
 * Build the DHCP offer/ack with proper client port.
 *
 * @param ethernetPacket the original packet comes from server
 * @return new packet which will send to the client
 */
private InternalPacket processLeaseQueryFromServer(Ethernet ethernetPacket) {
    // get dhcp header.
    Ethernet etherReply = (Ethernet) ethernetPacket.clone();
    IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
    UDP udpPacket = (UDP) ipv4Packet.getPayload();
    DHCP dhcpPayload = (DHCP) udpPacket.getPayload();
    // determine the vlanId of the client host - note that this vlan id
    // could be different from the vlan in the packet from the server
    Interface clientInterface = null;
    MacAddress destinationMac = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
    if (!learnRouteFromLeasequery) {
        int giaddr = ipv4Packet.getDestinationAddress();
        IpAddress destinationAddress = Ip4Address.valueOf(giaddr);
        log.debug("DHCPLEASEQUERYRESP giaddr: {}({})", giaddr, destinationAddress);
        Host destinationHost = hostService.getHostsByIp(destinationAddress).stream().findFirst().orElse(null);
        if (destinationHost != null) {
            destinationMac = destinationHost.mac();
            log.trace("DHCPLEASEQUERYRESP destination mac is: {}", destinationMac);
            ConnectPoint destinationLocation = destinationHost.location();
            log.trace("Lookup for client interface by destination location {}", destinationLocation);
            clientInterface = interfaceService.getInterfacesByPort(destinationLocation).stream().filter(iface -> interfaceContainsVlan(iface, VlanId.vlanId(etherReply.getVlanID()))).findFirst().orElse(null);
            log.trace("Found Host {} by ip {}", destinationHost, destinationAddress);
            log.debug("DHCPLEASEQUERYRESP Client interface: {}", (clientInterface != null ? clientInterface : "not resolved"));
        }
    } else {
        clientInterface = getClientInterface(ethernetPacket, dhcpPayload).orElse(null);
    }
    if (clientInterface == null) {
        log.warn("Cannot find the interface for the DHCP {}", dhcpPayload);
        return null;
    }
    VlanId vlanId;
    if (clientInterface.vlanTagged().isEmpty()) {
        vlanId = clientInterface.vlan();
    } else {
        // might be multiple vlan in same interface
        vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
    }
    if (vlanId == null) {
        vlanId = VlanId.NONE;
    }
    etherReply.setVlanID(vlanId.toShort());
    etherReply.setSourceMACAddress(clientInterface.mac());
    if (!directlyConnected(dhcpPayload) && learnRouteFromLeasequery) {
        // if client is indirectly connected, try use next hop mac address
        MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
        HostId hostId = HostId.hostId(macAddress, vlanId);
        DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
        if (record != null) {
            // if next hop can be found, use mac address of next hop
            Optional<MacAddress> nextHop = record.nextHopTemp();
            if (!nextHop.isPresent()) {
                nextHop = record.nextHop();
            }
            nextHop.ifPresent(etherReply::setDestinationMACAddress);
        } else {
            // otherwise, discard the packet
            log.warn("Can't find record for host id {}, discard packet", hostId);
            return null;
        }
    } else {
        etherReply.setDestinationMACAddress(destinationMac);
    }
    udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
    if (directlyConnected(dhcpPayload)) {
        udpPacket.setDestinationPort(UDP.DHCP_CLIENT_PORT);
    } else {
        udpPacket.setDestinationPort(UDP.DHCP_SERVER_PORT);
    }
    udpPacket.setPayload(dhcpPayload);
    ipv4Packet.setPayload(udpPacket);
    etherReply.setPayload(ipv4Packet);
    udpPacket.resetChecksum();
    return InternalPacket.internalPacket(etherReply, clientInterface.connectPoint());
}
Also used : UDP(org.onlab.packet.UDP) DeviceService(org.onosproject.net.device.DeviceService) DefaultTrafficTreatment(org.onosproject.net.flow.DefaultTrafficTreatment) ConnectPoint(org.onosproject.net.ConnectPoint) ObjectiveError(org.onosproject.net.flowobjective.ObjectiveError) OptionCode_END(org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_END) IgnoreDhcpConfig(org.onosproject.dhcprelay.config.IgnoreDhcpConfig) Port(org.onosproject.net.Port) ApplicationId(org.onosproject.core.ApplicationId) DhcpRelayStore(org.onosproject.dhcprelay.store.DhcpRelayStore) Ip4Address(org.onlab.packet.Ip4Address) Deactivate(org.osgi.service.component.annotations.Deactivate) OptionCode_MessageType(org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_MessageType) Set(java.util.Set) MacAddress.valueOf(org.onlab.packet.MacAddress.valueOf) PacketService(org.onosproject.net.packet.PacketService) DhcpServerConfig(org.onosproject.dhcprelay.config.DhcpServerConfig) DeviceId(org.onosproject.net.DeviceId) LEARN_ROUTE_FROM_LEASE_QUERY_DEFAULT(org.onosproject.dhcprelay.OsgiPropertyConstants.LEARN_ROUTE_FROM_LEASE_QUERY_DEFAULT) Dictionary(java.util.Dictionary) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Pipeliner(org.onosproject.net.behaviour.Pipeliner) REMOVE(org.onosproject.net.flowobjective.Objective.Operation.REMOVE) HostProviderRegistry(org.onosproject.net.host.HostProviderRegistry) Tools(org.onlab.util.Tools) Host(org.onosproject.net.Host) RouteStore(org.onosproject.routeservice.RouteStore) ComponentContext(org.osgi.service.component.ComponentContext) LEARN_ROUTE_FROM_LEASE_QUERY(org.onosproject.dhcprelay.OsgiPropertyConstants.LEARN_ROUTE_FROM_LEASE_QUERY) HostListener(org.onosproject.net.host.HostListener) InterfaceService(org.onosproject.net.intf.InterfaceService) HostService(org.onosproject.net.host.HostService) Multimaps(com.google.common.collect.Multimaps) ArrayList(java.util.ArrayList) Component(org.osgi.service.component.annotations.Component) Lists(com.google.common.collect.Lists) TrafficSelector(org.onosproject.net.flow.TrafficSelector) CIRCUIT_ID(org.onlab.packet.dhcp.DhcpRelayAgentOption.RelayAgentInfoOptions.CIRCUIT_ID) OptionCode_CircuitID(org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_CircuitID) CircuitId(org.onlab.packet.dhcp.CircuitId) DhcpRelayAgentOption(org.onlab.packet.dhcp.DhcpRelayAgentOption) DefaultTrafficSelector(org.onosproject.net.flow.DefaultTrafficSelector) TpPort(org.onlab.packet.TpPort) ComponentConfigService(org.onosproject.cfg.ComponentConfigService) BasePacket(org.onlab.packet.BasePacket) Executor(java.util.concurrent.Executor) HostProvider(org.onosproject.net.host.HostProvider) VlanId(org.onlab.packet.VlanId) ProviderId(org.onosproject.net.provider.ProviderId) IPv4(org.onlab.packet.IPv4) DhcpRecord(org.onosproject.dhcprelay.store.DhcpRecord) Objective(org.onosproject.net.flowobjective.Objective) MacAddress(org.onlab.packet.MacAddress) DHCP(org.onlab.packet.DHCP) DefaultOutboundPacket(org.onosproject.net.packet.DefaultOutboundPacket) Route(org.onosproject.routeservice.Route) HostLocation(org.onosproject.net.HostLocation) Interface(org.onosproject.net.intf.Interface) CoreService(org.onosproject.core.CoreService) LoggerFactory(org.slf4j.LoggerFactory) Tools.groupedThreads(org.onlab.util.Tools.groupedThreads) ForwardingObjective(org.onosproject.net.flowobjective.ForwardingObjective) ByteBuffer(java.nio.ByteBuffer) Ethernet(org.onlab.packet.Ethernet) HostProviderService(org.onosproject.net.host.HostProviderService) HashMultimap(com.google.common.collect.HashMultimap) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DhcpServerInfo(org.onosproject.dhcprelay.api.DhcpServerInfo) ImmutableSet(com.google.common.collect.ImmutableSet) Device(org.onosproject.net.Device) Collection(java.util.Collection) Executors.newSingleThreadExecutor(java.util.concurrent.Executors.newSingleThreadExecutor) DefaultForwardingObjective(org.onosproject.net.flowobjective.DefaultForwardingObjective) InterfaceIpAddress(org.onosproject.net.host.InterfaceIpAddress) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) Preconditions.checkState(com.google.common.base.Preconditions.checkState) List(java.util.List) ObjectiveContext(org.onosproject.net.flowobjective.ObjectiveContext) PacketContext(org.onosproject.net.packet.PacketContext) Optional(java.util.Optional) HostDescription(org.onosproject.net.host.HostDescription) ADD(org.onosproject.net.flowobjective.Objective.Operation.ADD) Multimap(com.google.common.collect.Multimap) FlowObjectiveService(org.onosproject.net.flowobjective.FlowObjectiveService) DefaultHostDescription(org.onosproject.net.host.DefaultHostDescription) OutboundPacket(org.onosproject.net.packet.OutboundPacket) HostEvent(org.onosproject.net.host.HostEvent) Activate(org.osgi.service.component.annotations.Activate) HostId(org.onosproject.net.HostId) IpAddress(org.onlab.packet.IpAddress) TrafficTreatment(org.onosproject.net.flow.TrafficTreatment) Logger(org.slf4j.Logger) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) UDP(org.onlab.packet.UDP) DhcpHandler(org.onosproject.dhcprelay.api.DhcpHandler) DhcpOption(org.onlab.packet.dhcp.DhcpOption) ReferenceCardinality(org.osgi.service.component.annotations.ReferenceCardinality) Modified(org.osgi.service.component.annotations.Modified) PacketPriority(org.onosproject.net.packet.PacketPriority) Reference(org.osgi.service.component.annotations.Reference) Collections(java.util.Collections) IPv4(org.onlab.packet.IPv4) Host(org.onosproject.net.Host) DhcpRecord(org.onosproject.dhcprelay.store.DhcpRecord) MacAddress(org.onlab.packet.MacAddress) HostId(org.onosproject.net.HostId) ConnectPoint(org.onosproject.net.ConnectPoint) DHCP(org.onlab.packet.DHCP) ConnectPoint(org.onosproject.net.ConnectPoint) Ethernet(org.onlab.packet.Ethernet) InterfaceIpAddress(org.onosproject.net.host.InterfaceIpAddress) IpAddress(org.onlab.packet.IpAddress) Interface(org.onosproject.net.intf.Interface) VlanId(org.onlab.packet.VlanId)

Example 4 with DHCP

use of org.onlab.packet.DHCP in project onos by opennetworkinglab.

the class Dhcp4HandlerImpl method removeRelayAgentOption.

/**
 * Removes DHCP relay agent information option (option 82) from DHCP payload.
 * Also reset giaddr to 0
 *
 * @param ethPacket the Ethernet packet to be processed
 * @return Ethernet packet processed
 */
private Ethernet removeRelayAgentOption(Ethernet ethPacket) {
    Ethernet ethernet = (Ethernet) ethPacket.duplicate();
    IPv4 ipv4 = (IPv4) ethernet.getPayload();
    UDP udp = (UDP) ipv4.getPayload();
    DHCP dhcpPayload = (DHCP) udp.getPayload();
    // removes relay agent information option
    List<DhcpOption> options = dhcpPayload.getOptions();
    options = options.stream().filter(option -> option.getCode() != OptionCode_CircuitID.getValue()).collect(Collectors.toList());
    dhcpPayload.setOptions(options);
    dhcpPayload.setGatewayIPAddress(0);
    udp.setPayload(dhcpPayload);
    ipv4.setPayload(udp);
    ethernet.setPayload(ipv4);
    return ethernet;
}
Also used : UDP(org.onlab.packet.UDP) Ethernet(org.onlab.packet.Ethernet) IPv4(org.onlab.packet.IPv4) DhcpOption(org.onlab.packet.dhcp.DhcpOption) DHCP(org.onlab.packet.DHCP)

Example 5 with DHCP

use of org.onlab.packet.DHCP in project onos by opennetworkinglab.

the class Dhcp4HandlerImpl method processDhcpPacketFromClient.

/**
 * Build the DHCP discover/request packet with gateway IP(unicast packet).
 *
 * @param context the packet context
 * @param ethernetPacket the ethernet payload to process
 * @return processed packet
 */
private List<InternalPacket> processDhcpPacketFromClient(PacketContext context, Ethernet ethernetPacket, Set<Interface> clientInterfaces) {
    ConnectPoint receivedFrom = context.inPacket().receivedFrom();
    DeviceId receivedFromDevice = receivedFrom.deviceId();
    Ip4Address relayAgentIp = null;
    relayAgentIp = Dhcp4HandlerUtil.getRelayAgentIPv4Address(clientInterfaces);
    MacAddress relayAgentMac = clientInterfaces.iterator().next().mac();
    if (relayAgentIp == null || relayAgentMac == null) {
        log.warn("Missing DHCP relay agent interface Ipv4 addr config for " + "packet from client on port: {}. Aborting packet processing", clientInterfaces.iterator().next().connectPoint());
        return Lists.newArrayList();
    }
    log.debug("Multi DHCP V4 processDhcpPacketFromClient on port {}", clientInterfaces.iterator().next().connectPoint());
    // get dhcp header.
    Ethernet etherReply = (Ethernet) ethernetPacket.clone();
    IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
    UDP udpPacket = (UDP) ipv4Packet.getPayload();
    DHCP dhcpPacket = (DHCP) udpPacket.getPayload();
    Ip4Address clientInterfaceIp = interfaceService.getInterfacesByPort(context.inPacket().receivedFrom()).stream().map(Interface::ipAddressesList).flatMap(Collection::stream).map(InterfaceIpAddress::ipAddress).filter(IpAddress::isIp4).map(IpAddress::getIp4Address).findFirst().orElse(null);
    if (clientInterfaceIp == null) {
        log.warn("Can't find interface IP for client interface for port {}", context.inPacket().receivedFrom());
        return Lists.newArrayList();
    }
    boolean isDirectlyConnected = directlyConnected(dhcpPacket);
    boolean directConnFlag = directlyConnected(dhcpPacket);
    // Multi DHCP Start
    ConnectPoint clientConnectionPoint = context.inPacket().receivedFrom();
    VlanId vlanIdInUse = VlanId.vlanId(ethernetPacket.getVlanID());
    Interface clientInterface = interfaceService.getInterfacesByPort(clientConnectionPoint).stream().filter(iface -> Dhcp4HandlerUtil.interfaceContainsVlan(iface, vlanIdInUse)).findFirst().orElse(null);
    List<InternalPacket> internalPackets = new ArrayList<>();
    List<DhcpServerInfo> serverInfoList = findValidServerInfo(directConnFlag);
    List<DhcpServerInfo> copyServerInfoList = new ArrayList<DhcpServerInfo>(serverInfoList);
    boolean serverFound = false;
    for (DhcpServerInfo serverInfo : copyServerInfoList) {
        etherReply = (Ethernet) ethernetPacket.clone();
        ipv4Packet = (IPv4) etherReply.getPayload();
        udpPacket = (UDP) ipv4Packet.getPayload();
        dhcpPacket = (DHCP) udpPacket.getPayload();
        if (!checkDhcpServerConnPt(directConnFlag, serverInfo)) {
            log.warn("Can't get server connect point, ignore");
            continue;
        }
        DhcpServerInfo newServerInfo = getHostInfoForServerInfo(serverInfo, serverInfoList);
        if (newServerInfo == null) {
            log.debug("Can't get server interface with host info resolved, ignore serverInfo {} serverInfoList {}", serverInfo, serverInfoList);
            continue;
        }
        Interface serverInterface = getServerInterface(newServerInfo);
        if (serverInterface == null) {
            log.debug("Can't get server interface, ignore for serverInfo {}, serverInfoList {}", serverInfo, serverInfoList);
            continue;
        }
        Ip4Address ipFacingServer = getFirstIpFromInterface(serverInterface);
        MacAddress macFacingServer = serverInterface.mac();
        log.debug("Interfacing server {} Mac : {} ", ipFacingServer, macFacingServer);
        if (ipFacingServer == null || macFacingServer == null) {
            log.debug("No IP address for server Interface {}", serverInterface);
            continue;
        }
        serverFound = true;
        log.debug("Server Info Found {}", serverInfo.getDhcpConnectMac());
        etherReply.setSourceMACAddress(macFacingServer);
        // set default info and replace with indirect if available later on.
        if (newServerInfo.getDhcpConnectMac().isPresent()) {
            etherReply.setDestinationMACAddress(newServerInfo.getDhcpConnectMac().get());
        }
        if (newServerInfo.getDhcpConnectVlan().isPresent()) {
            etherReply.setVlanID(newServerInfo.getDhcpConnectVlan().get().toShort());
        }
        ipv4Packet.setSourceAddress(ipFacingServer.toInt());
        ipv4Packet.setDestinationAddress(newServerInfo.getDhcpServerIp4().get().toInt());
        log.debug("Directly connected {}", isDirectlyConnected);
        log.debug("DHCP server IP: {}", newServerInfo.getDhcpServerIp4().get());
        if (isDirectlyConnected) {
            log.debug("Default DHCP server IP: {}", newServerInfo.getDhcpServerIp4().get());
            if (newServerInfo.getDhcpConnectMac().isPresent()) {
                etherReply.setDestinationMACAddress(newServerInfo.getDhcpConnectMac().get());
            }
            if (newServerInfo.getDhcpConnectVlan().isPresent()) {
                etherReply.setVlanID(newServerInfo.getDhcpConnectVlan().get().toShort());
            }
            ipv4Packet.setDestinationAddress(newServerInfo.getDhcpServerIp4().get().toInt());
            ConnectPoint inPort = context.inPacket().receivedFrom();
            VlanId vlanId = VlanId.vlanId(ethernetPacket.getVlanID());
            // add connected in port and vlan
            CircuitId cid = new CircuitId(inPort.toString(), vlanId);
            byte[] circuitId = cid.serialize();
            DhcpOption circuitIdSubOpt = new DhcpOption();
            circuitIdSubOpt.setCode(CIRCUIT_ID.getValue()).setLength((byte) circuitId.length).setData(circuitId);
            DhcpRelayAgentOption newRelayAgentOpt = new DhcpRelayAgentOption();
            newRelayAgentOpt.setCode(OptionCode_CircuitID.getValue());
            newRelayAgentOpt.addSubOption(circuitIdSubOpt);
            // Removes END option first
            List<DhcpOption> options = dhcpPacket.getOptions().stream().filter(opt -> opt.getCode() != OptionCode_END.getValue()).collect(Collectors.toList());
            // push relay agent option
            options.add(newRelayAgentOpt);
            // make sure option 255(End) is the last option
            DhcpOption endOption = new DhcpOption();
            endOption.setCode(OptionCode_END.getValue());
            options.add(endOption);
            dhcpPacket.setOptions(options);
            relayAgentIp = serverInfo.getRelayAgentIp4(receivedFromDevice).orElse(null);
            // Sets relay agent IP
            int effectiveRelayAgentIp = relayAgentIp != null ? relayAgentIp.toInt() : clientInterfaceIp.toInt();
            dhcpPacket.setGatewayIPAddress(effectiveRelayAgentIp);
            log.debug("In Default, Relay Agent IP {}", effectiveRelayAgentIp);
        } else {
            if (!newServerInfo.getDhcpServerIp4().isPresent()) {
            // do nothing
            } else if (!newServerInfo.getDhcpConnectMac().isPresent()) {
                continue;
            } else {
                relayAgentIp = newServerInfo.getRelayAgentIp4(receivedFromDevice).orElse(null);
                // Sets relay agent IP
                int effectiveRelayAgentIp = relayAgentIp != null ? relayAgentIp.toInt() : clientInterfaceIp.toInt();
                Ip4Address effectiveRealRealyAgentIP = relayAgentIp != null ? relayAgentIp : clientInterfaceIp;
                dhcpPacket.setGatewayIPAddress(effectiveRelayAgentIp);
                ipv4Packet.setSourceAddress(effectiveRealRealyAgentIP.toInt());
                log.debug("Source IP address set as relay agent IP with value: {}", effectiveRealRealyAgentIP);
            }
        }
        // Remove broadcast flag
        dhcpPacket.setFlags((short) 0);
        udpPacket.setPayload(dhcpPacket);
        // As a DHCP relay, the source port should be server port( instead
        // of client port.
        udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
        udpPacket.setDestinationPort(UDP.DHCP_SERVER_PORT);
        ipv4Packet.setPayload(udpPacket);
        ipv4Packet.setTtl((byte) 64);
        etherReply.setPayload(ipv4Packet);
        InternalPacket internalPacket = InternalPacket.internalPacket(etherReply, serverInfo.getDhcpServerConnectPoint().get());
        internalPackets.add(internalPacket);
    }
    if (!serverFound) {
        log.warn("ProcessDhcp4PacketFromClient No Server Found");
    }
    return internalPackets;
}
Also used : DeviceService(org.onosproject.net.device.DeviceService) DefaultTrafficTreatment(org.onosproject.net.flow.DefaultTrafficTreatment) ConnectPoint(org.onosproject.net.ConnectPoint) ObjectiveError(org.onosproject.net.flowobjective.ObjectiveError) OptionCode_END(org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_END) IgnoreDhcpConfig(org.onosproject.dhcprelay.config.IgnoreDhcpConfig) Port(org.onosproject.net.Port) ApplicationId(org.onosproject.core.ApplicationId) DhcpRelayStore(org.onosproject.dhcprelay.store.DhcpRelayStore) Ip4Address(org.onlab.packet.Ip4Address) Deactivate(org.osgi.service.component.annotations.Deactivate) OptionCode_MessageType(org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_MessageType) Set(java.util.Set) MacAddress.valueOf(org.onlab.packet.MacAddress.valueOf) PacketService(org.onosproject.net.packet.PacketService) DhcpServerConfig(org.onosproject.dhcprelay.config.DhcpServerConfig) DeviceId(org.onosproject.net.DeviceId) LEARN_ROUTE_FROM_LEASE_QUERY_DEFAULT(org.onosproject.dhcprelay.OsgiPropertyConstants.LEARN_ROUTE_FROM_LEASE_QUERY_DEFAULT) Dictionary(java.util.Dictionary) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Pipeliner(org.onosproject.net.behaviour.Pipeliner) REMOVE(org.onosproject.net.flowobjective.Objective.Operation.REMOVE) HostProviderRegistry(org.onosproject.net.host.HostProviderRegistry) Tools(org.onlab.util.Tools) Host(org.onosproject.net.Host) RouteStore(org.onosproject.routeservice.RouteStore) ComponentContext(org.osgi.service.component.ComponentContext) LEARN_ROUTE_FROM_LEASE_QUERY(org.onosproject.dhcprelay.OsgiPropertyConstants.LEARN_ROUTE_FROM_LEASE_QUERY) HostListener(org.onosproject.net.host.HostListener) InterfaceService(org.onosproject.net.intf.InterfaceService) HostService(org.onosproject.net.host.HostService) Multimaps(com.google.common.collect.Multimaps) ArrayList(java.util.ArrayList) Component(org.osgi.service.component.annotations.Component) Lists(com.google.common.collect.Lists) TrafficSelector(org.onosproject.net.flow.TrafficSelector) CIRCUIT_ID(org.onlab.packet.dhcp.DhcpRelayAgentOption.RelayAgentInfoOptions.CIRCUIT_ID) OptionCode_CircuitID(org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_CircuitID) CircuitId(org.onlab.packet.dhcp.CircuitId) DhcpRelayAgentOption(org.onlab.packet.dhcp.DhcpRelayAgentOption) DefaultTrafficSelector(org.onosproject.net.flow.DefaultTrafficSelector) TpPort(org.onlab.packet.TpPort) ComponentConfigService(org.onosproject.cfg.ComponentConfigService) BasePacket(org.onlab.packet.BasePacket) Executor(java.util.concurrent.Executor) HostProvider(org.onosproject.net.host.HostProvider) VlanId(org.onlab.packet.VlanId) ProviderId(org.onosproject.net.provider.ProviderId) IPv4(org.onlab.packet.IPv4) DhcpRecord(org.onosproject.dhcprelay.store.DhcpRecord) Objective(org.onosproject.net.flowobjective.Objective) MacAddress(org.onlab.packet.MacAddress) DHCP(org.onlab.packet.DHCP) DefaultOutboundPacket(org.onosproject.net.packet.DefaultOutboundPacket) Route(org.onosproject.routeservice.Route) HostLocation(org.onosproject.net.HostLocation) Interface(org.onosproject.net.intf.Interface) CoreService(org.onosproject.core.CoreService) LoggerFactory(org.slf4j.LoggerFactory) Tools.groupedThreads(org.onlab.util.Tools.groupedThreads) ForwardingObjective(org.onosproject.net.flowobjective.ForwardingObjective) ByteBuffer(java.nio.ByteBuffer) Ethernet(org.onlab.packet.Ethernet) HostProviderService(org.onosproject.net.host.HostProviderService) HashMultimap(com.google.common.collect.HashMultimap) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DhcpServerInfo(org.onosproject.dhcprelay.api.DhcpServerInfo) ImmutableSet(com.google.common.collect.ImmutableSet) Device(org.onosproject.net.Device) Collection(java.util.Collection) Executors.newSingleThreadExecutor(java.util.concurrent.Executors.newSingleThreadExecutor) DefaultForwardingObjective(org.onosproject.net.flowobjective.DefaultForwardingObjective) InterfaceIpAddress(org.onosproject.net.host.InterfaceIpAddress) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) Preconditions.checkState(com.google.common.base.Preconditions.checkState) List(java.util.List) ObjectiveContext(org.onosproject.net.flowobjective.ObjectiveContext) PacketContext(org.onosproject.net.packet.PacketContext) Optional(java.util.Optional) HostDescription(org.onosproject.net.host.HostDescription) ADD(org.onosproject.net.flowobjective.Objective.Operation.ADD) Multimap(com.google.common.collect.Multimap) FlowObjectiveService(org.onosproject.net.flowobjective.FlowObjectiveService) DefaultHostDescription(org.onosproject.net.host.DefaultHostDescription) OutboundPacket(org.onosproject.net.packet.OutboundPacket) HostEvent(org.onosproject.net.host.HostEvent) Activate(org.osgi.service.component.annotations.Activate) HostId(org.onosproject.net.HostId) IpAddress(org.onlab.packet.IpAddress) TrafficTreatment(org.onosproject.net.flow.TrafficTreatment) Logger(org.slf4j.Logger) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) UDP(org.onlab.packet.UDP) DhcpHandler(org.onosproject.dhcprelay.api.DhcpHandler) DhcpOption(org.onlab.packet.dhcp.DhcpOption) ReferenceCardinality(org.osgi.service.component.annotations.ReferenceCardinality) Modified(org.osgi.service.component.annotations.Modified) PacketPriority(org.onosproject.net.packet.PacketPriority) Reference(org.osgi.service.component.annotations.Reference) Collections(java.util.Collections) DeviceId(org.onosproject.net.DeviceId) IPv4(org.onlab.packet.IPv4) Ip4Address(org.onlab.packet.Ip4Address) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) CircuitId(org.onlab.packet.dhcp.CircuitId) VlanId(org.onlab.packet.VlanId) DhcpServerInfo(org.onosproject.dhcprelay.api.DhcpServerInfo) UDP(org.onlab.packet.UDP) DhcpOption(org.onlab.packet.dhcp.DhcpOption) MacAddress(org.onlab.packet.MacAddress) ConnectPoint(org.onosproject.net.ConnectPoint) DHCP(org.onlab.packet.DHCP) ConnectPoint(org.onosproject.net.ConnectPoint) DhcpRelayAgentOption(org.onlab.packet.dhcp.DhcpRelayAgentOption) Ethernet(org.onlab.packet.Ethernet) InterfaceIpAddress(org.onosproject.net.host.InterfaceIpAddress) IpAddress(org.onlab.packet.IpAddress) Interface(org.onosproject.net.intf.Interface) InterfaceIpAddress(org.onosproject.net.host.InterfaceIpAddress)

Aggregations

DHCP (org.onlab.packet.DHCP)21 Ethernet (org.onlab.packet.Ethernet)17 IPv4 (org.onlab.packet.IPv4)12 UDP (org.onlab.packet.UDP)12 ArrayList (java.util.ArrayList)9 DhcpOption (org.onlab.packet.dhcp.DhcpOption)9 ConnectPoint (org.onosproject.net.ConnectPoint)9 Interface (org.onosproject.net.intf.Interface)9 Ip4Address (org.onlab.packet.Ip4Address)8 MacAddress (org.onlab.packet.MacAddress)8 Preconditions.checkNotNull (com.google.common.base.Preconditions.checkNotNull)7 ByteBuffer (java.nio.ByteBuffer)7 Collection (java.util.Collection)7 Optional (java.util.Optional)7 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)7 IpAddress (org.onlab.packet.IpAddress)7 VlanId (org.onlab.packet.VlanId)7 Preconditions.checkState (com.google.common.base.Preconditions.checkState)6 HashMultimap (com.google.common.collect.HashMultimap)6 ImmutableSet (com.google.common.collect.ImmutableSet)6