blob: 0e665d3785d7fc6545cf695d5852434dfed7eee4 [file] [log] [blame]
Jonathan Hart9bdaaec2016-08-22 13:33:45 -07001/*
2 * Copyright 2016-present Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.onosproject.incubator.net.neighbour.impl;
18
19import com.google.common.collect.LinkedListMultimap;
20import com.google.common.collect.ListMultimap;
21import com.google.common.collect.Multimaps;
22import org.apache.felix.scr.annotations.Activate;
23import org.apache.felix.scr.annotations.Component;
24import org.apache.felix.scr.annotations.Deactivate;
25import org.apache.felix.scr.annotations.Modified;
26import org.apache.felix.scr.annotations.Property;
27import org.apache.felix.scr.annotations.Reference;
28import org.apache.felix.scr.annotations.ReferenceCardinality;
29import org.apache.felix.scr.annotations.Service;
30import org.onlab.packet.ARP;
31import org.onlab.packet.Ethernet;
32import org.onlab.packet.ICMP6;
33import org.onlab.packet.IPv6;
34import org.onlab.packet.Ip4Address;
35import org.onlab.packet.Ip6Address;
36import org.onlab.packet.MacAddress;
37import org.onlab.packet.VlanId;
38import org.onlab.packet.ndp.NeighborAdvertisement;
39import org.onlab.packet.ndp.NeighborDiscoveryOptions;
40import org.onlab.util.Tools;
41import org.onosproject.cfg.ComponentConfigService;
42import org.onosproject.core.ApplicationId;
43import org.onosproject.core.CoreService;
44import org.onosproject.incubator.net.intf.Interface;
45import org.onosproject.incubator.net.neighbour.NeighbourMessageActions;
46import org.onosproject.incubator.net.neighbour.NeighbourMessageContext;
47import org.onosproject.incubator.net.neighbour.NeighbourMessageHandler;
48import org.onosproject.incubator.net.neighbour.NeighbourResolutionService;
49import org.onosproject.net.ConnectPoint;
50import org.onosproject.net.edge.EdgePortService;
51import org.onosproject.net.flow.DefaultTrafficSelector;
52import org.onosproject.net.flow.DefaultTrafficTreatment;
53import org.onosproject.net.flow.TrafficSelector;
54import org.onosproject.net.flow.TrafficTreatment;
55import org.onosproject.net.host.HostService;
56import org.onosproject.net.packet.DefaultOutboundPacket;
57import org.onosproject.net.packet.InboundPacket;
58import org.onosproject.net.packet.PacketContext;
59import org.onosproject.net.packet.PacketProcessor;
60import org.onosproject.net.packet.PacketService;
61import org.osgi.service.component.ComponentContext;
62import org.slf4j.Logger;
63import org.slf4j.LoggerFactory;
64
65import java.nio.ByteBuffer;
66import java.util.Dictionary;
67import java.util.List;
68import java.util.Objects;
69
70import static com.google.common.base.Preconditions.checkNotNull;
71import static org.onlab.packet.Ethernet.TYPE_ARP;
72import static org.onlab.packet.Ethernet.TYPE_IPV6;
73import static org.onlab.packet.ICMP6.NEIGHBOR_ADVERTISEMENT;
74import static org.onlab.packet.ICMP6.NEIGHBOR_SOLICITATION;
75import static org.onlab.packet.IPv6.PROTOCOL_ICMP6;
76import static org.onosproject.net.packet.PacketPriority.CONTROL;
77
78/**
79 * Manages handlers for neighbour messages.
80 */
81@Service
82@Component(immediate = true)
83public class NeighbourPacketManager implements NeighbourResolutionService {
84
85 private final Logger log = LoggerFactory.getLogger(getClass());
86
87 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
88 protected CoreService coreService;
89
90 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
91 protected HostService hostService;
92
93 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
94 protected EdgePortService edgeService;
95
96 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
97 protected PacketService packetService;
98
99 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
100 protected ComponentConfigService componentConfigService;
101
102 @Property(name = "ndpEnabled", boolValue = false,
103 label = "Enable IPv6 neighbour discovery")
104 protected boolean ndpEnabled = false;
105
106 private static final String APP_NAME = "org.onosproject.neighbour";
107 private ApplicationId appId;
108
109 private ListMultimap<ConnectPoint, HandlerRegistration> packetHandlers =
110 Multimaps.synchronizedListMultimap(LinkedListMultimap.create());
111
112 private final InternalPacketProcessor processor = new InternalPacketProcessor();
113 private final InternalNeighbourMessageActions actions = new InternalNeighbourMessageActions();
114
115 @Activate
116 protected void activate(ComponentContext context) {
117 appId = coreService.registerApplication(APP_NAME);
118
119 componentConfigService.registerProperties(getClass());
120 modified(context);
121
122 packetService.addProcessor(processor, PacketProcessor.director(1));
123 }
124
125 @Deactivate
126 protected void deactivate() {
127 cancelPackets();
128 packetService.removeProcessor(processor);
129 componentConfigService.unregisterProperties(getClass(), false);
130 }
131
132 @Modified
133 protected void modified(ComponentContext context) {
134 Dictionary<?, ?> properties = context.getProperties();
135 Boolean flag;
136
137 flag = Tools.isPropertyEnabled(properties, "ndpEnabled");
138 if (flag != null) {
139 ndpEnabled = flag;
140 log.info("IPv6 neighbor discovery is {}",
141 ndpEnabled ? "enabled" : "disabled");
142 }
143
144 requestPackets();
145 }
146
147 private void requestPackets() {
148 packetService.requestPackets(buildArpSelector(), CONTROL, appId);
149
150 if (ndpEnabled) {
151 packetService.requestPackets(buildNeighborSolicitationSelector(),
152 CONTROL, appId);
153 packetService.requestPackets(buildNeighborAdvertisementSelector(),
154 CONTROL, appId);
155 } else {
156 packetService.cancelPackets(buildNeighborSolicitationSelector(),
157 CONTROL, appId);
158 packetService.cancelPackets(buildNeighborAdvertisementSelector(),
159 CONTROL, appId);
160 }
161 }
162
163 private void cancelPackets() {
164 packetService.cancelPackets(buildArpSelector(), CONTROL, appId);
165 packetService.cancelPackets(buildNeighborSolicitationSelector(),
166 CONTROL, appId);
167 packetService.cancelPackets(buildNeighborAdvertisementSelector(),
168 CONTROL, appId);
169 }
170
171 private TrafficSelector buildArpSelector() {
172 return DefaultTrafficSelector.builder()
173 .matchEthType(TYPE_ARP)
174 .build();
175 }
176
177 private TrafficSelector buildNeighborSolicitationSelector() {
178 return DefaultTrafficSelector.builder()
179 .matchEthType(TYPE_IPV6)
180 .matchIPProtocol(PROTOCOL_ICMP6)
181 .matchIcmpv6Type(NEIGHBOR_SOLICITATION)
182 .build();
183 }
184
185 private TrafficSelector buildNeighborAdvertisementSelector() {
186 return DefaultTrafficSelector.builder()
187 .matchEthType(TYPE_IPV6)
188 .matchIPProtocol(PROTOCOL_ICMP6)
189 .matchIcmpv6Type(NEIGHBOR_ADVERTISEMENT)
190 .build();
191 }
192
193 @Override
194 public void registerNeighbourHandler(ConnectPoint connectPoint, NeighbourMessageHandler handler) {
195 packetHandlers.put(connectPoint, new HandlerRegistration(handler));
196 }
197
198 @Override
199 public void registerNeighbourHandler(Interface intf, NeighbourMessageHandler handler) {
200 packetHandlers.put(intf.connectPoint(), new HandlerRegistration(handler, intf));
201 }
202
203 @Override
204 public void unregisterNeighbourHandler(ConnectPoint connectPoint, NeighbourMessageHandler handler) {
205 packetHandlers.remove(connectPoint, handler);
206 }
207
208 @Override
209 public void unregisterNeighbourHandler(Interface intf, NeighbourMessageHandler handler) {
210 packetHandlers.remove(intf.connectPoint(), handler);
211 }
212
213 public void handlePacket(PacketContext context) {
214 InboundPacket pkt = context.inPacket();
215 Ethernet ethPkt = pkt.parsed();
216
217 NeighbourMessageContext msgContext =
218 DefaultNeighbourMessageContext.createContext(ethPkt, pkt.receivedFrom(), actions);
219
220 if (msgContext == null) {
221 return;
222 }
223
224 handleMessage(msgContext);
225
226 context.block();
227 }
228
229 private void handleMessage(NeighbourMessageContext context) {
230 List<HandlerRegistration> handlers = packetHandlers.get(context.inPort());
231
232 handlers.forEach(registration -> {
233 if (registration.intf() == null || matches(context, registration.intf())) {
234 registration.handler().handleMessage(context, hostService);
235 }
236 });
237 }
238
239 private boolean matches(NeighbourMessageContext context, Interface intf) {
240 checkNotNull(context);
241 checkNotNull(intf);
242
243 boolean matches = true;
244 if (!intf.vlan().equals(VlanId.NONE) && !intf.vlan().equals(context.vlan())) {
245 matches = false;
246 }
247
248 return matches;
249 }
250
251
252 private void reply(NeighbourMessageContext context, MacAddress targetMac) {
253 switch (context.protocol()) {
254 case ARP:
255 sendTo(ARP.buildArpReply((Ip4Address) context.target(),
256 targetMac, context.packet()), context.inPort());
257 break;
258 case NDP:
259 sendTo(buildNdpReply((Ip6Address) context.target(), targetMac,
260 context.packet()), context.inPort());
261 break;
262 default:
263 break;
264 }
265 }
266
267 /**
268 * Outputs a packet out a specific port.
269 *
270 * @param packet the packet to send
271 * @param outPort the port to send it out
272 */
273 private void sendTo(Ethernet packet, ConnectPoint outPort) {
274 sendTo(ByteBuffer.wrap(packet.serialize()), outPort);
275 }
276
277 /**
278 * Outputs a packet out a specific port.
279 *
280 * @param packet packet to send
281 * @param outPort port to send it out
282 */
283 private void sendTo(ByteBuffer packet, ConnectPoint outPort) {
284 if (!edgeService.isEdgePoint(outPort)) {
285 // Sanity check to make sure we don't send the packet out an
286 // internal port and create a loop (could happen due to
287 // misconfiguration).
288 return;
289 }
290
291 TrafficTreatment.Builder builder = DefaultTrafficTreatment.builder();
292 builder.setOutput(outPort.port());
293 packetService.emit(new DefaultOutboundPacket(outPort.deviceId(),
294 builder.build(), packet));
295 }
296
297 /**
298 * Builds an Neighbor Discovery reply based on a request.
299 *
300 * @param srcIp the IP address to use as the reply source
301 * @param srcMac the MAC address to use as the reply source
302 * @param request the Neighbor Solicitation request we got
303 * @return an Ethernet frame containing the Neighbor Advertisement reply
304 */
305 private Ethernet buildNdpReply(Ip6Address srcIp, MacAddress srcMac,
306 Ethernet request) {
307 Ethernet eth = new Ethernet();
308 eth.setDestinationMACAddress(request.getSourceMAC());
309 eth.setSourceMACAddress(srcMac);
310 eth.setEtherType(Ethernet.TYPE_IPV6);
311 eth.setVlanID(request.getVlanID());
312
313 IPv6 requestIp = (IPv6) request.getPayload();
314 IPv6 ipv6 = new IPv6();
315 ipv6.setSourceAddress(srcIp.toOctets());
316 ipv6.setDestinationAddress(requestIp.getSourceAddress());
317 ipv6.setHopLimit((byte) 255);
318
319 ICMP6 icmp6 = new ICMP6();
320 icmp6.setIcmpType(ICMP6.NEIGHBOR_ADVERTISEMENT);
321 icmp6.setIcmpCode((byte) 0);
322
323 NeighborAdvertisement nadv = new NeighborAdvertisement();
324 nadv.setTargetAddress(srcIp.toOctets());
325 nadv.setSolicitedFlag((byte) 1);
326 nadv.setOverrideFlag((byte) 1);
327 nadv.addOption(NeighborDiscoveryOptions.TYPE_TARGET_LL_ADDRESS,
328 srcMac.toBytes());
329
330 icmp6.setPayload(nadv);
331 ipv6.setPayload(icmp6);
332 eth.setPayload(ipv6);
333 return eth;
334 }
335
336 /**
337 * Stores a neighbour message handler registration.
338 */
339 private class HandlerRegistration {
340 private final Interface intf;
341 private final NeighbourMessageHandler handler;
342
343 /**
344 * Creates a new handler registration.
345 *
346 * @param handler neighbour message handler
347 */
348 public HandlerRegistration(NeighbourMessageHandler handler) {
349 this(handler, null);
350 }
351
352 /**
353 * Creates a new handler registration.
354 *
355 * @param handler neighbour message handler
356 * @param intf interface
357 */
358 public HandlerRegistration(NeighbourMessageHandler handler, Interface intf) {
359 this.intf = intf;
360 this.handler = handler;
361 }
362
363 /**
364 * Gets the interface of the registration.
365 *
366 * @return interface
367 */
368 public Interface intf() {
369 return intf;
370 }
371
372 /**
373 * Gets the neighbour message handler.
374 *
375 * @return message handler
376 */
377 public NeighbourMessageHandler handler() {
378 return handler;
379 }
380
381 @Override
382 public boolean equals(Object other) {
383 if (this == other) {
384 return true;
385 }
386
387 if (!(other instanceof HandlerRegistration)) {
388 return false;
389 }
390
391 HandlerRegistration that = (HandlerRegistration) other;
392
393 return Objects.equals(intf, that.intf) &&
394 Objects.equals(handler, that.handler);
395 }
396
397 @Override
398 public int hashCode() {
399 return Objects.hash(intf, handler);
400 }
401 }
402
403 /**
404 * Packet processor for incoming packets.
405 */
406 private class InternalPacketProcessor implements PacketProcessor {
407
408 @Override
409 public void process(PacketContext context) {
410 // Stop processing if the packet has been handled, since we
411 // can't do any more to it.
412 if (context.isHandled()) {
413 return;
414 }
415
416 InboundPacket pkt = context.inPacket();
417 Ethernet ethPkt = pkt.parsed();
418 if (ethPkt == null) {
419 return;
420 }
421
422 if (ethPkt.getEtherType() == TYPE_ARP) {
423 // handle ARP packets
424 handlePacket(context);
425 } else if (ethPkt.getEtherType() == TYPE_IPV6) {
426 IPv6 ipv6 = (IPv6) ethPkt.getPayload();
427 if (ipv6.getNextHeader() == IPv6.PROTOCOL_ICMP6) {
428 ICMP6 icmp6 = (ICMP6) ipv6.getPayload();
429 if (icmp6.getIcmpType() == NEIGHBOR_SOLICITATION ||
430 icmp6.getIcmpType() == NEIGHBOR_ADVERTISEMENT) {
431 // handle ICMPv6 solicitations and advertisements (NDP)
432 handlePacket(context);
433 }
434 }
435 }
436 }
437 }
438
439 private class InternalNeighbourMessageActions implements NeighbourMessageActions {
440
441 @Override
442 public void reply(NeighbourMessageContext context, MacAddress targetMac) {
443 NeighbourPacketManager.this.reply(context, targetMac);
444 }
445
446 @Override
447 public void proxy(NeighbourMessageContext context, ConnectPoint outPort) {
448 sendTo(context.packet(), outPort);
449 }
450
451 @Override
452 public void proxy(NeighbourMessageContext context, Interface outIntf) {
453
454 }
455
456 @Override
457 public void flood(NeighbourMessageContext context) {
458 edgeService.getEdgePoints().forEach(connectPoint -> {
459 if (!connectPoint.equals(context.inPort())) {
460 sendTo(context.packet(), connectPoint);
461 }
462 });
463 }
464
465 @Override
466 public void drop(NeighbourMessageContext context) {
467
468 }
469 }
470
471}