Java Code Examples for org.onlab.packet.Ethernet#setDestinationMACAddress()

The following examples show how to use org.onlab.packet.Ethernet#setDestinationMACAddress() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DhcpRelayManagerTest.java    From onos with Apache License 2.0 6 votes vote down vote up
public TestArpRequestPacketContext(Interface fromInterface) {
    super(0, null, null, false);
    ARP arp = new ARP();
    arp.setOpCode(ARP.OP_REQUEST);

    IpAddress targetIp = fromInterface.ipAddressesList().get(0).ipAddress();
    arp.setTargetProtocolAddress(targetIp.toOctets());
    arp.setTargetHardwareAddress(MacAddress.BROADCAST.toBytes());
    arp.setSenderHardwareAddress(MacAddress.NONE.toBytes());
    arp.setSenderProtocolAddress(Ip4Address.valueOf(0).toOctets());
    arp.setHardwareAddressLength((byte) MacAddress.MAC_ADDRESS_LENGTH);
    Ethernet eth = new Ethernet();
    eth.setEtherType(Ethernet.TYPE_ARP);
    eth.setSourceMACAddress(MacAddress.NONE);
    eth.setDestinationMACAddress(MacAddress.BROADCAST);
    eth.setVlanID(fromInterface.vlan().toShort());
    eth.setPayload(arp);

    this.inPacket = new DefaultInboundPacket(fromInterface.connectPoint(), eth,
                                             ByteBuffer.wrap(eth.serialize()));
}
 
Example 2
Source File: MQEventHandlerTest.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public InboundPacket inPacket() {
    ONOSLLDP lldp = ONOSLLDP.onosSecureLLDP(deviceService.getDevice(DID1)
                                      .id().toString(),
                                            device.chassisId(),
                                            (int) pd1.number().toLong(), "", "test");

    Ethernet ethPacket = new Ethernet();
    ethPacket.setEtherType(Ethernet.TYPE_LLDP);
    ethPacket.setDestinationMACAddress(MacAddress.ONOS_LLDP);
    ethPacket.setPayload(lldp);
    ethPacket.setPad(true);

    ethPacket.setSourceMACAddress("DE:AD:BE:EF:BA:11");

    ConnectPoint cp = new ConnectPoint(device.id(), pd3.number());

    return new DefaultInboundPacket(cp, ethPacket,
                                    ByteBuffer.wrap(ethPacket
                                    .serialize()));

}
 
Example 3
Source File: DhcpManager.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Processes the ARP Payload and initiates a reply to the client.
 *
 * @param context context of the incoming message
 * @param packet the ethernet payload
 */
private void processArpPacket(PacketContext context, Ethernet packet) {

    ARP arpPacket = (ARP) packet.getPayload();

    ARP arpReply = arpPacket.duplicate();
    arpReply.setOpCode(ARP.OP_REPLY);

    arpReply.setTargetProtocolAddress(arpPacket.getSenderProtocolAddress());
    arpReply.setTargetHardwareAddress(arpPacket.getSenderHardwareAddress());
    arpReply.setSenderProtocolAddress(arpPacket.getTargetProtocolAddress());
    arpReply.setSenderHardwareAddress(myMAC.toBytes());

    // Ethernet Frame.
    Ethernet ethReply = new Ethernet();
    ethReply.setSourceMACAddress(myMAC);
    ethReply.setDestinationMACAddress(packet.getSourceMAC());
    ethReply.setEtherType(Ethernet.TYPE_ARP);
    ethReply.setVlanID(packet.getVlanID());

    ethReply.setPayload(arpReply);
    sendReply(context, ethReply);
}
 
Example 4
Source File: DirectHostManager.java    From onos with Apache License 2.0 6 votes vote down vote up
private void transformAndSend(IP ip, short ethType,
                              Interface egressInterface,
                              MacAddress macAddress) {
    // Base processing for IPv4
    if (ethType == Ethernet.TYPE_IPV4) {
        IPv4 ipv4 = (IPv4) ip;
        ipv4.setTtl((byte) (ipv4.getTtl() - 1));
        ipv4.setChecksum((short) 0);
    // Base processing for IPv6.
    } else {
        IPv6 ipv6 = (IPv6) ip;
        ipv6.setHopLimit((byte) (ipv6.getHopLimit() - 1));
        ipv6.resetChecksum();
    }
    // Sends and serializes.
    Ethernet eth = new Ethernet();
    eth.setDestinationMACAddress(macAddress);
    eth.setSourceMACAddress(egressInterface.mac());
    eth.setEtherType(ethType);
    eth.setPayload(ip);
    if (!egressInterface.vlan().equals(VlanId.NONE)) {
        eth.setVlanID(egressInterface.vlan().toShort());
    }
    send(eth, egressInterface.connectPoint());
}
 
Example 5
Source File: OpenstackMetadataProxyHandler.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Builds an ethernet frame with the given IPv4 and TCP payload.
 *
 * @param ethRequest    ethernet request frame
 * @param ipv4Request   IPv4 request
 * @param tcpReply      TCP reply
 * @return an ethernet frame contains TCP payload
 */
private Ethernet buildEthFrame(Ethernet ethRequest, IPv4 ipv4Request,
                               TCP tcpReply) {
    Ethernet ethReply = new Ethernet();
    ethReply.setSourceMACAddress(ethRequest.getDestinationMAC());
    ethReply.setDestinationMACAddress(ethRequest.getSourceMAC());
    ethReply.setEtherType(ethRequest.getEtherType());

    IPv4 ipv4Reply = new IPv4();
    ipv4Reply.setSourceAddress(ipv4Request.getDestinationAddress());
    ipv4Reply.setDestinationAddress(ipv4Request.getSourceAddress());
    ipv4Reply.setTtl(PACKET_TTL);

    ipv4Reply.setPayload(tcpReply);
    ethReply.setPayload(ipv4Reply);

    return ethReply;
}
 
Example 6
Source File: NetworkConfigLinksProviderTest.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public InboundPacket inPacket() {
    ONOSLLDP lldp = ONOSLLDP.onosSecureLLDP(src.deviceId().toString(),
                                            new ChassisId(),
                                            (int) src.port().toLong(), "", "test-secret");

    Ethernet ethPacket = new Ethernet();
    ethPacket.setEtherType(Ethernet.TYPE_LLDP);
    ethPacket.setDestinationMACAddress(MacAddress.ONOS_LLDP);
    ethPacket.setPayload(lldp);
    ethPacket.setPad(true);

    ethPacket.setSourceMACAddress("DE:AD:BE:EF:BA:11");

    return new DefaultInboundPacket(dst, ethPacket,
                                    ByteBuffer.wrap(ethPacket.serialize()));

}
 
Example 7
Source File: LldpLinkProviderTest.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public InboundPacket inPacket() {
    ONOSLLDP lldp = ONOSLLDP.onosSecureLLDP(deviceService.getDevice(DID1).id().toString(),
                                            device.chassisId(),
                                            (int) pd1.number().toLong(), "", "test");

    Ethernet ethPacket = new Ethernet();
    ethPacket.setEtherType(Ethernet.TYPE_LLDP);
    ethPacket.setDestinationMACAddress(MacAddress.ONOS_LLDP);
    ethPacket.setPayload(lldp);
    ethPacket.setPad(true);

    ethPacket.setSourceMACAddress("DE:AD:BE:EF:BA:11");

    ConnectPoint cp = new ConnectPoint(device.id(), pd3.number());

    return new DefaultInboundPacket(cp, ethPacket,
                                    ByteBuffer.wrap(ethPacket.serialize()));

}
 
Example 8
Source File: OpenstackNetworkingUtil.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Returns GARP packet with supplied floating ip and instance port information.
 *
 * @param floatingIP floating ip
 * @param instancePort instance port
 * @param vlanId vlan id
 * @return GARP packet
 */
private static Ethernet buildGratuitousArpPacket(NetFloatingIP floatingIP,
                                                 InstancePort instancePort,
                                                 VlanId vlanId) {
    Ethernet ethernet = new Ethernet();
    ethernet.setDestinationMACAddress(MacAddress.BROADCAST);
    ethernet.setSourceMACAddress(instancePort.macAddress());
    ethernet.setEtherType(Ethernet.TYPE_ARP);
    ethernet.setVlanID(vlanId.id());

    ARP arp = new ARP();
    arp.setOpCode(ARP.OP_REPLY);
    arp.setProtocolType(ARP.PROTO_TYPE_IP);
    arp.setHardwareType(ARP.HW_TYPE_ETHERNET);

    arp.setProtocolAddressLength((byte) Ip4Address.BYTE_LENGTH);
    arp.setHardwareAddressLength((byte) Ethernet.DATALAYER_ADDRESS_LENGTH);

    arp.setSenderHardwareAddress(instancePort.macAddress().toBytes());
    arp.setTargetHardwareAddress(MacAddress.BROADCAST.toBytes());

    arp.setSenderProtocolAddress(valueOf(floatingIP.getFloatingIpAddress()).toInt());
    arp.setTargetProtocolAddress(valueOf(floatingIP.getFloatingIpAddress()).toInt());

    ethernet.setPayload(arp);

    return ethernet;
}
 
Example 9
Source File: DhcpRelayManager.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Processes the ARP Payload and initiates a reply to the client.
 *
 * @param context the packet context
 * @param packet the ethernet payload
 * @param replyMac mac address to be replied
 */
private void processArpPacket(PacketContext context, Ethernet packet, MacAddress replyMac) {
    ARP arpPacket = (ARP) packet.getPayload();
    ARP arpReply = arpPacket.duplicate();
    arpReply.setOpCode(ARP.OP_REPLY);

    arpReply.setTargetProtocolAddress(arpPacket.getSenderProtocolAddress());
    arpReply.setTargetHardwareAddress(arpPacket.getSenderHardwareAddress());
    arpReply.setSenderProtocolAddress(arpPacket.getTargetProtocolAddress());
    arpReply.setSenderHardwareAddress(replyMac.toBytes());

    // Ethernet Frame.
    Ethernet ethReply = new Ethernet();
    ethReply.setSourceMACAddress(replyMac.toBytes());
    ethReply.setDestinationMACAddress(packet.getSourceMAC());
    ethReply.setEtherType(Ethernet.TYPE_ARP);
    ethReply.setVlanID(packet.getVlanID());
    ethReply.setPayload(arpReply);

    ConnectPoint targetPort = context.inPacket().receivedFrom();
    TrafficTreatment t = DefaultTrafficTreatment.builder()
            .setOutput(targetPort.port()).build();
    OutboundPacket o = new DefaultOutboundPacket(
            targetPort.deviceId(), t, ByteBuffer.wrap(ethReply.serialize()));
    if (log.isTraceEnabled()) {
        log.trace("Relaying ARP packet {} to {}", packet, targetPort);
    }
    packetService.emit(o);
}
 
Example 10
Source File: IcmpHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
private void sendIcmpResponse(Ethernet icmpRequest, ConnectPoint outport) {

        Ethernet icmpReplyEth = new Ethernet();

        IPv4 icmpRequestIpv4 = (IPv4) icmpRequest.getPayload();
        IPv4 icmpReplyIpv4 = new IPv4();

        int destAddress = icmpRequestIpv4.getDestinationAddress();
        icmpReplyIpv4.setDestinationAddress(icmpRequestIpv4.getSourceAddress());
        icmpReplyIpv4.setSourceAddress(destAddress);
        icmpReplyIpv4.setTtl((byte) 64);
        icmpReplyIpv4.setChecksum((short) 0);

        ICMP icmpReply = new ICMP();
        icmpReply.setPayload(((ICMP) icmpRequestIpv4.getPayload()).getPayload());
        icmpReply.setIcmpType(ICMP.TYPE_ECHO_REPLY);
        icmpReply.setIcmpCode(ICMP.CODE_ECHO_REPLY);
        icmpReply.setChecksum((short) 0);

        icmpReplyIpv4.setPayload(icmpReply);

        icmpReplyEth.setPayload(icmpReplyIpv4);
        icmpReplyEth.setEtherType(Ethernet.TYPE_IPV4);
        icmpReplyEth.setDestinationMACAddress(icmpRequest.getSourceMACAddress());
        icmpReplyEth.setSourceMACAddress(icmpRequest.getDestinationMACAddress());
        icmpReplyEth.setVlanID(icmpRequest.getVlanID());

        sendPacketOut(outport, icmpReplyEth);

    }
 
Example 11
Source File: IpHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Forwards IP packets in the buffer to the destination IP address.
 * It is called when the controller finds the destination MAC address
 * via NDP replies.
 *
 * @param deviceId the target device
 * @param destIpAddress the destination ip address
 */
public void forwardPackets(DeviceId deviceId, Ip6Address destIpAddress) {
    if (ipPacketQueue.get(destIpAddress) == null) {
        return;
    }
    for (IP ipPacket : ipPacketQueue.get(destIpAddress)) {
        if (ipPacket.getVersion() == ((byte) 6)) {
            IPv6 ipv6Packet = (IPv6) ipPacket;
            Ip6Address destAddress = Ip6Address.valueOf(ipv6Packet.getDestinationAddress());
            if (config.inSameSubnet(deviceId, destAddress)) {
                ipv6Packet.setHopLimit((byte) (ipv6Packet.getHopLimit() - 1));
                for (Host dest : srManager.hostService.getHostsByIp(destIpAddress)) {
                    Ethernet eth = new Ethernet();
                    eth.setDestinationMACAddress(dest.mac());
                    try {
                        eth.setSourceMACAddress(config.getDeviceMac(deviceId));
                    } catch (DeviceConfigNotFoundException e) {
                        log.warn(e.getMessage()
                                         + " Skipping forwardPackets for this destination.");
                        continue;
                    }
                    eth.setEtherType(Ethernet.TYPE_IPV6);
                    eth.setPayload(ipv6Packet);
                    forwardToHost(deviceId, eth, dest);
                    ipPacketQueue.get(destIpAddress).remove(ipPacket);
                }
                ipPacketQueue.get(destIpAddress).remove(ipPacket);
            }
        }
        ipPacketQueue.get(destIpAddress).remove(ipPacket);
    }
}
 
Example 12
Source File: NeighborAdvertisementTest.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Test Neighbor Advertisement reply build.
 */
@Test
public void testBuildNdpAdv() {
    Ethernet eth = new Ethernet();
    eth.setSourceMACAddress(MAC_ADDRESS);
    eth.setDestinationMACAddress(MAC_ADDRESS2);

    IPv6 ipv6 = new IPv6();
    ipv6.setSourceAddress(IPV6_SOURCE_ADDRESS);
    ipv6.setDestinationAddress(IPV6_DESTINATION_ADDRESS);
    ipv6.setNextHeader(IPv6.PROTOCOL_ICMP6);

    eth.setEtherType(Ethernet.TYPE_IPV6);
    eth.setPayload(ipv6);

    ICMP6 icmp6 = new ICMP6();
    icmp6.setIcmpType(ICMP6.NEIGHBOR_SOLICITATION);
    icmp6.setIcmpCode(NeighborAdvertisement.RESERVED_CODE);
    ipv6.setPayload(icmp6);

    final Ethernet ethResponse = NeighborAdvertisement.buildNdpAdv(IP_6_ADDRESS, MAC_ADDRESS2, eth);

    assertTrue(ethResponse.getDestinationMAC().equals(MAC_ADDRESS));
    assertTrue(ethResponse.getSourceMAC().equals(MAC_ADDRESS2));
    assertTrue(ethResponse.getEtherType() == Ethernet.TYPE_IPV6);

    final IPv6 responseIpv6 = (IPv6) ethResponse.getPayload();

    assertArrayEquals(responseIpv6.getSourceAddress(), ipv6.getDestinationAddress());
    assertArrayEquals(responseIpv6.getDestinationAddress(), ipv6.getSourceAddress());
    assertTrue(responseIpv6.getNextHeader() == IPv6.PROTOCOL_ICMP6);

    final ICMP6 responseIcmp6 = (ICMP6) responseIpv6.getPayload();

    assertTrue(responseIcmp6.getIcmpType() == ICMP6.NEIGHBOR_ADVERTISEMENT);
    assertTrue(responseIcmp6.getIcmpCode() == NeighborAdvertisement.RESERVED_CODE);

    final NeighborAdvertisement responseNadv = (NeighborAdvertisement) responseIcmp6.getPayload();

    assertArrayEquals(responseNadv.getTargetAddress(), IPV6_DESTINATION_ADDRESS);
    assertTrue(responseNadv.getSolicitedFlag() == NeighborAdvertisement.NDP_SOLICITED_FLAG);
    assertTrue(responseNadv.getOverrideFlag() == NeighborAdvertisement.NDP_OVERRIDE_FLAG);
    assertThat(responseNadv.getOptions(),
            hasItem(hasOption(NeighborDiscoveryOptions.TYPE_TARGET_LL_ADDRESS, MAC_ADDRESS2.toBytes())));
}
 
Example 13
Source File: Dhcp6Test.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Test serialize request message.
 *
 * @throws Exception exception while serialize the DHCPv6 payload
 */
@Test
public void serializeRequest() throws Exception {
    DHCP6 dhcp6 = new DHCP6();
    dhcp6.setMsgType(DHCP6.MsgType.REQUEST.value());
    dhcp6.setTransactionId(XID_2);
    List<Dhcp6Option> options = Lists.newArrayList();

    // Client ID
    Dhcp6Duid duid = new Dhcp6Duid();
    duid.setDuidType(Dhcp6Duid.DuidType.DUID_LLT);
    duid.setHardwareType((short) 1);
    duid.setDuidTime(CLIENT_DUID_TIME);
    duid.setLinkLayerAddress(CLIENT_MAC.toBytes());
    Dhcp6ClientIdOption clientIdOption = new Dhcp6ClientIdOption();
    clientIdOption.setDuid(duid);
    options.add(clientIdOption);

    // Server ID
    Dhcp6Option option = new Dhcp6Option();
    option.setCode(DHCP6.OptionCode.SERVERID.value());
    option.setLength((short) 14);
    Dhcp6Duid serverDuid = new Dhcp6Duid();
    serverDuid.setDuidType(Dhcp6Duid.DuidType.DUID_LLT);
    serverDuid.setLinkLayerAddress(SERVER_MAC.toBytes());
    serverDuid.setHardwareType((short) 1);
    serverDuid.setDuidTime(0x211e5340);
    option.setData(serverDuid.serialize());
    options.add(option);

    // Option request
    option = new Dhcp6Option();
    option.setCode(DHCP6.OptionCode.ORO.value());
    option.setLength((short) 8);
    option.setData(new byte[]{0, 23, 0, 24, 0, 39, 0, 31});
    options.add(option);

    // Elapsed Time
    option = new Dhcp6Option();
    option.setCode(DHCP6.OptionCode.ELAPSED_TIME.value());
    option.setLength((short) 2);
    option.setData(new byte[]{0, 0});
    options.add(option);

    // IA address
    Dhcp6IaAddressOption iaAddressOption = new Dhcp6IaAddressOption();
    iaAddressOption.setIp6Address(IA_ADDRESS);
    iaAddressOption.setPreferredLifetime(PREFFERRED_LT_REQ);
    iaAddressOption.setValidLifetime(VALID_LT_REQ_2);

    // IA NA
    Dhcp6IaNaOption iaNaOption = new Dhcp6IaNaOption();
    iaNaOption.setIaId(IA_ID);
    iaNaOption.setT1(T1_CLIENT);
    iaNaOption.setT2(T2_CLIENT);
    iaNaOption.setOptions(ImmutableList.of(iaAddressOption));
    options.add(iaNaOption);

    dhcp6.setOptions(options);

    Dhcp6RelayOption relayOption = new Dhcp6RelayOption();
    relayOption.setPayload(dhcp6);

    UDP udp = new UDP();
    udp.setSourcePort(UDP.DHCP_V6_CLIENT_PORT);
    udp.setDestinationPort(UDP.DHCP_V6_SERVER_PORT);
    udp.setPayload(dhcp6);
    udp.setChecksum((short) 0xffc1);

    IPv6 ipv6 = new IPv6();
    ipv6.setHopLimit((byte) 1);
    ipv6.setSourceAddress(CLIENT_LL.toOctets());
    ipv6.setDestinationAddress(DHCP6_BRC.toOctets());
    ipv6.setNextHeader(IPv6.PROTOCOL_UDP);
    ipv6.setTrafficClass((byte) 0);
    ipv6.setFlowLabel(0x000322ad);
    ipv6.setPayload(udp);

    Ethernet eth = new Ethernet();
    eth.setDestinationMACAddress(IPV6_MCAST);
    eth.setSourceMACAddress(CLIENT_MAC);
    eth.setEtherType(Ethernet.TYPE_IPV6);
    eth.setPayload(ipv6);

    assertArrayEquals(Resources.toByteArray(Dhcp6RelayTest.class.getResource(REQUEST)),
                      eth.serialize());
}
 
Example 14
Source File: Dhcp6Test.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Test serialize advertise message.
 *
 * @throws Exception exception while serialize the DHCPv6 payload
 */
@Test
public void serializeAdvertise() throws Exception {
    DHCP6 dhcp6 = new DHCP6();
    dhcp6.setMsgType(DHCP6.MsgType.ADVERTISE.value());
    dhcp6.setTransactionId(XID_1);
    List<Dhcp6Option> options = Lists.newArrayList();

    // IA address
    Dhcp6IaAddressOption iaAddressOption = new Dhcp6IaAddressOption();
    iaAddressOption.setIp6Address(IA_ADDRESS);
    iaAddressOption.setPreferredLifetime(PREFFERRED_LT_SERVER);
    iaAddressOption.setValidLifetime(VALID_LT_SERVER);

    // IA NA
    Dhcp6IaNaOption iaNaOption = new Dhcp6IaNaOption();
    iaNaOption.setIaId(IA_ID);
    iaNaOption.setT1(T1_SERVER);
    iaNaOption.setT2(T2_SERVER);
    iaNaOption.setOptions(ImmutableList.of(iaAddressOption));
    options.add(iaNaOption);

    // Client ID
    Dhcp6Duid duid = new Dhcp6Duid();
    duid.setDuidType(Dhcp6Duid.DuidType.DUID_LLT);
    duid.setHardwareType((short) 1);
    duid.setDuidTime(CLIENT_DUID_TIME);
    duid.setLinkLayerAddress(CLIENT_MAC.toBytes());
    Dhcp6ClientIdOption clientIdOption = new Dhcp6ClientIdOption();
    clientIdOption.setDuid(duid);
    options.add(clientIdOption);

    // Server ID
    Dhcp6Option option = new Dhcp6Option();
    option.setCode(DHCP6.OptionCode.SERVERID.value());
    option.setLength((short) 14);
    Dhcp6Duid serverDuid = new Dhcp6Duid();
    serverDuid.setDuidType(Dhcp6Duid.DuidType.DUID_LLT);
    serverDuid.setLinkLayerAddress(SERVER_MAC.toBytes());
    serverDuid.setHardwareType((short) 1);
    serverDuid.setDuidTime(0x211e5340);
    option.setData(serverDuid.serialize());
    options.add(option);

    dhcp6.setOptions(options);

    Dhcp6RelayOption relayOption = new Dhcp6RelayOption();
    relayOption.setPayload(dhcp6);

    UDP udp = new UDP();
    udp.setSourcePort(UDP.DHCP_V6_SERVER_PORT);
    udp.setDestinationPort(UDP.DHCP_V6_CLIENT_PORT);
    udp.setPayload(dhcp6);
    udp.setChecksum((short) 0xcb5a);

    IPv6 ipv6 = new IPv6();
    ipv6.setHopLimit((byte) 64);
    ipv6.setSourceAddress(UPSTREAM_LL.toOctets());
    ipv6.setDestinationAddress(CLIENT_LL.toOctets());
    ipv6.setNextHeader(IPv6.PROTOCOL_UDP);
    ipv6.setTrafficClass((byte) 0);
    ipv6.setFlowLabel(0x000d935f);
    ipv6.setPayload(udp);

    Ethernet eth = new Ethernet();
    eth.setDestinationMACAddress(CLIENT_MAC);
    eth.setSourceMACAddress(UPSTREAM_MAC);
    eth.setEtherType(Ethernet.TYPE_IPV6);
    eth.setPayload(ipv6);

    assertArrayEquals(Resources.toByteArray(Dhcp6RelayTest.class.getResource(ADVERTISE)),
                      eth.serialize());
}
 
Example 15
Source File: OpenstackSwitchingDhcpHandler.java    From onos with Apache License 2.0 4 votes vote down vote up
private Ethernet buildReply(Ethernet ethRequest, byte packetType,
                            Port port) {
    log.trace("Build for DHCP reply msg for openstack port {}", port.toString());

    // pick one IP address to make a reply
    // since we check the validity of fixed IP address at parent method,
    // so no need to double check the fixed IP existence here
    IP fixedIp = port.getFixedIps().stream().findFirst().get();

    Subnet osSubnet = osNetworkService.subnet(fixedIp.getSubnetId());

    Ethernet ethReply = new Ethernet();
    ethReply.setSourceMACAddress(dhcpServerMac);
    ethReply.setDestinationMACAddress(ethRequest.getSourceMAC());
    ethReply.setEtherType(Ethernet.TYPE_IPV4);

    IPv4 ipv4Request = (IPv4) ethRequest.getPayload();
    IPv4 ipv4Reply = new IPv4();

    ipv4Reply.setSourceAddress(
            clusterService.getLocalNode().ip().getIp4Address().toString());
    ipv4Reply.setDestinationAddress(fixedIp.getIpAddress());
    ipv4Reply.setTtl(PACKET_TTL);

    UDP udpRequest = (UDP) ipv4Request.getPayload();
    UDP udpReply = new UDP();
    udpReply.setSourcePort((byte) UDP.DHCP_SERVER_PORT);
    udpReply.setDestinationPort((byte) UDP.DHCP_CLIENT_PORT);

    DHCP dhcpRequest = (DHCP) udpRequest.getPayload();
    DHCP dhcpReply = buildDhcpReply(
            dhcpRequest,
            packetType,
            Ip4Address.valueOf(fixedIp.getIpAddress()),
            (NeutronPort) port, osSubnet);

    udpReply.setPayload(dhcpReply);
    ipv4Reply.setPayload(udpReply);
    ethReply.setPayload(ipv4Reply);

    return ethReply;
}
 
Example 16
Source File: DhcpManagerTest.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Constructs an Ethernet packet containing a DHCP Payload.
 * @param packetType DHCP Message Type
 * @return Ethernet packet
 */
private Ethernet constructDhcpPacket(DHCP.MsgType packetType) {

    // Ethernet Frame.
    Ethernet ethReply = new Ethernet();
    ethReply.setSourceMACAddress(CLIENT1_HOST.mac());
    ethReply.setDestinationMACAddress(MacAddress.BROADCAST);
    ethReply.setEtherType(Ethernet.TYPE_IPV4);
    ethReply.setVlanID((short) 2);

    // IP Packet
    IPv4 ipv4Reply = new IPv4();
    ipv4Reply.setSourceAddress(0);
    ipv4Reply.setDestinationAddress(BROADCAST.toInt());
    ipv4Reply.setTtl((byte) 127);

    // UDP Datagram.
    UDP udpReply = new UDP();
    udpReply.setSourcePort((byte) UDP.DHCP_CLIENT_PORT);
    udpReply.setDestinationPort((byte) UDP.DHCP_SERVER_PORT);

    // DHCP Payload.
    DHCP dhcpReply = new DHCP();
    dhcpReply.setOpCode(DHCP.OPCODE_REQUEST);

    dhcpReply.setYourIPAddress(0);
    dhcpReply.setServerIPAddress(0);

    dhcpReply.setTransactionId(TRANSACTION_ID);
    dhcpReply.setClientHardwareAddress(CLIENT1_HOST.mac().toBytes());
    dhcpReply.setHardwareType(DHCP.HWTYPE_ETHERNET);
    dhcpReply.setHardwareAddressLength((byte) 6);

    // DHCP Options.
    DhcpOption option = new DhcpOption();
    List<DhcpOption> optionList = new ArrayList<>();

    // DHCP Message Type.
    option.setCode(DHCP.DHCPOptionCode.OptionCode_MessageType.getValue());
    option.setLength((byte) 1);
    byte[] optionData = {(byte) packetType.getValue()};
    option.setData(optionData);
    optionList.add(option);

    // DHCP Requested IP.
    option = new DhcpOption();
    option.setCode(DHCP.DHCPOptionCode.OptionCode_RequestedIP.getValue());
    option.setLength((byte) 4);
    optionData = Ip4Address.valueOf(EXPECTED_IP).toOctets();
    option.setData(optionData);
    optionList.add(option);

    // End Option.
    option = new DhcpOption();
    option.setCode(DHCP.DHCPOptionCode.OptionCode_END.getValue());
    option.setLength((byte) 1);
    optionList.add(option);

    dhcpReply.setOptions(optionList);

    udpReply.setPayload(dhcpReply);
    ipv4Reply.setPayload(udpReply);
    ethReply.setPayload(ipv4Reply);

    return ethReply;
}
 
Example 17
Source File: Dhcp6HandlerImpl.java    From onos with Apache License 2.0 4 votes vote down vote up
private List<InternalPacket> processLQ6PacketFromClient(PacketContext context,
                                                          Ethernet clientPacket,
                                                          Set<Interface> clientInterfaces,
                                                          DHCP6 dhcp6Payload) {
    ConnectPoint inPort = context.inPacket().receivedFrom();
    log.info("Got LQ-REQUEST V6 on port {}", inPort);
    List<Dhcp6Option> lopt = dhcp6Payload.getOptions();
    log.info("Options list: {}", lopt);
    Dhcp6LeaseQueryOption lqoption = dhcp6Payload.getOptions()
            .stream()
            .filter(opt -> opt instanceof Dhcp6LeaseQueryOption)
            .map(pld -> (Dhcp6LeaseQueryOption) pld)
            .findFirst()
            .orElse(null);

    if (lqoption == null) {
        // Can't find dhcp payload
        log.warn("Can't find dhcp6 lease query message - aborting");
        return null;
    } else {
        log.info("dhcp6 lqv6 options found: {}", lqoption);
    }
    log.warn("LQv6 for " + lqoption.linkAddress.toString() + " comes from " + inPort.toString());
    Ethernet packet = context.inPacket().parsed();
    Ip6Address clientAddress = lqoption.linkAddress;
    IPv6 ipv6Packet = (IPv6) packet.getPayload();
    Ip6Address nextHopIp = findNextHopIp6FromRelayStore(clientAddress);

    // 1. only if there is a route to remove - remove it
    if (nextHopIp != null) {
        Route routeForIP6 = new Route(Route.Source.DHCP, clientAddress.toIpPrefix(), nextHopIp);
        log.debug("Removing route of Client " + clientAddress +
                          " for indirectly connected - next hop ip6 " + nextHopIp);
        routeStore.removeRoute(routeForIP6);
    }

    // 2. note the potential NH this packet came from in case it's a known lease
    //    this NH will then be used to build the route
    MacAddress potentialNH = packet.getSourceMAC();
    VlanId vlanId = VlanId.vlanId(packet.getVlanID());
    setPotentialNextHopForIp6InRelayStore(clientAddress, vlanId, potentialNH);
    // 3. route this LQ6 to all relevant servers
    IPv6 clientIpv6 = (IPv6) clientPacket.getPayload();
    UDP clientUdp = (UDP) clientIpv6.getPayload();
    DHCP6 clientDhcp6 = (DHCP6) clientUdp.getPayload();

    boolean directConnFlag = Dhcp6HandlerUtil.directlyConnected(clientDhcp6);
    boolean serverFound = false;
    List<InternalPacket> internalPackets = new ArrayList<>();
    List<DhcpServerInfo> serverInfoList = findValidServerInfo(directConnFlag);
    List<DhcpServerInfo> copyServerInfoList = new ArrayList<DhcpServerInfo>(serverInfoList);

    for (DhcpServerInfo serverInfo : copyServerInfoList) {
        if (!Dhcp6HandlerUtil.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;
        }

        serverFound = true;
        log.debug("Server Info Found {}", serverInfo.getDhcpConnectMac());
        Ethernet etherRouted = (Ethernet) clientPacket.clone();
        MacAddress macFacingServer = serverInterface.mac();
        if (macFacingServer == null) {
            log.warn("No MAC address for server Interface {}", serverInterface);
            return null;
        }
        etherRouted.setSourceMACAddress(macFacingServer);
        etherRouted.setDestinationMACAddress(newServerInfo.getDhcpConnectMac().get());
        InternalPacket internalPacket =
                InternalPacket.internalPacket(etherRouted,
                          serverInfo.getDhcpServerConnectPoint().get());
        internalPackets.add(internalPacket);
        log.debug("Sending LQ to DHCP server {}", newServerInfo.getDhcpServerIp6());
    }
    if (!serverFound) {
        log.warn("ProcessDhcp6PacketFromClient No Server Found");
    }
    log.debug("num of client packets to send is{}", internalPackets.size());

    return internalPackets;
}
 
Example 18
Source File: OpenstackRoutingSnatHandler.java    From onos with Apache License 2.0 4 votes vote down vote up
private void packetOut(Ethernet ethPacketIn, DeviceId srcDevice, int patPort,
                       IpAddress externalIp, ExternalPeerRouter externalPeerRouter) {
    IPv4 iPacket = (IPv4) ethPacketIn.getPayload();
    switch (iPacket.getProtocol()) {
        case IPv4.PROTOCOL_TCP:
            iPacket.setPayload(buildPacketOutTcp(iPacket, patPort));
            break;
        case IPv4.PROTOCOL_UDP:
            iPacket.setPayload(buildPacketOutUdp(iPacket, patPort));
            break;
        default:
            log.trace("Temporally, this method can process UDP and TCP protocol.");
            return;
    }

    iPacket.setSourceAddress(externalIp.toString());
    iPacket.resetChecksum();
    iPacket.setParent(ethPacketIn);
    ethPacketIn.setSourceMACAddress(DEFAULT_GATEWAY_MAC);
    ethPacketIn.setDestinationMACAddress(externalPeerRouter.macAddress());
    ethPacketIn.setPayload(iPacket);

    if (!externalPeerRouter.vlanId().equals(VlanId.NONE)) {
        ethPacketIn.setVlanID(externalPeerRouter.vlanId().toShort());
    }

    ethPacketIn.resetChecksum();

    OpenstackNode srcNode = osNodeService.node(srcDevice);
    if (srcNode == null) {
        final String error = String.format("Cannot find openstack node for %s",
                srcDevice);
        throw new IllegalStateException(error);
    }

    TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();

    packetService.emit(new DefaultOutboundPacket(
            srcDevice,
            tBuilder.setOutput(srcNode.uplinkPortNum()).build(),
            ByteBuffer.wrap(ethPacketIn.serialize())));
}
 
Example 19
Source File: Dhcp6RelayTest.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Test serialize relay message with solicit message.
 *
 * @throws Exception exception while serialize the DHCPv6 payload
 */
@Test
public void serializeSolicit() throws Exception {
    DHCP6 relayMsg = new DHCP6();
    relayMsg.setMsgType(DHCP6.MsgType.RELAY_FORW.value());
    relayMsg.setHopCount((byte) HOP_COUNT);
    relayMsg.setLinkAddress(LINK_ADDRESS.toOctets());
    relayMsg.setPeerAddress(PEER_ADDRESS.toOctets());

    DHCP6 relaiedDhcp6 = new DHCP6();
    relaiedDhcp6.setMsgType(DHCP6.MsgType.SOLICIT.value());
    relaiedDhcp6.setTransactionId(XID_1);
    List<Dhcp6Option> options = Lists.newArrayList();

    // Client ID
    Dhcp6Duid duid = new Dhcp6Duid();
    duid.setDuidType(Dhcp6Duid.DuidType.DUID_LLT);
    duid.setHardwareType((short) 1);
    duid.setDuidTime(CLIENT_DUID_TIME);
    duid.setLinkLayerAddress(CLIENT_MAC.toBytes());
    Dhcp6ClientIdOption clientIdOption = new Dhcp6ClientIdOption();
    clientIdOption.setDuid(duid);
    options.add(clientIdOption);

    // Option request
    Dhcp6Option option = new Dhcp6Option();
    option.setCode(DHCP6.OptionCode.ORO.value());
    option.setLength((short) 8);
    option.setData(new byte[]{0, 23, 0, 24, 0, 39, 0, 31});
    options.add(option);

    // Elapsed Time
    option = new Dhcp6Option();
    option.setCode(DHCP6.OptionCode.ELAPSED_TIME.value());
    option.setLength((short) 2);
    option.setData(new byte[]{0, 0});
    options.add(option);

    // IA NA
    Dhcp6IaNaOption iaNaOption = new Dhcp6IaNaOption();
    iaNaOption.setIaId(IA_ID);
    iaNaOption.setT1(T1_CLIENT);
    iaNaOption.setT2(T2_CLIENT);
    Dhcp6IaAddressOption iaAddressOption = new Dhcp6IaAddressOption();
    iaAddressOption.setIp6Address(IA_ADDRESS);
    iaAddressOption.setPreferredLifetime(PREFFERRED_LT_REQ);
    iaAddressOption.setValidLifetime(VALID_LT_REQ);
    iaNaOption.setOptions(ImmutableList.of(iaAddressOption));
    options.add(iaNaOption);
    relaiedDhcp6.setOptions(options);

    Dhcp6RelayOption relayOption = new Dhcp6RelayOption();
    relayOption.setPayload(relaiedDhcp6);

    Dhcp6Option subscriberId = new Dhcp6Option();
    subscriberId.setCode(DHCP6.OptionCode.SUBSCRIBER_ID.value());
    subscriberId.setLength((short) 10);
    subscriberId.setData(SERVER_IP.toString().getBytes(US_ASCII));

    relayMsg.setOptions(ImmutableList.of(subscriberId, relayOption));

    UDP udp = new UDP();
    udp.setSourcePort(UDP.DHCP_V6_SERVER_PORT);
    udp.setDestinationPort(UDP.DHCP_V6_SERVER_PORT);
    udp.setPayload(relayMsg);
    udp.setChecksum((short) 0x9a99);

    IPv6 ipv6 = new IPv6();
    ipv6.setHopLimit((byte) 32);
    ipv6.setSourceAddress(DOWNSTREAM_LL.toOctets());
    ipv6.setDestinationAddress(DHCP6_BRC.toOctets());
    ipv6.setNextHeader(IPv6.PROTOCOL_UDP);
    ipv6.setTrafficClass((byte) 0);
    ipv6.setFlowLabel(0x000cbf64);
    ipv6.setPayload(udp);

    Ethernet eth = new Ethernet();
    eth.setDestinationMACAddress(IPV6_MCAST);
    eth.setSourceMACAddress(DOWNSTREAM_MAC);
    eth.setEtherType(Ethernet.TYPE_IPV6);
    eth.setPayload(ipv6);

    assertArrayEquals(Resources.toByteArray(Dhcp6RelayTest.class.getResource(SOLICIT)),
                      eth.serialize());
}
 
Example 20
Source File: OpenstackRoutingSnatIcmpHandlerTest.java    From onos with Apache License 2.0 4 votes vote down vote up
private Ethernet constructIcmpRequestPacket(IpAddress srcIp,
                                            MacAddress srcMac,
                                            IpAddress dstIp,
                                            MacAddress dstMac, byte icmpType) {
    try {
        ICMPEcho icmpEcho = new ICMPEcho();
        icmpEcho.setIdentifier((short) 0)
                .setSequenceNum((short) 0);
        ByteBuffer byteBufferIcmpEcho = ByteBuffer.wrap(icmpEcho.serialize());

        ICMP icmp = new ICMP();
        icmp.setIcmpType(icmpType)
                .setIcmpCode(icmpType == TYPE_ECHO_REQUEST ? CODE_ECHO_REQUEST : CODE_ECHO_REPLY)
                .setChecksum((short) 0);

        icmp.setPayload(ICMPEcho.deserializer().deserialize(byteBufferIcmpEcho.array(),
                0, ICMPEcho.ICMP_ECHO_HEADER_LENGTH));

        ByteBuffer byteBufferIcmp = ByteBuffer.wrap(icmp.serialize());

        IPv4 iPacket = new IPv4();
        iPacket.setDestinationAddress(dstIp.toString());
        iPacket.setSourceAddress(srcIp.toString());
        iPacket.setTtl((byte) 64);
        iPacket.setChecksum((short) 0);
        iPacket.setDiffServ((byte) 0);
        iPacket.setProtocol(IPv4.PROTOCOL_ICMP);

        iPacket.setPayload(ICMP.deserializer().deserialize(byteBufferIcmp.array(), 0, 8));

        Ethernet ethPacket = new Ethernet();

        ethPacket.setEtherType(TYPE_IPV4);
        ethPacket.setSourceMACAddress(srcMac);
        ethPacket.setDestinationMACAddress(dstMac);
        ethPacket.setPayload(iPacket);

        return ethPacket;
    } catch (DeserializationException e) {
        return null;
    }
}