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

The following examples show how to use org.onlab.packet.Ethernet#setSourceMACAddress() . 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: EthernetCodecTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Unit test for the ethernet object codec.
 */
@Test
public void ethernetCodecTest() {
    final CodecContext context = new MockCodecContext();
    final JsonCodec<Ethernet> ethernetCodec = context.codec(Ethernet.class);
    assertThat(ethernetCodec, notNullValue());

    final Ethernet eth1 = new Ethernet();
    eth1.setSourceMACAddress("11:22:33:44:55:01");
    eth1.setDestinationMACAddress("11:22:33:44:55:02");
    eth1.setPad(true);
    eth1.setEtherType(Ethernet.TYPE_ARP);
    eth1.setPriorityCode((byte) 7);
    eth1.setVlanID((short) 33);

    final ObjectNode eth1Json = ethernetCodec.encode(eth1, context);
    assertThat(eth1Json, notNullValue());
    assertThat(eth1Json, matchesEthernet(eth1));
}
 
Example 2
Source File: DefaultNeighbourMessageActionsTest.java    From onos with Apache License 2.0 6 votes vote down vote up
@Test
public void forwardToInterface() {
    Ethernet request = NeighbourTestUtils.createArpRequest(IP1);

    Ethernet forwardedRequest = request.duplicate();
    forwardedRequest.setSourceMACAddress(INTF2.mac());
    forwardedRequest.setVlanID(INTF2.vlan().toShort());

    packetService.emit(outbound(forwardedRequest, CP2));
    expectLastCall().once();
    replay(packetService);

    actions.forward(createContext(request, CP1, null), INTF2);

    verify(packetService);
}
 
Example 3
Source File: NeighbourTestUtils.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an ARP request for the given target IP.
 *
 * @param targetIp IP address
 * @return ARP request packet
 */
public static Ethernet createArpRequest(IpAddress targetIp) {
    Ethernet eth = new Ethernet();
    eth.setDestinationMACAddress(MAC1);
    eth.setSourceMACAddress(MAC2);
    eth.setEtherType(Ethernet.TYPE_ARP);

    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(MAC2.toBytes());
    arp.setTargetHardwareAddress(MacAddress.ZERO.toBytes());

    arp.setTargetProtocolAddress(targetIp.toOctets());
    arp.setSenderProtocolAddress(IP2.toOctets());

    eth.setPayload(arp);
    return eth;
}
 
Example 4
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 5
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 6
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 7
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 8
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 9
Source File: DefaultVirtualPacketProviderTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/** Test the physical packet context is delivered to a proper (physical)
 *  virtual network and device.
 */
@Test
public void virtualizePacket() {
    Ethernet eth = new Ethernet();
    eth.setSourceMACAddress(SRC_MAC_ADDR);
    eth.setDestinationMACAddress(DST_MAC_ADDR);
    eth.setVlanID((short) 1);
    eth.setPayload(null);

    InboundPacket pInPacket =
            new DefaultInboundPacket(CP22, eth,
                                     ByteBuffer.wrap(eth.serialize()));

    PacketContext pContext =
            new TestPacketContext(System.nanoTime(), pInPacket, null, false);

    testPacketService.sendTestPacketContext(pContext);

    PacketContext vContext = providerService.getRequestedPacketContext(0);
    InboundPacket vInPacket = vContext.inPacket();

    assertEquals("the packet should be received from VCP12",
                 VCP12, vInPacket.receivedFrom());

    assertEquals("VLAN tag should be excludede", VlanId.UNTAGGED,
                 vInPacket.parsed().getVlanID());
}
 
Example 10
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 11
Source File: NeighborAdvertisement.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Builds an NDP reply based on a request.
 *
 * @param srcIp   the IP address to use as the reply source
 * @param srcMac  the MAC address to use as the reply source
 * @param request the Neighbor Solicitation request we got
 * @return an Ethernet frame containing the Neighbor Advertisement reply
 */
public static Ethernet buildNdpAdv(Ip6Address srcIp,
                                   MacAddress srcMac,
                                   Ethernet request) {

    checkNotNull(srcIp, "IP address cannot be null");
    checkNotNull(srcMac, "MAC address cannot be null");
    checkNotNull(request, "Request cannot be null");
    checkArgument(request.getEtherType() == Ethernet.TYPE_IPV6,
            "EtherType must be IPv6");

    final IPv6 ipv6Request = (IPv6) request.getPayload();

    checkArgument(ipv6Request.getNextHeader() == IPv6.PROTOCOL_ICMP6,
            "Protocol must be ICMP6");

    final ICMP6 icmpv6 = (ICMP6) ipv6Request.getPayload();

    checkArgument(icmpv6.getIcmpType() == ICMP6.NEIGHBOR_SOLICITATION,
            "ICMP6 type must be NEIGHBOR_SOLICITATION");

    Ethernet eth = new Ethernet();
    eth.setDestinationMACAddress(request.getSourceMAC());
    eth.setSourceMACAddress(srcMac);
    eth.setEtherType(Ethernet.TYPE_IPV6);
    eth.setVlanID(request.getVlanID());

    IPv6 ipv6 = new IPv6();
    ipv6.setSourceAddress(srcIp.toOctets());
    ipv6.setDestinationAddress(ipv6Request.getSourceAddress());
    ipv6.setHopLimit(NDP_HOP_LIMIT);
    ipv6.setNextHeader(IPv6.PROTOCOL_ICMP6);

    ICMP6 icmp6 = new ICMP6();
    icmp6.setIcmpType(ICMP6.NEIGHBOR_ADVERTISEMENT);
    icmp6.setIcmpCode(RESERVED_CODE);

    NeighborAdvertisement nadv = new NeighborAdvertisement();
    nadv.setTargetAddress(srcIp.toOctets());
    nadv.setSolicitedFlag(NDP_SOLICITED_FLAG);
    nadv.setOverrideFlag(NDP_OVERRIDE_FLAG);
    nadv.addOption(NeighborDiscoveryOptions.TYPE_TARGET_LL_ADDRESS,
            srcMac.toBytes());

    icmp6.setPayload(nadv);
    ipv6.setPayload(icmp6);
    eth.setPayload(ipv6);
    return eth;
}
 
Example 12
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;
    }
}
 
Example 13
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 14
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 15
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 16
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 17
Source File: Dhcp6Test.java    From onos with Apache License 2.0 4 votes vote down vote up
@Test
public void serializeReply() throws Exception {
    DHCP6 dhcp6 = new DHCP6();
    dhcp6.setMsgType(DHCP6.MsgType.REPLY.value());
    dhcp6.setTransactionId(XID_2);
    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(REPLY)),
                      eth.serialize());
}
 
Example 18
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 19
Source File: Dhcp6RelayTest.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Test serialize relay message with advertise message.
 *
 * @throws Exception exception while serialize the DHCPv6 payload
 */
@Test
public void serializeAdvertise() throws Exception {
    DHCP6 relayMsg = new DHCP6();
    relayMsg.setMsgType(DHCP6.MsgType.RELAY_REPL.value());
    relayMsg.setHopCount((byte) HOP_COUNT);
    relayMsg.setLinkAddress(LINK_ADDRESS.toOctets());
    relayMsg.setPeerAddress(PEER_ADDRESS.toOctets());

    DHCP6 relaiedDhcp6 = new DHCP6();
    relaiedDhcp6.setMsgType(DHCP6.MsgType.ADVERTISE.value());
    relaiedDhcp6.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);

    relaiedDhcp6.setOptions(options);

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

    relayMsg.setOptions(ImmutableList.of(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) 0x0000019d);

    IPv6 ipv6 = new IPv6();
    ipv6.setHopLimit((byte) 64);
    ipv6.setSourceAddress(SERVER_LL.toOctets());
    ipv6.setDestinationAddress(DOWNSTREAM_LL.toOctets());
    ipv6.setNextHeader(IPv6.PROTOCOL_UDP);
    ipv6.setTrafficClass((byte) 0);
    ipv6.setFlowLabel(0x000c72ef);
    ipv6.setPayload(udp);

    Ethernet eth = new Ethernet();
    eth.setDestinationMACAddress(DOWNSTREAM_MAC);
    eth.setSourceMACAddress(SERVER_MAC);
    eth.setEtherType(Ethernet.TYPE_IPV6);
    eth.setPayload(ipv6);
    assertArrayEquals(Resources.toByteArray(Dhcp6RelayTest.class.getResource(ADVERTISE)),
                      eth.serialize());
}
 
Example 20
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());
}