blob: 7c5c762274d69a1685d9eee9bdb806b176be787e [file] [log] [blame]
Yi Tseng51301292017-07-28 13:02:59 -07001/*
2 * Copyright 2017-present Open Networking Foundation
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 */
17
18package org.onosproject.dhcprelay;
19
Yi Tseng525ff402017-10-23 19:39:39 -070020import com.google.common.collect.HashMultimap;
Yi Tseng919b2df2017-09-07 16:22:51 -070021import com.google.common.collect.Lists;
Yi Tseng525ff402017-10-23 19:39:39 -070022import com.google.common.collect.Multimap;
Kalhee Kim45fede42017-09-05 19:05:06 +000023import org.apache.felix.scr.annotations.Activate;
24import org.apache.felix.scr.annotations.Deactivate;
Kalhee Kim45fede42017-09-05 19:05:06 +000025import com.google.common.collect.Sets;
26import com.google.common.collect.ImmutableSet;
Yi Tseng51301292017-07-28 13:02:59 -070027import org.apache.felix.scr.annotations.Component;
28import org.apache.felix.scr.annotations.Property;
Kalhee Kim45fede42017-09-05 19:05:06 +000029import org.apache.felix.scr.annotations.Reference;
30import org.apache.felix.scr.annotations.ReferenceCardinality;
Yi Tseng51301292017-07-28 13:02:59 -070031import org.apache.felix.scr.annotations.Service;
32import org.onlab.packet.BasePacket;
Kalhee Kim45fede42017-09-05 19:05:06 +000033import org.onlab.packet.DHCP6;
34import org.onlab.packet.IPv6;
35import org.onlab.packet.Ethernet;
36import org.onlab.packet.Ip6Address;
Yi Tseng51301292017-07-28 13:02:59 -070037import org.onlab.packet.IpAddress;
Kalhee Kim45fede42017-09-05 19:05:06 +000038import org.onlab.packet.IpPrefix;
Yi Tseng51301292017-07-28 13:02:59 -070039import org.onlab.packet.MacAddress;
Yi Tseng525ff402017-10-23 19:39:39 -070040import org.onlab.packet.TpPort;
Kalhee Kim45fede42017-09-05 19:05:06 +000041import org.onlab.packet.UDP;
Yi Tseng51301292017-07-28 13:02:59 -070042import org.onlab.packet.VlanId;
Kalhee Kim45fede42017-09-05 19:05:06 +000043import org.onlab.packet.dhcp.Dhcp6RelayOption;
44import org.onlab.packet.dhcp.Dhcp6InterfaceIdOption;
45import org.onlab.packet.dhcp.Dhcp6Option;
46import org.onlab.packet.dhcp.Dhcp6IaNaOption;
47import org.onlab.packet.dhcp.Dhcp6IaTaOption;
48import org.onlab.packet.dhcp.Dhcp6IaPdOption;
49import org.onlab.packet.dhcp.Dhcp6IaAddressOption;
50import org.onlab.packet.dhcp.Dhcp6IaPrefixOption;
51import org.onlab.util.HexString;
Yi Tseng525ff402017-10-23 19:39:39 -070052import org.onosproject.core.ApplicationId;
53import org.onosproject.core.CoreService;
Yi Tseng51301292017-07-28 13:02:59 -070054import org.onosproject.dhcprelay.api.DhcpHandler;
Yi Tseng919b2df2017-09-07 16:22:51 -070055import org.onosproject.dhcprelay.api.DhcpServerInfo;
Yi Tseng525ff402017-10-23 19:39:39 -070056import org.onosproject.dhcprelay.config.IgnoreDhcpConfig;
Kalhee Kim45fede42017-09-05 19:05:06 +000057import org.onosproject.dhcprelay.store.DhcpRelayStore;
Kalhee Kimba366062017-11-07 16:32:09 +000058import org.onosproject.dhcprelay.store.DhcpFpmPrefixStore;
Yi Tseng525ff402017-10-23 19:39:39 -070059import org.onosproject.net.Device;
60import org.onosproject.net.DeviceId;
Kalhee Kimba366062017-11-07 16:32:09 +000061import org.onosproject.routing.fpm.api.FpmRecord;
Yi Tseng525ff402017-10-23 19:39:39 -070062import org.onosproject.net.behaviour.Pipeliner;
63import org.onosproject.net.device.DeviceService;
64import org.onosproject.net.flow.DefaultTrafficSelector;
65import org.onosproject.net.flow.TrafficSelector;
66import org.onosproject.net.flowobjective.DefaultForwardingObjective;
67import org.onosproject.net.flowobjective.FlowObjectiveService;
68import org.onosproject.net.flowobjective.ForwardingObjective;
69import org.onosproject.net.flowobjective.Objective;
70import org.onosproject.net.flowobjective.ObjectiveContext;
71import org.onosproject.net.flowobjective.ObjectiveError;
Yi Tsengaa417a62017-09-08 17:22:51 -070072import org.onosproject.net.host.HostProvider;
73import org.onosproject.net.host.HostProviderRegistry;
74import org.onosproject.net.host.HostProviderService;
Kalhee Kim45fede42017-09-05 19:05:06 +000075import org.onosproject.net.host.HostService;
76import org.onosproject.net.host.DefaultHostDescription;
77import org.onosproject.net.host.HostDescription;
78import org.onosproject.net.host.InterfaceIpAddress;
79import org.onosproject.net.host.HostListener;
80import org.onosproject.net.host.HostEvent;
81import org.onosproject.net.intf.Interface;
82import org.onosproject.net.intf.InterfaceService;
Yi Tseng525ff402017-10-23 19:39:39 -070083import org.onosproject.net.packet.PacketPriority;
Yi Tsengaa417a62017-09-08 17:22:51 -070084import org.onosproject.net.provider.ProviderId;
Kalhee Kim45fede42017-09-05 19:05:06 +000085import org.onosproject.routeservice.Route;
86import org.onosproject.routeservice.RouteStore;
Yi Tseng483ac6f2017-08-02 15:03:31 -070087import org.onosproject.dhcprelay.config.DhcpServerConfig;
Yi Tseng51301292017-07-28 13:02:59 -070088import org.onosproject.net.ConnectPoint;
Kalhee Kim45fede42017-09-05 19:05:06 +000089import org.onosproject.net.Host;
90import org.onosproject.net.HostId;
91import org.onosproject.net.HostLocation;
92import org.onosproject.net.packet.DefaultOutboundPacket;
93import org.onosproject.net.packet.OutboundPacket;
Yi Tseng51301292017-07-28 13:02:59 -070094import org.onosproject.net.packet.PacketContext;
Kalhee Kim45fede42017-09-05 19:05:06 +000095import org.onosproject.net.packet.PacketService;
96import org.slf4j.Logger;
97import org.slf4j.LoggerFactory;
98import org.onosproject.net.flow.DefaultTrafficTreatment;
99import org.onosproject.net.flow.TrafficTreatment;
Yi Tseng51301292017-07-28 13:02:59 -0700100
Kalhee Kim45fede42017-09-05 19:05:06 +0000101
102import java.nio.ByteBuffer;
103import java.util.List;
Yi Tseng483ac6f2017-08-02 15:03:31 -0700104import java.util.Collection;
Yi Tseng51301292017-07-28 13:02:59 -0700105import java.util.Optional;
Kalhee Kim45fede42017-09-05 19:05:06 +0000106import java.util.Set;
107import java.util.ArrayList;
Yi Tseng525ff402017-10-23 19:39:39 -0700108import java.util.concurrent.atomic.AtomicInteger;
Kalhee Kim45fede42017-09-05 19:05:06 +0000109
110
111import static com.google.common.base.Preconditions.checkNotNull;
112import static com.google.common.base.Preconditions.checkState;
Yi Tseng525ff402017-10-23 19:39:39 -0700113import static org.onosproject.net.flowobjective.Objective.Operation.ADD;
114import static org.onosproject.net.flowobjective.Objective.Operation.REMOVE;
Yi Tseng51301292017-07-28 13:02:59 -0700115
116@Component
117@Service
118@Property(name = "version", value = "6")
Yi Tsengaa417a62017-09-08 17:22:51 -0700119public class Dhcp6HandlerImpl implements DhcpHandler, HostProvider {
Charles Chand988c282017-09-12 17:09:32 -0700120 public static final String DHCP_V6_RELAY_APP = "org.onosproject.Dhcp6HandlerImpl";
Saurav Das7c6dec12017-09-13 14:35:56 -0700121 public static final ProviderId PROVIDER_ID = new ProviderId("dhcp6", DHCP_V6_RELAY_APP);
Yi Tseng525ff402017-10-23 19:39:39 -0700122 private static final int IGNORE_CONTROL_PRIORITY = PacketPriority.CONTROL.priorityValue() + 1000;
123
124 private static final TrafficSelector CLIENT_SERVER_SELECTOR = DefaultTrafficSelector.builder()
125 .matchEthType(Ethernet.TYPE_IPV6)
126 .matchIPProtocol(IPv6.PROTOCOL_UDP)
127 .matchIPv6Src(IpPrefix.IPV6_LINK_LOCAL_PREFIX)
128 .matchIPv6Dst(Ip6Address.ALL_DHCP_RELAY_AGENTS_AND_SERVERS.toIpPrefix())
129 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_V6_CLIENT_PORT))
130 .matchUdpDst(TpPort.tpPort(UDP.DHCP_V6_SERVER_PORT))
131 .build();
132 private static final TrafficSelector SERVER_RELAY_SELECTOR = DefaultTrafficSelector.builder()
133 .matchEthType(Ethernet.TYPE_IPV6)
134 .matchIPProtocol(IPv6.PROTOCOL_UDP)
135 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_V6_SERVER_PORT))
136 .matchUdpDst(TpPort.tpPort(UDP.DHCP_V6_SERVER_PORT))
137 .build();
138 static final Set<TrafficSelector> DHCP_SELECTORS = ImmutableSet.of(
139 CLIENT_SERVER_SELECTOR,
140 SERVER_RELAY_SELECTOR
141 );
Kalhee Kim45fede42017-09-05 19:05:06 +0000142 private static Logger log = LoggerFactory.getLogger(Dhcp6HandlerImpl.class);
Yi Tseng51301292017-07-28 13:02:59 -0700143
Kalhee Kim45fede42017-09-05 19:05:06 +0000144 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
145 protected DhcpRelayStore dhcpRelayStore;
Yi Tseng51301292017-07-28 13:02:59 -0700146
Kalhee Kim45fede42017-09-05 19:05:06 +0000147 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
148 protected PacketService packetService;
149
150 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Kalhee Kim45fede42017-09-05 19:05:06 +0000151 protected RouteStore routeStore;
152
153 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
154 protected InterfaceService interfaceService;
155
156 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
157 protected HostService hostService;
158
Yi Tsengaa417a62017-09-08 17:22:51 -0700159 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
160 protected HostProviderRegistry providerRegistry;
Kalhee Kim45fede42017-09-05 19:05:06 +0000161
Yi Tseng525ff402017-10-23 19:39:39 -0700162 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
163 protected CoreService coreService;
164
165 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Kalhee Kimba366062017-11-07 16:32:09 +0000166 protected DhcpFpmPrefixStore dhcpFpmPrefixStore;
167
168 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yi Tseng525ff402017-10-23 19:39:39 -0700169 protected DeviceService deviceService;
170
171 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
172 protected FlowObjectiveService flowObjectiveService;
173
Yi Tsengaa417a62017-09-08 17:22:51 -0700174 protected HostProviderService providerService;
Yi Tseng525ff402017-10-23 19:39:39 -0700175 protected ApplicationId appId;
176 protected Multimap<DeviceId, VlanId> ignoredVlans = HashMultimap.create();
177 private InternalHostListener hostListener = new InternalHostListener();
178
Kalhee Kimba366062017-11-07 16:32:09 +0000179 private Boolean dhcpFpmEnabled = false;
180
Yi Tseng919b2df2017-09-07 16:22:51 -0700181 private List<DhcpServerInfo> defaultServerInfoList = Lists.newArrayList();
182 private List<DhcpServerInfo> indirectServerInfoList = Lists.newArrayList();
183
Kalhee Kim45fede42017-09-05 19:05:06 +0000184
185 // CLIENT message types
186 public static final Set<Byte> MSG_TYPE_FROM_CLIENT =
187 ImmutableSet.of(DHCP6.MsgType.SOLICIT.value(),
188 DHCP6.MsgType.REQUEST.value(),
189 DHCP6.MsgType.REBIND.value(),
190 DHCP6.MsgType.RENEW.value(),
191 DHCP6.MsgType.RELEASE.value(),
192 DHCP6.MsgType.DECLINE.value(),
193 DHCP6.MsgType.CONFIRM.value(),
194 DHCP6.MsgType.RELAY_FORW.value());
195 // SERVER message types
196 public static final Set<Byte> MSG_TYPE_FROM_SERVER =
197 ImmutableSet.of(DHCP6.MsgType.RELAY_REPL.value());
198
199 @Activate
200 protected void activate() {
Yi Tseng525ff402017-10-23 19:39:39 -0700201 appId = coreService.registerApplication(DHCP_V6_RELAY_APP);
Yi Tsengaa417a62017-09-08 17:22:51 -0700202 providerService = providerRegistry.register(this);
Kalhee Kim45fede42017-09-05 19:05:06 +0000203 hostService.addListener(hostListener);
Yi Tseng51301292017-07-28 13:02:59 -0700204 }
205
Kalhee Kim45fede42017-09-05 19:05:06 +0000206 @Deactivate
207 protected void deactivate() {
Yi Tsengaa417a62017-09-08 17:22:51 -0700208 providerRegistry.unregister(this);
Kalhee Kim45fede42017-09-05 19:05:06 +0000209 hostService.removeListener(hostListener);
Yi Tseng919b2df2017-09-07 16:22:51 -0700210 defaultServerInfoList.forEach(this::stopMonitoringIps);
211 defaultServerInfoList.clear();
212 indirectServerInfoList.forEach(this::stopMonitoringIps);
213 indirectServerInfoList.clear();
214 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000215
Yi Tseng919b2df2017-09-07 16:22:51 -0700216 private void stopMonitoringIps(DhcpServerInfo serverInfo) {
217 serverInfo.getDhcpGatewayIp6().ifPresent(gatewayIp -> {
218 hostService.stopMonitoringIp(gatewayIp);
219 });
220 serverInfo.getDhcpServerIp6().ifPresent(serverIp -> {
221 hostService.stopMonitoringIp(serverIp);
222 });
Yi Tseng51301292017-07-28 13:02:59 -0700223 }
224
Yi Tseng51301292017-07-28 13:02:59 -0700225 @Override
Yi Tseng919b2df2017-09-07 16:22:51 -0700226 public List<DhcpServerInfo> getDefaultDhcpServerInfoList() {
227 return defaultServerInfoList;
Yi Tseng51301292017-07-28 13:02:59 -0700228 }
229
230 @Override
Yi Tseng919b2df2017-09-07 16:22:51 -0700231 public List<DhcpServerInfo> getIndirectDhcpServerInfoList() {
232 return indirectServerInfoList;
Yi Tseng51301292017-07-28 13:02:59 -0700233 }
234
235 @Override
Yi Tseng525ff402017-10-23 19:39:39 -0700236 public void updateIgnoreVlanConfig(IgnoreDhcpConfig config) {
237 if (config == null) {
238 ignoredVlans.forEach(((deviceId, vlanId) -> {
239 processIgnoreVlanRule(deviceId, vlanId, REMOVE);
240 }));
241 return;
242 }
243 config.ignoredVlans().forEach((deviceId, vlanId) -> {
244 if (ignoredVlans.get(deviceId).contains(vlanId)) {
245 // don't need to process if it already ignored
246 return;
247 }
248 processIgnoreVlanRule(deviceId, vlanId, ADD);
249 });
250
251 ignoredVlans.forEach((deviceId, vlanId) -> {
252 if (!config.ignoredVlans().get(deviceId).contains(vlanId)) {
253 // not contains in new config, remove it
254 processIgnoreVlanRule(deviceId, vlanId, REMOVE);
255 }
256 });
257 }
258
259 @Override
Kalhee Kim45fede42017-09-05 19:05:06 +0000260 public void processDhcpPacket(PacketContext context, BasePacket payload) {
261 checkNotNull(payload, "DHCP6 payload can't be null");
262 checkState(payload instanceof DHCP6, "Payload is not a DHCP6");
263 DHCP6 dhcp6Payload = (DHCP6) payload;
264 Ethernet receivedPacket = context.inPacket().parsed();
265
266 if (!configured()) {
267 log.warn("Missing DHCP6 relay server config. Abort packet processing");
268 log.warn("dhcp6 payload {}", dhcp6Payload);
269
270 return;
271 }
272
273 byte msgType = dhcp6Payload.getMsgType();
274 log.warn("msgType is {}", msgType);
275
276 ConnectPoint inPort = context.inPacket().receivedFrom();
277 if (inPort == null) {
278 log.warn("incommin ConnectPoint is null");
279 }
280 Set<Interface> receivingInterfaces = interfaceService.getInterfacesByPort(inPort);
281 //ignore the packets if dhcp client interface is not configured on onos.
282 if (receivingInterfaces.isEmpty()) {
283 log.warn("Virtual interface is not configured on {}", inPort);
284 return;
285 }
286
287
288 if (MSG_TYPE_FROM_CLIENT.contains(msgType)) {
289
290 InternalPacket ethernetClientPacket =
291 processDhcp6PacketFromClient(context, receivedPacket, receivingInterfaces);
292 if (ethernetClientPacket != null) {
293 forwardPacket(ethernetClientPacket);
294 }
295
296 } else if (MSG_TYPE_FROM_SERVER.contains(msgType)) {
297 log.warn("calling processDhcp6PacketFromServer with RELAY_REPL", msgType);
298 InternalPacket ethernetPacketReply =
299 processDhcp6PacketFromServer(context, receivedPacket, receivingInterfaces);
300 if (ethernetPacketReply != null) {
301 forwardPacket(ethernetPacketReply);
302 }
303 } else {
304 log.warn("Not so fast, packet type {} not supported yet", msgType);
305 }
306 }
307
308
309 /**
310 * Checks if this app has been configured.
311 *
312 * @return true if all information we need have been initialized
313 */
314 public boolean configured() {
Yi Tseng919b2df2017-09-07 16:22:51 -0700315 return !defaultServerInfoList.isEmpty();
Kalhee Kim45fede42017-09-05 19:05:06 +0000316 }
317
Yi Tsengaa417a62017-09-08 17:22:51 -0700318 @Override
319 public ProviderId id() {
Charles Chand988c282017-09-12 17:09:32 -0700320 return PROVIDER_ID;
Yi Tsengaa417a62017-09-08 17:22:51 -0700321 }
322
323 @Override
324 public void triggerProbe(Host host) {
325 // Do nothing here
326 }
327
Kalhee Kim45fede42017-09-05 19:05:06 +0000328 // the new class the contains Ethernet packet and destination port, kind of like adding
329 // internal header to the packet
330 private class InternalPacket {
331 Ethernet packet;
332 ConnectPoint destLocation;
333 public InternalPacket(Ethernet newPacket, ConnectPoint newLocation) {
334 packet = newPacket;
335 destLocation = newLocation;
336 }
337 void setLocation(ConnectPoint newLocation) {
338 destLocation = newLocation;
339 }
340 }
341
342 //forward the packet to ConnectPoint where the DHCP server is attached.
343 private void forwardPacket(InternalPacket packet) {
344 //send Packetout to dhcp server connectpoint.
345 if (packet.destLocation != null) {
346 TrafficTreatment t = DefaultTrafficTreatment.builder()
347 .setOutput(packet.destLocation.port()).build();
348 OutboundPacket o = new DefaultOutboundPacket(
349 packet.destLocation.deviceId(), t, ByteBuffer.wrap(packet.packet.serialize()));
350 if (log.isTraceEnabled()) {
351 log.trace("Relaying packet to destination {}", packet.destLocation);
352 }
353 packetService.emit(o);
354 } // if
355 }
356
357 /**
358 * Check if the host is directly connected to the network or not.
359 *
360 * @param dhcp6Payload the dhcp6 payload
361 * @return true if the host is directly connected to the network; false otherwise
362 */
363 private boolean directlyConnected(DHCP6 dhcp6Payload) {
364 log.debug("directlyConnected enters");
365
366 if (dhcp6Payload.getMsgType() != DHCP6.MsgType.RELAY_FORW.value() &&
367 dhcp6Payload.getMsgType() != DHCP6.MsgType.RELAY_REPL.value()) {
368 log.debug("directlyConnected true. MsgType {}", dhcp6Payload.getMsgType());
369
370 return true;
371 }
372
373 // Regardless of relay-forward or relay-replay, check if we see another relay message
374 DHCP6 dhcp6Payload2 = dhcp6PacketFromRelayPacket(dhcp6Payload);
375 if (dhcp6Payload2 != null) {
376 if (dhcp6Payload.getMsgType() == DHCP6.MsgType.RELAY_FORW.value()) {
377 log.debug("directlyConnected false. 1st realy-foward, 2nd MsgType {}", dhcp6Payload2.getMsgType());
378 return false;
379 } else {
380 // relay-reply
381 if (dhcp6Payload2.getMsgType() != DHCP6.MsgType.RELAY_REPL.value()) {
382 log.debug("directlyConnected true. 2nd MsgType {}", dhcp6Payload2.getMsgType());
383 return true; // must be directly connected
384 } else {
385 log.debug("directlyConnected false. 1st relay-reply, 2nd relay-reply MsgType {}",
386 dhcp6Payload2.getMsgType());
387 return false; // must be indirectly connected
388 }
389 }
390 } else {
391 log.warn("directlyConnected true.");
392 return true;
393 }
394 }
395
396 /**
397 * extract DHCP6 payload from dhcp6 relay message within relay-forwrd/reply.
398 *
399 * @param dhcp6 dhcp6 relay-reply or relay-foward
400 * @return dhcp6Packet dhcp6 packet extracted from relay-message
401 */
402 private DHCP6 dhcp6PacketFromRelayPacket(DHCP6 dhcp6) {
403 log.debug("dhcp6PacketFromRelayPacket enters. dhcp6 {}", dhcp6);
404
405 // extract the relay message if exist
406 DHCP6 dhcp6Payload = dhcp6.getOptions().stream()
407 .filter(opt -> opt instanceof Dhcp6RelayOption)
408 .map(BasePacket::getPayload)
409 .map(pld -> (DHCP6) pld)
410 .findFirst()
411 .orElse(null);
412
413
414 if (dhcp6Payload == null) {
415 // Can't find dhcp payload
416 log.debug("Can't find dhcp6 payload from relay message");
417 } else {
418 log.debug("dhcp6 payload found from relay message {}", dhcp6Payload);
419 }
420
421 return dhcp6Payload;
422 }
423
424 /**
425 * find the leaf DHCP6 packet from multi-level relay packet.
426 *
427 * @param relayPacket dhcp6 relay packet
428 * @return leafPacket non-relay dhcp6 packet
429 */
430 private DHCP6 getDhcp6Leaf(DHCP6 relayPacket) {
431 DHCP6 dhcp6Parent = relayPacket;
432 DHCP6 dhcp6Child = null;
433
434 log.debug("getDhcp6Leaf entered.");
435 while (dhcp6Parent != null) {
436 dhcp6Child = dhcp6PacketFromRelayPacket(dhcp6Parent);
437
438 if (dhcp6Child != null) {
439 if (dhcp6Child.getMsgType() != DHCP6.MsgType.RELAY_FORW.value() &&
440 dhcp6Child.getMsgType() != DHCP6.MsgType.RELAY_REPL.value()) {
441 log.debug("leaf dhcp6 packet found.");
442 break;
443 } else {
444 // found another relay
445 // go for another loop
446 dhcp6Parent = dhcp6Child;
447 }
448 } else {
449 log.warn("malformed pkt! Expected dhcp6 within relay pkt, but no dhcp6 leaf found.");
450 break;
451 }
452 }
453 return dhcp6Child;
454 }
455
456 /**
457 * check if DHCP6 relay-reply is reply.
458 *
459 * @param relayPacket dhcp6 relay-reply
460 * @return boolean relay-reply contains ack
461 */
462 private boolean isDhcp6Reply(DHCP6 relayPacket) {
463 log.debug("isDhcp6Reply entered.");
464
465 DHCP6 leafDhcp6 = getDhcp6Leaf(relayPacket);
466
467 if (leafDhcp6 != null) {
468 if (leafDhcp6.getMsgType() == DHCP6.MsgType.REPLY.value()) {
469 log.debug("isDhcp6Reply true.");
470 return true; // must be directly connected
471 } else {
472 log.debug("isDhcp6Reply false. leaf dhcp6 is not replay. MsgType {}", leafDhcp6.getMsgType());
473 }
474 } else {
475 log.debug("isDhcp6Reply false. Expected dhcp6 within relay pkt but not found.");
476 }
477 log.debug("isDhcp6Reply false.");
478 return false;
479 }
480
481 /**
482 * check if DHCP6 is release or relay-forward contains release.
483 *
484 * @param dhcp6Payload dhcp6 packet
485 * @return boolean dhcp6 contains release
486 */
487 private boolean isDhcp6Release(DHCP6 dhcp6Payload) {
488
489 log.debug("isDhcp6Release entered.");
490
491 if (dhcp6Payload.getMsgType() == DHCP6.MsgType.RELEASE.value()) {
492 log.debug("isDhcp6Release true.");
493 return true; // must be directly connected
494 } else {
495 DHCP6 dhcp6Leaf = getDhcp6Leaf(dhcp6Payload);
496 if (dhcp6Leaf != null) {
497 if (dhcp6Leaf.getMsgType() == DHCP6.MsgType.RELEASE.value()) {
498 log.debug("isDhcp6Release true. indirectlry connected");
499 return true;
500 } else {
501 log.debug("leaf dhcp6 is not release. MsgType {}", dhcp6Leaf.getMsgType());
502 return false;
503 }
504 } else {
505 log.debug("isDhcp6Release false. dhcp6 is niether relay nor release.");
506 return false;
507 }
508 }
509 }
510
511 /**
512 * extract from dhcp6 packet client ipv6 address of given by dhcp server.
513 *
514 * @param dhcp6 the dhcp6 packet
515 * @return Ip6Address Ip6Address given by dhcp server, or null if not exists
516 */
517 private Ip6Address extractIpAddress(DHCP6 dhcp6) {
518 Ip6Address ip = null;
519
520 log.debug("extractIpAddress enters dhcp6 {}.", dhcp6);
521 // Extract IPv6 address from IA NA ot IA TA option
522 Optional<Dhcp6IaNaOption> iaNaOption = dhcp6.getOptions()
523 .stream()
524 .filter(opt -> opt instanceof Dhcp6IaNaOption)
525 .map(opt -> (Dhcp6IaNaOption) opt)
526 .findFirst();
527 Optional<Dhcp6IaTaOption> iaTaOption = dhcp6.getOptions()
528 .stream()
529 .filter(opt -> opt instanceof Dhcp6IaTaOption)
530 .map(opt -> (Dhcp6IaTaOption) opt)
531 .findFirst();
532 Optional<Dhcp6IaAddressOption> iaAddressOption;
533 if (iaNaOption.isPresent()) {
534 log.debug("Found IPv6 address from iaNaOption {}", iaNaOption);
535
536 iaAddressOption = iaNaOption.get().getOptions().stream()
537 .filter(opt -> opt instanceof Dhcp6IaAddressOption)
538 .map(opt -> (Dhcp6IaAddressOption) opt)
539 .findFirst();
540 } else if (iaTaOption.isPresent()) {
541 log.debug("Found IPv6 address from iaTaOption {}", iaTaOption);
542
543 iaAddressOption = iaTaOption.get().getOptions().stream()
544 .filter(opt -> opt instanceof Dhcp6IaAddressOption)
545 .map(opt -> (Dhcp6IaAddressOption) opt)
546 .findFirst();
547 } else {
548 iaAddressOption = Optional.empty();
549 }
550 if (iaAddressOption.isPresent()) {
551 ip = iaAddressOption.get().getIp6Address();
552 log.debug("Found IPv6 address from iaAddressOption {}", iaAddressOption);
553
554
555 } else {
556 log.debug("Can't find IPv6 address from DHCPv6 {}", dhcp6);
557 }
558
559 return ip;
560 }
561 /**
562 * extract from dhcp6 packet Prefix prefix provided by dhcp server.
563 *
564 * @param dhcp6 the dhcp6 payload
565 * @return IpPrefix Prefix Delegation prefix, or null if not exists.
566 */
567 private IpPrefix extractPrefix(DHCP6 dhcp6) {
568 log.warn("extractPrefix enters {}", dhcp6);
569
570 // extract prefix
571 IpPrefix prefixPrefix = null;
572
573 Ip6Address prefixAddress = null;
574
575 // Extract IPv6 prefix from IA PD option
576 Optional<Dhcp6IaPdOption> iaPdOption = dhcp6.getOptions()
577 .stream()
578 .filter(opt -> opt instanceof Dhcp6IaPdOption)
579 .map(opt -> (Dhcp6IaPdOption) opt)
580 .findFirst();
581
582 Optional<Dhcp6IaPrefixOption> iaPrefixOption;
583 if (iaPdOption.isPresent()) {
584 log.warn("IA_PD option found {}", iaPdOption);
585
586 iaPrefixOption = iaPdOption.get().getOptions().stream()
587 .filter(opt -> opt instanceof Dhcp6IaPrefixOption)
588 .map(opt -> (Dhcp6IaPrefixOption) opt)
589 .findFirst();
590 } else {
591 log.warn("IA_PD option NOT found");
592
593 iaPrefixOption = Optional.empty();
594 }
595 if (iaPrefixOption.isPresent()) {
596 log.warn("IAPrefix Option within IA_PD option found {}", iaPrefixOption);
597
598 prefixAddress = iaPrefixOption.get().getIp6Prefix();
599 int prefixLen = (int) iaPrefixOption.get().getPrefixLength();
600 log.warn("Prefix length is {} bits", prefixLen);
601 prefixPrefix = IpPrefix.valueOf(prefixAddress, prefixLen);
602
603 } else {
604 log.warn("Can't find IPv6 prefix from DHCPv6 {}", dhcp6);
605 }
606
607 return prefixPrefix;
608 }
609
610 /**
611 * remove host or route.
612 *
613 * @param directConnFlag flag to show that packet is from directly connected client
614 * @param dhcp6Packet the dhcp6 payload
615 * @param clientPacket client's ethernet packet
616 * @param clientIpv6 client's Ipv6 packet
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000617 * @param clientInterface client interfaces
Kalhee Kim45fede42017-09-05 19:05:06 +0000618 */
619 private void removeHostOrRoute(boolean directConnFlag, DHCP6 dhcp6Packet,
620 Ethernet clientPacket, IPv6 clientIpv6,
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000621 Interface clientInterface) {
Kalhee Kim45fede42017-09-05 19:05:06 +0000622 log.debug("extractPrefix enters {}", dhcp6Packet);
Kalhee Kim121ba922017-11-01 17:56:44 +0000623 VlanId vlanId = clientInterface.vlan();
624 MacAddress clientMac = clientPacket.getSourceMAC();
625 log.debug("client mac {} client vlan {}", HexString.toHexString(clientMac.toBytes(), ":"), vlanId);
626
Kalhee Kim45fede42017-09-05 19:05:06 +0000627 // add host or route
628 if (isDhcp6Release(dhcp6Packet)) {
629 IpAddress ip = null;
630 if (directConnFlag) {
631 // Add to host store if it is connected to network directly
632 ip = extractIpAddress(dhcp6Packet);
633 if (ip != null) {
Kalhee Kim121ba922017-11-01 17:56:44 +0000634
Kalhee Kim45fede42017-09-05 19:05:06 +0000635 HostId hostId = HostId.hostId(clientMac, vlanId);
636 log.debug("remove Host {} ip for directly connected.", hostId.toString());
Kalhee Kim45fede42017-09-05 19:05:06 +0000637 // Remove host's ip of when dhcp release msg is received
Yi Tsengaa417a62017-09-08 17:22:51 -0700638 providerService.removeIpFromHost(hostId, ip);
Kalhee Kim45fede42017-09-05 19:05:06 +0000639 } else {
640 log.debug("ipAddress not found. Do not add Host for directly connected.");
641 }
642 } else {
643 // Remove from route store if it is not connected to network directly
Kalhee Kim121ba922017-11-01 17:56:44 +0000644 // pick out the first link-local ip address
645 IpAddress nextHopIp = getFirstIpByHost(clientMac, vlanId);
646 if (nextHopIp == null) {
647 log.warn("Can't find link-local IP address of gateway mac {} vlanId {}",
648 clientMac, vlanId);
649 return;
650 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000651
652 DHCP6 leafDhcp = getDhcp6Leaf(dhcp6Packet);
653 ip = extractIpAddress(leafDhcp);
654 if (ip == null) {
655 log.debug("ip is null");
656 } else {
657 Route routeForIP = new Route(Route.Source.STATIC, ip.toIpPrefix(), nextHopIp);
658 log.debug("removing route of 128 address for indirectly connected.");
659 log.debug("128 ip {}, nexthop {}", HexString.toHexString(ip.toOctets(), ":"),
660 HexString.toHexString(nextHopIp.toOctets(), ":"));
661 routeStore.removeRoute(routeForIP);
662 }
663
664 IpPrefix ipPrefix = extractPrefix(leafDhcp);
665 if (ipPrefix == null) {
666 log.debug("ipPrefix is null ");
667 } else {
668 Route routeForPrefix = new Route(Route.Source.STATIC, ipPrefix, nextHopIp);
669 log.debug("removing route of PD for indirectly connected.");
670 log.debug("pd ip {}, nexthop {}", HexString.toHexString(ipPrefix.address().toOctets(), ":"),
671 HexString.toHexString(nextHopIp.toOctets(), ":"));
672
673 routeStore.removeRoute(routeForPrefix);
Kalhee Kimba366062017-11-07 16:32:09 +0000674 if (this.dhcpFpmEnabled) {
675 dhcpFpmPrefixStore.removeFpmRecord(ipPrefix);
676 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000677 }
678 }
679 }
680 }
681
682 /**
683 * add host or route.
684 *
685 * @param directConnFlag flag to show that packet is from directly connected client
686 * @param dhcp6Relay the dhcp6 payload
687 * @param embeddedDhcp6 client's ethernet packetthe dhcp6 payload within relay
688 * @param clientMac client macAddress
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000689 * @param clientInterface client interface
Kalhee Kim45fede42017-09-05 19:05:06 +0000690 */
691 private void addHostOrRoute(boolean directConnFlag, DHCP6 dhcp6Relay,
692 DHCP6 embeddedDhcp6,
693 MacAddress clientMac,
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000694 Interface clientInterface) {
Kalhee Kim45fede42017-09-05 19:05:06 +0000695 log.debug("addHostOrRoute entered.");
Kalhee Kim121ba922017-11-01 17:56:44 +0000696 VlanId vlanId = clientInterface.vlan();
Kalhee Kim45fede42017-09-05 19:05:06 +0000697 // add host or route
698 if (isDhcp6Reply(dhcp6Relay)) {
699 IpAddress ip = null;
700 if (directConnFlag) {
701 // Add to host store if it connect to network directly
702 ip = extractIpAddress(embeddedDhcp6);
703 if (ip != null) {
704 Set<IpAddress> ips = Sets.newHashSet(ip);
Yi Tsengaa417a62017-09-08 17:22:51 -0700705
706 // FIXME: we should use vlan id from original packet (solicit, request)
Kalhee Kim45fede42017-09-05 19:05:06 +0000707 HostId hostId = HostId.hostId(clientMac, vlanId);
Yi Tsengaa417a62017-09-08 17:22:51 -0700708 Host host = hostService.getHost(hostId);
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000709 HostLocation hostLocation = new HostLocation(clientInterface.connectPoint(),
Yi Tsengaa417a62017-09-08 17:22:51 -0700710 System.currentTimeMillis());
711 Set<HostLocation> hostLocations = Sets.newHashSet(hostLocation);
712
713 if (host != null) {
714 // Dual homing support:
715 // if host exists, use old locations and new location
716 hostLocations.addAll(host.locations());
717 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000718 HostDescription desc = new DefaultHostDescription(clientMac, vlanId,
Yi Tsengaa417a62017-09-08 17:22:51 -0700719 hostLocations, ips,
720 false);
Kalhee Kim45fede42017-09-05 19:05:06 +0000721 log.debug("adding Host for directly connected.");
722 log.debug("client mac {} client vlan {} hostlocation {}",
723 HexString.toHexString(clientMac.toBytes(), ":"),
724 vlanId, hostLocation.toString());
725
726 // Replace the ip when dhcp server give the host new ip address
Yi Tsengaa417a62017-09-08 17:22:51 -0700727 providerService.hostDetected(hostId, desc, false);
Kalhee Kim45fede42017-09-05 19:05:06 +0000728 } else {
729 log.warn("ipAddress not found. Do not add Host for directly connected.");
730 }
731 } else {
732 // Add to route store if it does not connect to network directly
Kalhee Kim121ba922017-11-01 17:56:44 +0000733 // pick out the first link-local ip address
734 IpAddress nextHopIp = getFirstIpByHost(clientMac, vlanId);
735 if (nextHopIp == null) {
736 log.warn("Can't find link-local IP address of gateway mac {} vlanId {}",
737 clientMac, vlanId);
738 return;
739 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000740
741 DHCP6 leafDhcp = getDhcp6Leaf(embeddedDhcp6);
742 ip = extractIpAddress(leafDhcp);
743 if (ip == null) {
744 log.warn("ip is null");
745 } else {
746 Route routeForIP = new Route(Route.Source.STATIC, ip.toIpPrefix(), nextHopIp);
747 log.warn("adding Route of 128 address for indirectly connected.");
748 routeStore.updateRoute(routeForIP);
749 }
750
751 IpPrefix ipPrefix = extractPrefix(leafDhcp);
752 if (ipPrefix == null) {
753 log.warn("ipPrefix is null ");
754 } else {
755 Route routeForPrefix = new Route(Route.Source.STATIC, ipPrefix, nextHopIp);
756 log.warn("adding Route of PD for indirectly connected.");
757 routeStore.updateRoute(routeForPrefix);
Kalhee Kimba366062017-11-07 16:32:09 +0000758 if (this.dhcpFpmEnabled) {
759 FpmRecord record = new FpmRecord(ipPrefix, nextHopIp, FpmRecord.Type.DHCP_RELAY);
760 dhcpFpmPrefixStore.addFpmRecord(ipPrefix, record);
761 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000762 }
763 }
764 }
765 }
766
767 /**
Yi Tseng25bfe372017-11-03 16:27:32 -0700768 * Build the DHCP6 solicit/request packet with gatewayip.
769 * TODO: method too long, need to be refactored.
Kalhee Kim45fede42017-09-05 19:05:06 +0000770 *
771 * @param context packet context
772 * @param clientPacket client ethernet packet
773 * @param clientInterfaces set of client side interfaces
774 */
Yi Tseng3bd57ac2017-11-29 14:39:18 -0800775 private InternalPacket processDhcp6PacketFromClient(PacketContext context,
776 Ethernet clientPacket, Set<Interface> clientInterfaces) {
777 ConnectPoint receivedFrom = context.inPacket().receivedFrom();
778 DeviceId receivedFromDevice = receivedFrom.deviceId();
779 DhcpServerInfo serverInfo;
780 Ip6Address dhcpServerIp = null;
781 ConnectPoint dhcpServerConnectPoint = null;
782 MacAddress dhcpConnectMac = null;
783 VlanId dhcpConnectVlan = null;
784 Ip6Address dhcpGatewayIp = null;
785 Ip6Address indirectDhcpServerIp = null;
786 ConnectPoint indirectDhcpServerConnectPoint = null;
787 MacAddress indirectDhcpConnectMac = null;
788 VlanId indirectDhcpConnectVlan = null;
789 Ip6Address indirectDhcpGatewayIp = null;
790 Ip6Address indirectRelayAgentIpFromCfg = null;
791 if (!defaultServerInfoList.isEmpty()) {
792 serverInfo = defaultServerInfoList.get(0);
793 dhcpConnectMac = serverInfo.getDhcpConnectMac().orElse(null);
794 dhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
795 dhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
796 dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
797 dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
798 }
799 if (!indirectServerInfoList.isEmpty()) {
800 serverInfo = indirectServerInfoList.get(0);
801 indirectDhcpConnectMac = serverInfo.getDhcpConnectMac().orElse(null);
802 indirectDhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
803 indirectDhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
804 indirectDhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
805 indirectDhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
806 indirectRelayAgentIpFromCfg = serverInfo.getRelayAgentIp6(receivedFromDevice).orElse(null);
807 }
808 Ip6Address relayAgentIp = getRelayAgentIPv6Address(clientInterfaces);
809 MacAddress relayAgentMac = clientInterfaces.iterator().next().mac();
810 if (relayAgentIp == null || relayAgentMac == null) {
811 log.warn("Missing DHCP relay agent interface Ipv6 addr config for "
812 + "packet from client on port: {}. Aborting packet processing",
813 clientInterfaces.iterator().next().connectPoint());
814 return null;
815 }
816 // get dhcp6 header.
817 IPv6 clientIpv6 = (IPv6) clientPacket.getPayload();
818 UDP clientUdp = (UDP) clientIpv6.getPayload();
819 DHCP6 clientDhcp6 = (DHCP6) clientUdp.getPayload();
820 boolean directConnFlag = directlyConnected(clientDhcp6);
821 Interface serverInterface;
822 if (directConnFlag) {
823 serverInterface = getServerInterface();
824 } else {
825 serverInterface = getIndirectServerInterface();
826 if (serverInterface == null) {
827 // Indirect server interface not found, use default server interface
828 serverInterface = getServerInterface();
829 }
830 }
831 if (serverInterface == null) {
832 log.warn("Can't get {} server interface, ignore", directConnFlag ? "direct" : "indirect");
833 return null;
834 }
835 Ip6Address ipFacingServer = getFirstIpFromInterface(serverInterface);
836 MacAddress macFacingServer = serverInterface.mac();
837 if (ipFacingServer == null || macFacingServer == null) {
838 log.warn("No IP v6 address for server Interface {}", serverInterface);
839 return null;
840 }
841 Ethernet etherReply = (Ethernet) clientPacket.duplicate();
842 etherReply.setSourceMACAddress(macFacingServer);
843 if ((directConnFlag && dhcpConnectMac == null) ||
844 !directConnFlag && indirectDhcpConnectMac == null && dhcpConnectMac == null) {
845 log.warn("Packet received from {} connected client.", directConnFlag ? "directly" : "indirectly");
846 log.warn("DHCP6 {} not yet resolved .. Aborting DHCP packet processing from client on port: {}",
847 (dhcpGatewayIp == null) ? "server IP " + dhcpServerIp
848 : "gateway IP " + dhcpGatewayIp,
849 clientInterfaces.iterator().next().connectPoint());
850 return null;
851 }
852 if (dhcpServerConnectPoint == null) {
853 log.warn("DHCP6 server connection point direct {} directConn {} indirectConn {} is not set up yet",
Yi Tseng25bfe372017-11-03 16:27:32 -0700854 directConnFlag, dhcpServerConnectPoint, indirectDhcpServerConnectPoint);
Kalhee Kim121ba922017-11-01 17:56:44 +0000855 return null;
856 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000857
Yi Tseng25bfe372017-11-03 16:27:32 -0700858 etherReply.setDestinationMACAddress(dhcpConnectMac);
859 etherReply.setVlanID(dhcpConnectVlan.toShort());
Kalhee Kim121ba922017-11-01 17:56:44 +0000860 IPv6 ipv6Packet = (IPv6) etherReply.getPayload();
861 byte[] peerAddress = clientIpv6.getSourceAddress();
862 ipv6Packet.setSourceAddress(ipFacingServer.toOctets());
Yi Tseng25bfe372017-11-03 16:27:32 -0700863 ipv6Packet.setDestinationAddress(dhcpServerIp.toOctets());
Kalhee Kim121ba922017-11-01 17:56:44 +0000864 UDP udpPacket = (UDP) ipv6Packet.getPayload();
865 udpPacket.setSourcePort(UDP.DHCP_V6_SERVER_PORT);
866 DHCP6 dhcp6Packet = (DHCP6) udpPacket.getPayload();
867 byte[] dhcp6PacketByte = dhcp6Packet.serialize();
Charles Chana990ce92017-10-30 10:22:50 -0700868
Kalhee Kim121ba922017-11-01 17:56:44 +0000869 ConnectPoint clientConnectionPoint = context.inPacket().receivedFrom();
870 VlanId vlanIdInUse = VlanId.vlanId(clientPacket.getVlanID());
871 Interface clientInterface = interfaceService.getInterfacesByPort(clientConnectionPoint)
872 .stream().filter(iface -> interfaceContainsVlan(iface, vlanIdInUse))
873 .findFirst().orElse(null);
Kalhee Kim45fede42017-09-05 19:05:06 +0000874
Kalhee Kim121ba922017-11-01 17:56:44 +0000875 removeHostOrRoute(directConnFlag, dhcp6Packet, clientPacket, clientIpv6, clientInterface);
Kalhee Kim45b24182017-10-18 18:30:23 +0000876
Kalhee Kim121ba922017-11-01 17:56:44 +0000877 DHCP6 dhcp6Relay = new DHCP6();
878 dhcp6Relay.setMsgType(DHCP6.MsgType.RELAY_FORW.value());
Kalhee Kim121ba922017-11-01 17:56:44 +0000879 if (directConnFlag) {
880 dhcp6Relay.setLinkAddress(relayAgentIp.toOctets());
881 log.debug("direct connection: relayAgentIp obtained dynamically {}",
882 HexString.toHexString(relayAgentIp.toOctets(), ":"));
Kalhee Kim45fede42017-09-05 19:05:06 +0000883
Kalhee Kim121ba922017-11-01 17:56:44 +0000884 } else {
Yi Tseng25bfe372017-11-03 16:27:32 -0700885 if (indirectDhcpServerIp == null) {
Kalhee Kim121ba922017-11-01 17:56:44 +0000886 log.warn("indirect DhcpServerIp not available, use default DhcpServerIp {}",
Yi Tseng25bfe372017-11-03 16:27:32 -0700887 HexString.toHexString(dhcpServerIp.toOctets()));
Kalhee Kimd21029f2017-09-26 20:21:53 +0000888 } else {
889 // Indirect case, replace destination to indirect dhcp server if exist
890 // Check if mac is obtained for valid server ip
Yi Tseng25bfe372017-11-03 16:27:32 -0700891 if (indirectDhcpConnectMac == null) {
Kalhee Kimd21029f2017-09-26 20:21:53 +0000892 log.warn("DHCP6 {} not yet resolved .. Aborting DHCP "
Yi Tseng25bfe372017-11-03 16:27:32 -0700893 + "packet processing from client on port: {}",
894 (indirectDhcpGatewayIp == null) ? "server IP " + indirectDhcpServerIp
895 : "gateway IP " + indirectDhcpGatewayIp,
896 clientInterfaces.iterator().next().connectPoint());
Kalhee Kimd21029f2017-09-26 20:21:53 +0000897 return null;
898 }
Yi Tseng25bfe372017-11-03 16:27:32 -0700899 etherReply.setDestinationMACAddress(indirectDhcpConnectMac);
900 etherReply.setVlanID(indirectDhcpConnectVlan.toShort());
901 ipv6Packet.setDestinationAddress(indirectDhcpServerIp.toOctets());
Kalhee Kimd21029f2017-09-26 20:21:53 +0000902 }
Yi Tseng25bfe372017-11-03 16:27:32 -0700903 if (indirectRelayAgentIpFromCfg == null) {
Kalhee Kim45fede42017-09-05 19:05:06 +0000904 dhcp6Relay.setLinkAddress(relayAgentIp.toOctets());
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000905 log.warn("indirect connection: relayAgentIp NOT availale from config file! Use dynamic. {}",
Yi Tseng25bfe372017-11-03 16:27:32 -0700906 HexString.toHexString(relayAgentIp.toOctets(), ":"));
907 } else {
908 dhcp6Relay.setLinkAddress(indirectRelayAgentIpFromCfg.toOctets());
909 log.debug("indirect connection: relayAgentIp from config file is available! {}",
910 HexString.toHexString(indirectRelayAgentIpFromCfg.toOctets(), ":"));
911 }
912 }
913 // peer address: address of the client or relay agent from which
914 // the message to be relayed was received.
915 dhcp6Relay.setPeerAddress(peerAddress);
916 List<Dhcp6Option> options = new ArrayList<>();
917 // directly connected case, hop count is zero; otherwise, hop count + 1
918 if (directConnFlag) {
919 dhcp6Relay.setHopCount((byte) 0);
920 } else {
921 dhcp6Relay.setHopCount((byte) (dhcp6Packet.getHopCount() + 1));
922 }
923 // create relay message option
924 Dhcp6Option relayMessage = new Dhcp6Option();
925 relayMessage.setCode(DHCP6.OptionCode.RELAY_MSG.value());
926 relayMessage.setLength((short) dhcp6PacketByte.length);
927 relayMessage.setData(dhcp6PacketByte);
928 options.add(relayMessage);
929 // create interfaceId option
930 String inPortString = "-" + context.inPacket().receivedFrom().toString() + ":";
931 Dhcp6Option interfaceId = new Dhcp6Option();
932 interfaceId.setCode(DHCP6.OptionCode.INTERFACE_ID.value());
933 byte[] clientSoureMacBytes = clientPacket.getSourceMACAddress();
934 byte[] inPortStringBytes = inPortString.getBytes();
935 byte[] vlanIdBytes = new byte[2];
936 vlanIdBytes[0] = (byte) (clientPacket.getVlanID() & 0xff);
937 vlanIdBytes[1] = (byte) ((clientPacket.getVlanID() >> 8) & 0xff);
938 byte[] interfaceIdBytes = new byte[clientSoureMacBytes.length +
939 inPortStringBytes.length + vlanIdBytes.length];
940 log.debug("Length: interfaceIdBytes {} clientSoureMacBytes {} inPortStringBytes {} vlan {}",
941 interfaceIdBytes.length, clientSoureMacBytes.length, inPortStringBytes.length,
942 vlanIdBytes.length);
943 System.arraycopy(clientSoureMacBytes, 0, interfaceIdBytes, 0, clientSoureMacBytes.length);
944 System.arraycopy(inPortStringBytes, 0, interfaceIdBytes, clientSoureMacBytes.length, inPortStringBytes.length);
945 System.arraycopy(vlanIdBytes, 0, interfaceIdBytes, clientSoureMacBytes.length + inPortStringBytes.length,
946 vlanIdBytes.length);
947 interfaceId.setData(interfaceIdBytes);
948 interfaceId.setLength((short) interfaceIdBytes.length);
949 options.add(interfaceId);
950 log.debug("interfaceId write srcMac {} portString {}",
951 HexString.toHexString(clientSoureMacBytes, ":"), inPortString);
952 dhcp6Relay.setOptions(options);
953 udpPacket.setPayload(dhcp6Relay);
954 udpPacket.resetChecksum();
955 ipv6Packet.setPayload(udpPacket);
956 ipv6Packet.setHopLimit((byte) 64);
957 etherReply.setPayload(ipv6Packet);
958 if (directConnFlag || indirectDhcpServerIp == null) {
959 return new InternalPacket(etherReply, dhcpServerConnectPoint);
960 } else {
961 return new InternalPacket(etherReply, indirectDhcpServerConnectPoint);
962 }
963 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000964
965 /**
966 *
967 * process the DHCP6 relay-reply packet from dhcp server.
968 *
969 * @param context packet context
970 * @param receivedPacket server ethernet packet
971 * @param recevingInterfaces set of server side interfaces
972 */
973 private InternalPacket processDhcp6PacketFromServer(PacketContext context,
974 Ethernet receivedPacket, Set<Interface> recevingInterfaces) {
Yi Tseng25bfe372017-11-03 16:27:32 -0700975
976 ConnectPoint receivedFrom = context.inPacket().receivedFrom();
977 DeviceId receivedFromDevice = receivedFrom.deviceId();
978
979 // TODO: refactor
980 DhcpServerInfo serverInfo;
981 Ip6Address dhcpServerIp = null;
982 ConnectPoint dhcpServerConnectPoint = null;
983 MacAddress dhcpConnectMac = null;
984 VlanId dhcpConnectVlan = null;
985 Ip6Address dhcpGatewayIp = null;
986
987 Ip6Address indirectDhcpServerIp = null;
988 ConnectPoint indirectDhcpServerConnectPoint = null;
989 MacAddress indirectDhcpConnectMac = null;
990 VlanId indirectDhcpConnectVlan = null;
991 Ip6Address indirectDhcpGatewayIp = null;
992 Ip6Address indirectRelayAgentIpFromCfg = null;
993
994 if (!defaultServerInfoList.isEmpty()) {
995 serverInfo = defaultServerInfoList.get(0);
996 dhcpConnectMac = serverInfo.getDhcpConnectMac().orElse(null);
997 dhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
998 dhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
999 dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1000 dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1001 }
1002
1003 if (!indirectServerInfoList.isEmpty()) {
1004 serverInfo = indirectServerInfoList.get(0);
1005 indirectDhcpConnectMac = serverInfo.getDhcpConnectMac().orElse(null);
1006 indirectDhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1007 indirectDhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
1008 indirectDhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1009 indirectDhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1010 indirectRelayAgentIpFromCfg = serverInfo.getRelayAgentIp6(receivedFromDevice).orElse(null);
1011 }
1012
Kalhee Kim45fede42017-09-05 19:05:06 +00001013 // get dhcp6 header.
Ray Milkeyf0c47612017-09-28 11:29:38 -07001014 Ethernet etherReply = receivedPacket.duplicate();
Kalhee Kim45fede42017-09-05 19:05:06 +00001015 IPv6 ipv6Packet = (IPv6) etherReply.getPayload();
1016 UDP udpPacket = (UDP) ipv6Packet.getPayload();
1017 DHCP6 dhcp6Relay = (DHCP6) udpPacket.getPayload();
1018
1019 Boolean directConnFlag = directlyConnected(dhcp6Relay);
Kalhee Kimd21029f2017-09-26 20:21:53 +00001020 ConnectPoint inPort = context.inPacket().receivedFrom();
Yi Tseng25bfe372017-11-03 16:27:32 -07001021 if ((directConnFlag || (!directConnFlag && indirectDhcpServerIp == null))
1022 && !inPort.equals(dhcpServerConnectPoint)) {
Kalhee Kimd21029f2017-09-26 20:21:53 +00001023 log.warn("Receiving port {} is not the same as server connect point {} for direct or indirect-null",
Yi Tseng25bfe372017-11-03 16:27:32 -07001024 inPort, dhcpServerConnectPoint);
Kalhee Kimd21029f2017-09-26 20:21:53 +00001025 return null;
1026 }
1027
Yi Tseng25bfe372017-11-03 16:27:32 -07001028 if (!directConnFlag && indirectDhcpServerIp != null &&
1029 !inPort.equals(indirectDhcpServerConnectPoint)) {
Kalhee Kimd21029f2017-09-26 20:21:53 +00001030 log.warn("Receiving port {} is not the same as server connect point {} for indirect",
Yi Tseng25bfe372017-11-03 16:27:32 -07001031 inPort, indirectDhcpServerConnectPoint);
Kalhee Kimd21029f2017-09-26 20:21:53 +00001032 return null;
1033 }
1034
Kalhee Kim45fede42017-09-05 19:05:06 +00001035
1036 Dhcp6InterfaceIdOption interfaceIdOption = dhcp6Relay.getOptions().stream()
1037 .filter(opt -> opt instanceof Dhcp6InterfaceIdOption)
1038 .map(opt -> (Dhcp6InterfaceIdOption) opt)
1039 .findFirst()
1040 .orElse(null);
1041
1042 if (interfaceIdOption == null) {
1043 log.warn("Interface Id option is not present, abort packet...");
1044 return null;
1045 }
1046
1047 MacAddress peerMac = interfaceIdOption.getMacAddress();
1048 String clientConnectionPointStr = new String(interfaceIdOption.getInPort());
1049
1050 ConnectPoint clientConnectionPoint = ConnectPoint.deviceConnectPoint(clientConnectionPointStr);
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +00001051 VlanId vlanIdInUse = VlanId.vlanId(interfaceIdOption.getVlanId());
1052 Interface clientInterface = interfaceService.getInterfacesByPort(clientConnectionPoint)
1053 .stream()
1054 .filter(iface -> interfaceContainsVlan(iface, vlanIdInUse))
1055 .findFirst()
1056 .orElse(null);
1057 if (clientInterface == null) {
1058 log.warn("Cannot get client interface for from packet, abort... vlan {}", vlanIdInUse.toString());
Kalhee Kim45fede42017-09-05 19:05:06 +00001059 return null;
1060 }
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +00001061 MacAddress relayAgentMac = clientInterface.mac();
Kalhee Kim45fede42017-09-05 19:05:06 +00001062 if (relayAgentMac == null) {
1063 log.warn("Can not get interface mac, abort packet..");
1064 return null;
1065 }
1066 etherReply.setSourceMACAddress(relayAgentMac);
1067
1068 // find destMac
1069 MacAddress clientMac = null;
Yi Tsengaa417a62017-09-08 17:22:51 -07001070 Ip6Address peerAddress = Ip6Address.valueOf(dhcp6Relay.getPeerAddress());
1071 Set<Host> clients = hostService.getHostsByIp(peerAddress);
Kalhee Kim45fede42017-09-05 19:05:06 +00001072 if (clients.isEmpty()) {
1073 log.warn("There's no host found for this address {}",
1074 HexString.toHexString(dhcp6Relay.getPeerAddress(), ":"));
1075 log.warn("Let's look up interfaceId {}", HexString.toHexString(peerMac.toBytes(), ":"));
1076 clientMac = peerMac;
1077 } else {
1078 clientMac = clients.iterator().next().mac();
1079 if (clientMac == null) {
1080 log.warn("No client mac address found, abort packet...");
1081 return null;
1082 }
1083 log.warn("Client mac address found from getHostByIp");
1084
1085 }
1086 etherReply.setDestinationMACAddress(clientMac);
1087
1088 // ip header
1089 ipv6Packet.setSourceAddress(dhcp6Relay.getLinkAddress());
1090 ipv6Packet.setDestinationAddress(dhcp6Relay.getPeerAddress());
1091 // udp header
1092 udpPacket.setSourcePort(UDP.DHCP_V6_SERVER_PORT);
1093 if (directConnFlag) {
1094 udpPacket.setDestinationPort(UDP.DHCP_V6_CLIENT_PORT);
1095 } else {
1096 udpPacket.setDestinationPort(UDP.DHCP_V6_SERVER_PORT);
1097 }
1098
1099 DHCP6 embeddedDhcp6 = dhcp6Relay.getOptions().stream()
1100 .filter(opt -> opt instanceof Dhcp6RelayOption)
1101 .map(BasePacket::getPayload)
1102 .map(pld -> (DHCP6) pld)
1103 .findFirst()
1104 .orElse(null);
1105
1106
1107 // add host or route
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +00001108 addHostOrRoute(directConnFlag, dhcp6Relay, embeddedDhcp6, clientMac, clientInterface);
Kalhee Kim45fede42017-09-05 19:05:06 +00001109
1110 udpPacket.setPayload(embeddedDhcp6);
1111 udpPacket.resetChecksum();
1112 ipv6Packet.setPayload(udpPacket);
1113 etherReply.setPayload(ipv6Packet);
1114
1115 return new InternalPacket(etherReply, clientConnectionPoint);
1116 }
1117
Yi Tseng919b2df2017-09-07 16:22:51 -07001118 // Returns the first v6 interface ip out of a set of interfaces or null.
Kalhee Kim45fede42017-09-05 19:05:06 +00001119 // Checks all interfaces, and ignores v6 interface ips
1120 private Ip6Address getRelayAgentIPv6Address(Set<Interface> intfs) {
1121 for (Interface intf : intfs) {
1122 for (InterfaceIpAddress ip : intf.ipAddressesList()) {
1123 Ip6Address relayAgentIp = ip.ipAddress().getIp6Address();
1124 if (relayAgentIp != null) {
1125 return relayAgentIp;
1126 }
1127 }
1128 }
1129 return null;
Yi Tseng51301292017-07-28 13:02:59 -07001130 }
Yi Tseng483ac6f2017-08-02 15:03:31 -07001131
1132 @Override
Kalhee Kimba366062017-11-07 16:32:09 +00001133 public void setDhcpFpmEnabled(Boolean enabled) {
1134 dhcpFpmEnabled = enabled;
1135 }
1136
1137 @Override
Yi Tseng483ac6f2017-08-02 15:03:31 -07001138 public void setDefaultDhcpServerConfigs(Collection<DhcpServerConfig> configs) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001139 setDhcpServerConfigs(configs, defaultServerInfoList);
Yi Tseng919b2df2017-09-07 16:22:51 -07001140 }
1141
1142 @Override
1143 public void setIndirectDhcpServerConfigs(Collection<DhcpServerConfig> configs) {
1144 setDhcpServerConfigs(configs, indirectServerInfoList);
Yi Tseng919b2df2017-09-07 16:22:51 -07001145 }
1146
1147 public void setDhcpServerConfigs(Collection<DhcpServerConfig> configs, List<DhcpServerInfo> serverInfoList) {
Kalhee Kim45fede42017-09-05 19:05:06 +00001148 if (configs.size() == 0) {
1149 // no config to update
1150 return;
1151 }
1152
1153 // TODO: currently we pick up first DHCP server config.
1154 // Will use other server configs in the future for HA.
1155 DhcpServerConfig serverConfig = configs.iterator().next();
Yi Tseng919b2df2017-09-07 16:22:51 -07001156
Kalhee Kim45fede42017-09-05 19:05:06 +00001157 if (!serverConfig.getDhcpServerIp6().isPresent()) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001158 // not a DHCPv6 config
Kalhee Kim45fede42017-09-05 19:05:06 +00001159 return;
1160 }
1161
Yi Tseng919b2df2017-09-07 16:22:51 -07001162 if (!serverInfoList.isEmpty()) {
1163 // remove old server info
1164 DhcpServerInfo oldServerInfo = serverInfoList.remove(0);
1165
1166 // stop monitoring gateway or server
1167 oldServerInfo.getDhcpGatewayIp6().ifPresent(gatewayIp -> {
1168 hostService.stopMonitoringIp(gatewayIp);
1169 });
1170 oldServerInfo.getDhcpServerIp6().ifPresent(serverIp -> {
1171 hostService.stopMonitoringIp(serverIp);
Yi Tseng525ff402017-10-23 19:39:39 -07001172 cancelDhcpPacket(serverIp);
Yi Tseng919b2df2017-09-07 16:22:51 -07001173 });
1174 }
1175
1176 // Create new server info according to the config
1177 DhcpServerInfo newServerInfo = new DhcpServerInfo(serverConfig,
1178 DhcpServerInfo.Version.DHCP_V6);
1179 checkState(newServerInfo.getDhcpServerConnectPoint().isPresent(),
1180 "Connect point not exists");
1181 checkState(newServerInfo.getDhcpServerIp6().isPresent(),
1182 "IP of DHCP server not exists");
1183
1184 log.debug("DHCP server connect point: {}", newServerInfo.getDhcpServerConnectPoint().orElse(null));
1185 log.debug("DHCP server IP: {}", newServerInfo.getDhcpServerIp6().orElse(null));
1186
Yi Tseng525ff402017-10-23 19:39:39 -07001187 Ip6Address serverIp = newServerInfo.getDhcpServerIp6().get();
1188 Ip6Address ipToProbe;
Yi Tseng919b2df2017-09-07 16:22:51 -07001189 if (newServerInfo.getDhcpGatewayIp6().isPresent()) {
1190 ipToProbe = newServerInfo.getDhcpGatewayIp6().get();
1191 } else {
1192 ipToProbe = newServerInfo.getDhcpServerIp6().orElse(null);
1193 }
1194 String hostToProbe = newServerInfo.getDhcpGatewayIp6()
1195 .map(ip -> "gateway").orElse("server");
1196
1197 log.debug("Probing to resolve {} IP {}", hostToProbe, ipToProbe);
Kalhee Kim45fede42017-09-05 19:05:06 +00001198 hostService.startMonitoringIp(ipToProbe);
1199
1200 Set<Host> hosts = hostService.getHostsByIp(ipToProbe);
1201 if (!hosts.isEmpty()) {
1202 Host host = hosts.iterator().next();
Yi Tseng919b2df2017-09-07 16:22:51 -07001203 newServerInfo.setDhcpConnectVlan(host.vlan());
1204 newServerInfo.setDhcpConnectMac(host.mac());
Kalhee Kim45fede42017-09-05 19:05:06 +00001205 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001206 // Add new server info
Yi Tseng48cd0862017-11-09 13:54:12 -08001207 synchronized (this) {
1208 serverInfoList.clear();
1209 serverInfoList.add(0, newServerInfo);
1210 }
Yi Tseng525ff402017-10-23 19:39:39 -07001211 requestDhcpPacket(serverIp);
Kalhee Kim45fede42017-09-05 19:05:06 +00001212 }
1213
1214 class InternalHostListener implements HostListener {
1215 @Override
1216 public void event(HostEvent event) {
1217 switch (event.type()) {
1218 case HOST_ADDED:
1219 case HOST_UPDATED:
1220 hostUpdated(event.subject());
1221 break;
1222 case HOST_REMOVED:
1223 hostRemoved(event.subject());
1224 break;
Kalhee Kim45fede42017-09-05 19:05:06 +00001225 default:
1226 break;
1227 }
1228 }
1229 }
1230
1231 /**
Kalhee Kim45fede42017-09-05 19:05:06 +00001232 * Handle host updated.
1233 * If the host is DHCP server or gateway, update connect mac and vlan.
1234 *
1235 * @param host the host
1236 */
1237 private void hostUpdated(Host host) {
Yi Tseng525ff402017-10-23 19:39:39 -07001238 hostUpdated(host, defaultServerInfoList);
1239 hostUpdated(host, indirectServerInfoList);
Kalhee Kim45fede42017-09-05 19:05:06 +00001240 }
1241
Yi Tseng525ff402017-10-23 19:39:39 -07001242 private void hostUpdated(Host host, List<DhcpServerInfo> serverInfoList) {
1243 DhcpServerInfo serverInfo;
1244 Ip6Address targetIp;
1245 if (!serverInfoList.isEmpty()) {
1246 serverInfo = serverInfoList.get(0);
1247 Ip6Address serverIp = serverInfo.getDhcpServerIp6().orElse(null);
1248 targetIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1249
1250 if (targetIp == null) {
1251 targetIp = serverIp;
1252 }
1253
1254 if (targetIp != null) {
1255 if (host.ipAddresses().contains(targetIp)) {
1256 serverInfo.setDhcpConnectMac(host.mac());
1257 serverInfo.setDhcpConnectVlan(host.vlan());
1258 requestDhcpPacket(serverIp);
1259 }
1260 }
1261 }
1262 }
1263
Kalhee Kim45fede42017-09-05 19:05:06 +00001264 /**
1265 * Handle host removed.
1266 * If the host is DHCP server or gateway, unset connect mac and vlan.
1267 *
1268 * @param host the host
1269 */
1270 private void hostRemoved(Host host) {
Yi Tseng525ff402017-10-23 19:39:39 -07001271 hostRemoved(host, defaultServerInfoList);
1272 hostRemoved(host, indirectServerInfoList);
Yi Tseng919b2df2017-09-07 16:22:51 -07001273 }
1274
Yi Tseng525ff402017-10-23 19:39:39 -07001275 private void hostRemoved(Host host, List<DhcpServerInfo> serverInfoList) {
1276 DhcpServerInfo serverInfo;
1277 Ip6Address targetIp;
1278
1279 if (!serverInfoList.isEmpty()) {
1280 serverInfo = serverInfoList.get(0);
1281 Ip6Address serverIp = serverInfo.getDhcpServerIp6().orElse(null);
1282 targetIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1283
1284 if (targetIp == null) {
1285 targetIp = serverIp;
1286 }
1287
1288 if (targetIp != null) {
1289 if (host.ipAddresses().contains(targetIp)) {
1290 serverInfo.setDhcpConnectVlan(null);
1291 serverInfo.setDhcpConnectMac(null);
1292 cancelDhcpPacket(serverIp);
1293 }
1294 }
1295 }
1296 }
1297
Kalhee Kim45b24182017-10-18 18:30:23 +00001298 /**
1299 * Returns the first interface ip from interface.
1300 *
1301 * @param iface interface of one connect point
1302 * @return the first interface IP; null if not exists an IP address in
1303 * these interfaces
1304 */
1305 private Ip6Address getFirstIpFromInterface(Interface iface) {
1306 checkNotNull(iface, "Interface can't be null");
1307 return iface.ipAddressesList().stream()
1308 .map(InterfaceIpAddress::ipAddress)
1309 .filter(IpAddress::isIp6)
1310 .map(IpAddress::getIp6Address)
1311 .findFirst()
1312 .orElse(null);
1313 }
1314
1315 /**
1316 * Gets Interface facing to the server for default host.
1317 *
1318 * @return the Interface facing to the server; null if not found
1319 */
1320 private Interface getServerInterface() {
Yi Tseng25bfe372017-11-03 16:27:32 -07001321 DhcpServerInfo serverInfo;
1322 ConnectPoint dhcpServerConnectPoint;
1323 VlanId dhcpConnectVlan;
1324
1325 if (!defaultServerInfoList.isEmpty()) {
1326 serverInfo = defaultServerInfoList.get(0);
1327 dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1328 dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1329 } else {
Kalhee Kim45b24182017-10-18 18:30:23 +00001330 return null;
1331 }
Yi Tseng921e5b02017-11-17 17:14:41 -08001332 if (dhcpServerConnectPoint == null || dhcpConnectVlan == null) {
1333 log.info("Default DHCP server {} not resolve yet", serverInfo.getDhcpGatewayIp6());
1334 return null;
1335 }
Kalhee Kim45b24182017-10-18 18:30:23 +00001336 return interfaceService.getInterfacesByPort(dhcpServerConnectPoint)
1337 .stream()
1338 .filter(iface -> interfaceContainsVlan(iface, dhcpConnectVlan))
1339 .findFirst()
1340 .orElse(null);
1341 }
1342
1343 /**
1344 * Gets Interface facing to the server for indirect hosts.
1345 * Use default server Interface if indirect server not configured.
1346 *
1347 * @return the Interface facing to the server; null if not found
1348 */
1349 private Interface getIndirectServerInterface() {
Yi Tseng25bfe372017-11-03 16:27:32 -07001350 DhcpServerInfo serverInfo;
1351
1352 ConnectPoint indirectDhcpServerConnectPoint;
1353 VlanId indirectDhcpConnectVlan;
1354
1355 if (!indirectServerInfoList.isEmpty()) {
1356 serverInfo = indirectServerInfoList.get(0);
1357 indirectDhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1358 indirectDhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1359 } else {
Kalhee Kim45b24182017-10-18 18:30:23 +00001360 return getServerInterface();
1361 }
Yi Tseng921e5b02017-11-17 17:14:41 -08001362 if (indirectDhcpServerConnectPoint == null || indirectDhcpConnectVlan == null) {
1363 log.info("Indirect DHCP server {} not resolve yet", serverInfo.getDhcpGatewayIp6());
1364 return null;
1365 }
Kalhee Kim45b24182017-10-18 18:30:23 +00001366 return interfaceService.getInterfacesByPort(indirectDhcpServerConnectPoint)
1367 .stream()
1368 .filter(iface -> interfaceContainsVlan(iface, indirectDhcpConnectVlan))
1369 .findFirst()
1370 .orElse(null);
1371 }
1372
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +00001373 /**
1374 * Determind if an Interface contains a vlan id.
1375 *
1376 * @param iface the Interface
1377 * @param vlanId the vlan id
1378 * @return true if the Interface contains the vlan id
1379 */
1380 private boolean interfaceContainsVlan(Interface iface, VlanId vlanId) {
1381 if (vlanId.equals(VlanId.NONE)) {
1382 // untagged packet, check if vlan untagged or vlan native is not NONE
1383 return !iface.vlanUntagged().equals(VlanId.NONE) ||
1384 !iface.vlanNative().equals(VlanId.NONE);
1385 }
1386 // tagged packet, check if the interface contains the vlan
1387 return iface.vlanTagged().contains(vlanId);
1388 }
1389
Yi Tseng525ff402017-10-23 19:39:39 -07001390 private void requestDhcpPacket(Ip6Address serverIp) {
1391 requestServerDhcpPacket(serverIp);
1392 requestClientDhcpPacket(serverIp);
1393 }
1394
1395 private void cancelDhcpPacket(Ip6Address serverIp) {
1396 cancelServerDhcpPacket(serverIp);
1397 cancelClientDhcpPacket(serverIp);
1398 }
1399
1400 private void cancelServerDhcpPacket(Ip6Address serverIp) {
1401 TrafficSelector serverSelector =
1402 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1403 .matchIPv6Src(serverIp.toIpPrefix())
1404 .build();
1405 packetService.cancelPackets(serverSelector,
1406 PacketPriority.CONTROL,
1407 appId);
1408 }
1409
1410 private void requestServerDhcpPacket(Ip6Address serverIp) {
1411 TrafficSelector serverSelector =
1412 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1413 .matchIPv6Src(serverIp.toIpPrefix())
1414 .build();
1415 packetService.requestPackets(serverSelector,
1416 PacketPriority.CONTROL,
1417 appId);
1418 }
1419
1420 private void cancelClientDhcpPacket(Ip6Address serverIp) {
1421 // Packet comes from relay
1422 TrafficSelector indirectClientSelector =
1423 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1424 .matchIPv6Dst(serverIp.toIpPrefix())
1425 .build();
1426 packetService.cancelPackets(indirectClientSelector,
1427 PacketPriority.CONTROL,
1428 appId);
Yi Tseng41dde702017-11-02 15:21:10 -07001429 indirectClientSelector =
1430 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1431 .matchIPv6Dst(Ip6Address.ALL_DHCP_RELAY_AGENTS_AND_SERVERS.toIpPrefix())
1432 .build();
1433 packetService.cancelPackets(indirectClientSelector,
1434 PacketPriority.CONTROL,
1435 appId);
1436 indirectClientSelector =
1437 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1438 .matchIPv6Dst(Ip6Address.ALL_DHCP_SERVERS.toIpPrefix())
1439 .build();
1440 packetService.cancelPackets(indirectClientSelector,
1441 PacketPriority.CONTROL,
1442 appId);
Yi Tseng525ff402017-10-23 19:39:39 -07001443
1444 // Packet comes from client
1445 packetService.cancelPackets(CLIENT_SERVER_SELECTOR,
1446 PacketPriority.CONTROL,
1447 appId);
1448 }
1449
1450 private void requestClientDhcpPacket(Ip6Address serverIp) {
1451 // Packet comes from relay
1452 TrafficSelector indirectClientSelector =
1453 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1454 .matchIPv6Dst(serverIp.toIpPrefix())
1455 .build();
1456 packetService.requestPackets(indirectClientSelector,
1457 PacketPriority.CONTROL,
1458 appId);
Yi Tseng41dde702017-11-02 15:21:10 -07001459 indirectClientSelector =
1460 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1461 .matchIPv6Dst(Ip6Address.ALL_DHCP_RELAY_AGENTS_AND_SERVERS.toIpPrefix())
1462 .build();
1463 packetService.requestPackets(indirectClientSelector,
1464 PacketPriority.CONTROL,
1465 appId);
1466 indirectClientSelector =
1467 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1468 .matchIPv6Dst(Ip6Address.ALL_DHCP_SERVERS.toIpPrefix())
1469 .build();
1470 packetService.requestPackets(indirectClientSelector,
1471 PacketPriority.CONTROL,
1472 appId);
Yi Tseng525ff402017-10-23 19:39:39 -07001473
1474 // Packet comes from client
1475 packetService.requestPackets(CLIENT_SERVER_SELECTOR,
1476 PacketPriority.CONTROL,
1477 appId);
1478 }
1479
1480 /**
1481 * Process the ignore rules.
1482 *
1483 * @param deviceId the device id
1484 * @param vlanId the vlan to be ignored
1485 * @param op the operation, ADD to install; REMOVE to uninstall rules
1486 */
1487 private void processIgnoreVlanRule(DeviceId deviceId, VlanId vlanId, Objective.Operation op) {
Yi Tseng525ff402017-10-23 19:39:39 -07001488 AtomicInteger installedCount = new AtomicInteger(DHCP_SELECTORS.size());
1489 DHCP_SELECTORS.forEach(trafficSelector -> {
1490 TrafficSelector selector = DefaultTrafficSelector.builder(trafficSelector)
1491 .matchVlanId(vlanId)
1492 .build();
1493
1494 ForwardingObjective.Builder builder = DefaultForwardingObjective.builder()
1495 .withFlag(ForwardingObjective.Flag.VERSATILE)
1496 .withSelector(selector)
1497 .withPriority(IGNORE_CONTROL_PRIORITY)
Yi Tsengdbabeed2017-11-29 10:49:20 -08001498 .withTreatment(DefaultTrafficTreatment.emptyTreatment())
Yi Tseng525ff402017-10-23 19:39:39 -07001499 .fromApp(appId);
1500
1501
1502 ObjectiveContext objectiveContext = new ObjectiveContext() {
1503 @Override
1504 public void onSuccess(Objective objective) {
1505 log.info("Ignore rule {} (Vlan id {}, device {}, selector {})",
1506 op, vlanId, deviceId, selector);
1507 int countDown = installedCount.decrementAndGet();
1508 if (countDown != 0) {
1509 return;
1510 }
1511 switch (op) {
1512 case ADD:
1513 ignoredVlans.put(deviceId, vlanId);
1514 break;
1515 case REMOVE:
1516 ignoredVlans.remove(deviceId, vlanId);
1517 break;
1518 default:
1519 log.warn("Unsupported objective operation {}", op);
1520 break;
1521 }
1522 }
1523
1524 @Override
1525 public void onError(Objective objective, ObjectiveError error) {
1526 log.warn("Can't {} ignore rule (vlan id {}, selector {}, device {}) due to {}",
1527 op, vlanId, selector, deviceId, error);
1528 }
1529 };
1530
1531 ForwardingObjective fwd;
1532 switch (op) {
1533 case ADD:
1534 fwd = builder.add(objectiveContext);
1535 break;
1536 case REMOVE:
1537 fwd = builder.remove(objectiveContext);
1538 break;
1539 default:
1540 log.warn("Unsupported objective operation {}", op);
1541 return;
1542 }
1543
1544 Device device = deviceService.getDevice(deviceId);
1545 if (device == null || !device.is(Pipeliner.class)) {
1546 log.warn("Device {} is not available now, wait until device is available", deviceId);
1547 return;
1548 }
1549 flowObjectiveService.apply(deviceId, fwd);
1550 });
1551 }
Kalhee Kim121ba922017-11-01 17:56:44 +00001552
1553 /**
1554 * Find first ipaddress for a given Host info i.e. mac and vlan.
1555 *
1556 * @param clientMac client mac
1557 * @param vlanId packet's vlan
1558 * @return next-hop link-local ipaddress for a given host
1559 */
1560 private IpAddress getFirstIpByHost(MacAddress clientMac, VlanId vlanId) {
1561 IpAddress nextHopIp;
1562 // pick out the first link-local ip address
1563 HostId gwHostId = HostId.hostId(clientMac, vlanId);
1564 Host gwHost = hostService.getHost(gwHostId);
1565 if (gwHost == null) {
1566 log.warn("Can't find gateway host for hostId {}", gwHostId);
1567 return null;
1568 }
1569 nextHopIp = gwHost.ipAddresses()
1570 .stream()
1571 .filter(IpAddress::isIp6)
1572 .filter(ip6 -> ip6.isLinkLocal())
1573 .map(IpAddress::getIp6Address)
1574 .findFirst()
1575 .orElse(null);
1576 return nextHopIp;
1577 }
Yi Tseng51301292017-07-28 13:02:59 -07001578}