blob: 754d70d94a0ea73cbe4480b750945ee2c6affb67 [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 Tseng919b2df2017-09-07 16:22:51 -070020import com.google.common.collect.Lists;
Kalhee Kim45fede42017-09-05 19:05:06 +000021import org.apache.felix.scr.annotations.Activate;
22import org.apache.felix.scr.annotations.Deactivate;
Kalhee Kim45fede42017-09-05 19:05:06 +000023import com.google.common.collect.Sets;
24import com.google.common.collect.ImmutableSet;
Yi Tseng51301292017-07-28 13:02:59 -070025import org.apache.felix.scr.annotations.Component;
26import org.apache.felix.scr.annotations.Property;
Kalhee Kim45fede42017-09-05 19:05:06 +000027import org.apache.felix.scr.annotations.Reference;
28import org.apache.felix.scr.annotations.ReferenceCardinality;
Yi Tseng51301292017-07-28 13:02:59 -070029import org.apache.felix.scr.annotations.Service;
30import org.onlab.packet.BasePacket;
Kalhee Kim45fede42017-09-05 19:05:06 +000031import org.onlab.packet.DHCP6;
32import org.onlab.packet.IPv6;
33import org.onlab.packet.Ethernet;
34import org.onlab.packet.Ip6Address;
Yi Tseng51301292017-07-28 13:02:59 -070035import org.onlab.packet.IpAddress;
Kalhee Kim45fede42017-09-05 19:05:06 +000036import org.onlab.packet.IpPrefix;
Yi Tseng51301292017-07-28 13:02:59 -070037import org.onlab.packet.MacAddress;
Kalhee Kim45fede42017-09-05 19:05:06 +000038import org.onlab.packet.UDP;
Yi Tseng51301292017-07-28 13:02:59 -070039import org.onlab.packet.VlanId;
Kalhee Kim45fede42017-09-05 19:05:06 +000040import org.onlab.packet.dhcp.Dhcp6RelayOption;
41import org.onlab.packet.dhcp.Dhcp6InterfaceIdOption;
42import org.onlab.packet.dhcp.Dhcp6Option;
43import org.onlab.packet.dhcp.Dhcp6IaNaOption;
44import org.onlab.packet.dhcp.Dhcp6IaTaOption;
45import org.onlab.packet.dhcp.Dhcp6IaPdOption;
46import org.onlab.packet.dhcp.Dhcp6IaAddressOption;
47import org.onlab.packet.dhcp.Dhcp6IaPrefixOption;
48import org.onlab.util.HexString;
Yi Tseng51301292017-07-28 13:02:59 -070049import org.onosproject.dhcprelay.api.DhcpHandler;
Yi Tseng919b2df2017-09-07 16:22:51 -070050import org.onosproject.dhcprelay.api.DhcpServerInfo;
Kalhee Kim45fede42017-09-05 19:05:06 +000051import org.onosproject.dhcprelay.store.DhcpRelayStore;
Yi Tsengaa417a62017-09-08 17:22:51 -070052import org.onosproject.net.host.HostProvider;
53import org.onosproject.net.host.HostProviderRegistry;
54import org.onosproject.net.host.HostProviderService;
Kalhee Kim45fede42017-09-05 19:05:06 +000055import org.onosproject.net.host.HostService;
56import org.onosproject.net.host.DefaultHostDescription;
57import org.onosproject.net.host.HostDescription;
58import org.onosproject.net.host.InterfaceIpAddress;
59import org.onosproject.net.host.HostListener;
60import org.onosproject.net.host.HostEvent;
61import org.onosproject.net.intf.Interface;
62import org.onosproject.net.intf.InterfaceService;
Yi Tsengaa417a62017-09-08 17:22:51 -070063import org.onosproject.net.provider.ProviderId;
Kalhee Kim45fede42017-09-05 19:05:06 +000064import org.onosproject.routeservice.Route;
65import org.onosproject.routeservice.RouteStore;
Yi Tseng483ac6f2017-08-02 15:03:31 -070066import org.onosproject.dhcprelay.config.DhcpServerConfig;
Yi Tseng51301292017-07-28 13:02:59 -070067import org.onosproject.net.ConnectPoint;
Kalhee Kim45fede42017-09-05 19:05:06 +000068import org.onosproject.net.Host;
69import org.onosproject.net.HostId;
70import org.onosproject.net.HostLocation;
71import org.onosproject.net.packet.DefaultOutboundPacket;
72import org.onosproject.net.packet.OutboundPacket;
Yi Tseng51301292017-07-28 13:02:59 -070073import org.onosproject.net.packet.PacketContext;
Kalhee Kim45fede42017-09-05 19:05:06 +000074import org.onosproject.net.packet.PacketService;
75import org.slf4j.Logger;
76import org.slf4j.LoggerFactory;
77import org.onosproject.net.flow.DefaultTrafficTreatment;
78import org.onosproject.net.flow.TrafficTreatment;
Yi Tseng51301292017-07-28 13:02:59 -070079
Kalhee Kim45fede42017-09-05 19:05:06 +000080
81import java.nio.ByteBuffer;
82import java.util.List;
Yi Tseng483ac6f2017-08-02 15:03:31 -070083import java.util.Collection;
Yi Tseng51301292017-07-28 13:02:59 -070084import java.util.Optional;
Kalhee Kim45fede42017-09-05 19:05:06 +000085import java.util.Set;
86import java.util.ArrayList;
Yi Tseng919b2df2017-09-07 16:22:51 -070087import java.util.stream.Collectors;
Kalhee Kim45fede42017-09-05 19:05:06 +000088
89
90import static com.google.common.base.Preconditions.checkNotNull;
91import static com.google.common.base.Preconditions.checkState;
Yi Tseng51301292017-07-28 13:02:59 -070092
93@Component
94@Service
95@Property(name = "version", value = "6")
Yi Tsengaa417a62017-09-08 17:22:51 -070096public class Dhcp6HandlerImpl implements DhcpHandler, HostProvider {
Charles Chand988c282017-09-12 17:09:32 -070097 public static final String DHCP_V6_RELAY_APP = "org.onosproject.Dhcp6HandlerImpl";
Saurav Das7c6dec12017-09-13 14:35:56 -070098 public static final ProviderId PROVIDER_ID = new ProviderId("dhcp6", DHCP_V6_RELAY_APP);
Kalhee Kim45fede42017-09-05 19:05:06 +000099 private static Logger log = LoggerFactory.getLogger(Dhcp6HandlerImpl.class);
Yi Tseng51301292017-07-28 13:02:59 -0700100
Kalhee Kim45fede42017-09-05 19:05:06 +0000101 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
102 protected DhcpRelayStore dhcpRelayStore;
Yi Tseng51301292017-07-28 13:02:59 -0700103
Kalhee Kim45fede42017-09-05 19:05:06 +0000104 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
105 protected PacketService packetService;
106
107 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Kalhee Kim45fede42017-09-05 19:05:06 +0000108 protected RouteStore routeStore;
109
110 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
111 protected InterfaceService interfaceService;
112
113 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
114 protected HostService hostService;
115
Yi Tsengaa417a62017-09-08 17:22:51 -0700116 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
117 protected HostProviderRegistry providerRegistry;
Kalhee Kim45fede42017-09-05 19:05:06 +0000118
Yi Tsengaa417a62017-09-08 17:22:51 -0700119 private InternalHostListener hostListener = new InternalHostListener();
120 protected HostProviderService providerService;
Kalhee Kim45fede42017-09-05 19:05:06 +0000121 private Ip6Address dhcpServerIp = null;
122 // dhcp server may be connected directly to the SDN network or
123 // via an external gateway. When connected directly, the dhcpConnectPoint, dhcpConnectMac,
124 // and dhcpConnectVlan refer to the server. When connected via the gateway, they refer
125 // to the gateway.
126 private ConnectPoint dhcpServerConnectPoint = null;
127 private MacAddress dhcpConnectMac = null;
128 private VlanId dhcpConnectVlan = null;
129 private Ip6Address dhcpGatewayIp = null;
130 private Ip6Address relayAgentIpFromCfg = null;
131
132 private Ip6Address indirectDhcpServerIp = null;
133 private ConnectPoint indirectDhcpServerConnectPoint = null;
134 private MacAddress indirectDhcpConnectMac = null;
135 private VlanId indirectDhcpConnectVlan = null;
136 private Ip6Address indirectDhcpGatewayIp = null;
137 private Ip6Address indirectRelayAgentIpFromCfg = null;
138
Yi Tseng919b2df2017-09-07 16:22:51 -0700139 private List<DhcpServerInfo> defaultServerInfoList = Lists.newArrayList();
140 private List<DhcpServerInfo> indirectServerInfoList = Lists.newArrayList();
141
Kalhee Kim45fede42017-09-05 19:05:06 +0000142
143 // CLIENT message types
144 public static final Set<Byte> MSG_TYPE_FROM_CLIENT =
145 ImmutableSet.of(DHCP6.MsgType.SOLICIT.value(),
146 DHCP6.MsgType.REQUEST.value(),
147 DHCP6.MsgType.REBIND.value(),
148 DHCP6.MsgType.RENEW.value(),
149 DHCP6.MsgType.RELEASE.value(),
150 DHCP6.MsgType.DECLINE.value(),
151 DHCP6.MsgType.CONFIRM.value(),
152 DHCP6.MsgType.RELAY_FORW.value());
153 // SERVER message types
154 public static final Set<Byte> MSG_TYPE_FROM_SERVER =
155 ImmutableSet.of(DHCP6.MsgType.RELAY_REPL.value());
156
157 @Activate
158 protected void activate() {
Yi Tsengaa417a62017-09-08 17:22:51 -0700159 providerService = providerRegistry.register(this);
Kalhee Kim45fede42017-09-05 19:05:06 +0000160 hostService.addListener(hostListener);
Yi Tseng51301292017-07-28 13:02:59 -0700161 }
162
Kalhee Kim45fede42017-09-05 19:05:06 +0000163 @Deactivate
164 protected void deactivate() {
Yi Tsengaa417a62017-09-08 17:22:51 -0700165 providerRegistry.unregister(this);
Kalhee Kim45fede42017-09-05 19:05:06 +0000166 hostService.removeListener(hostListener);
Yi Tseng919b2df2017-09-07 16:22:51 -0700167 defaultServerInfoList.forEach(this::stopMonitoringIps);
168 defaultServerInfoList.clear();
169 indirectServerInfoList.forEach(this::stopMonitoringIps);
170 indirectServerInfoList.clear();
171 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000172
Yi Tseng919b2df2017-09-07 16:22:51 -0700173 private void stopMonitoringIps(DhcpServerInfo serverInfo) {
174 serverInfo.getDhcpGatewayIp6().ifPresent(gatewayIp -> {
175 hostService.stopMonitoringIp(gatewayIp);
176 });
177 serverInfo.getDhcpServerIp6().ifPresent(serverIp -> {
178 hostService.stopMonitoringIp(serverIp);
179 });
Yi Tseng51301292017-07-28 13:02:59 -0700180 }
181
Yi Tseng51301292017-07-28 13:02:59 -0700182 @Override
Yi Tseng919b2df2017-09-07 16:22:51 -0700183 public List<DhcpServerInfo> getDefaultDhcpServerInfoList() {
184 return defaultServerInfoList;
Yi Tseng51301292017-07-28 13:02:59 -0700185 }
186
187 @Override
Yi Tseng919b2df2017-09-07 16:22:51 -0700188 public List<DhcpServerInfo> getIndirectDhcpServerInfoList() {
189 return indirectServerInfoList;
Yi Tseng51301292017-07-28 13:02:59 -0700190 }
191
192 @Override
Kalhee Kim45fede42017-09-05 19:05:06 +0000193 public void processDhcpPacket(PacketContext context, BasePacket payload) {
194 checkNotNull(payload, "DHCP6 payload can't be null");
195 checkState(payload instanceof DHCP6, "Payload is not a DHCP6");
196 DHCP6 dhcp6Payload = (DHCP6) payload;
197 Ethernet receivedPacket = context.inPacket().parsed();
198
199 if (!configured()) {
200 log.warn("Missing DHCP6 relay server config. Abort packet processing");
201 log.warn("dhcp6 payload {}", dhcp6Payload);
202
203 return;
204 }
205
206 byte msgType = dhcp6Payload.getMsgType();
207 log.warn("msgType is {}", msgType);
208
209 ConnectPoint inPort = context.inPacket().receivedFrom();
210 if (inPort == null) {
211 log.warn("incommin ConnectPoint is null");
212 }
213 Set<Interface> receivingInterfaces = interfaceService.getInterfacesByPort(inPort);
214 //ignore the packets if dhcp client interface is not configured on onos.
215 if (receivingInterfaces.isEmpty()) {
216 log.warn("Virtual interface is not configured on {}", inPort);
217 return;
218 }
219
220
221 if (MSG_TYPE_FROM_CLIENT.contains(msgType)) {
222
223 InternalPacket ethernetClientPacket =
224 processDhcp6PacketFromClient(context, receivedPacket, receivingInterfaces);
225 if (ethernetClientPacket != null) {
226 forwardPacket(ethernetClientPacket);
227 }
228
229 } else if (MSG_TYPE_FROM_SERVER.contains(msgType)) {
230 log.warn("calling processDhcp6PacketFromServer with RELAY_REPL", msgType);
231 InternalPacket ethernetPacketReply =
232 processDhcp6PacketFromServer(context, receivedPacket, receivingInterfaces);
233 if (ethernetPacketReply != null) {
234 forwardPacket(ethernetPacketReply);
235 }
236 } else {
237 log.warn("Not so fast, packet type {} not supported yet", msgType);
238 }
239 }
240
241
242 /**
243 * Checks if this app has been configured.
244 *
245 * @return true if all information we need have been initialized
246 */
247 public boolean configured() {
Yi Tseng919b2df2017-09-07 16:22:51 -0700248 return !defaultServerInfoList.isEmpty();
Kalhee Kim45fede42017-09-05 19:05:06 +0000249 }
250
Yi Tsengaa417a62017-09-08 17:22:51 -0700251 @Override
252 public ProviderId id() {
Charles Chand988c282017-09-12 17:09:32 -0700253 return PROVIDER_ID;
Yi Tsengaa417a62017-09-08 17:22:51 -0700254 }
255
256 @Override
257 public void triggerProbe(Host host) {
258 // Do nothing here
259 }
260
Kalhee Kim45fede42017-09-05 19:05:06 +0000261 // the new class the contains Ethernet packet and destination port, kind of like adding
262 // internal header to the packet
263 private class InternalPacket {
264 Ethernet packet;
265 ConnectPoint destLocation;
266 public InternalPacket(Ethernet newPacket, ConnectPoint newLocation) {
267 packet = newPacket;
268 destLocation = newLocation;
269 }
270 void setLocation(ConnectPoint newLocation) {
271 destLocation = newLocation;
272 }
273 }
274
275 //forward the packet to ConnectPoint where the DHCP server is attached.
276 private void forwardPacket(InternalPacket packet) {
277 //send Packetout to dhcp server connectpoint.
278 if (packet.destLocation != null) {
279 TrafficTreatment t = DefaultTrafficTreatment.builder()
280 .setOutput(packet.destLocation.port()).build();
281 OutboundPacket o = new DefaultOutboundPacket(
282 packet.destLocation.deviceId(), t, ByteBuffer.wrap(packet.packet.serialize()));
283 if (log.isTraceEnabled()) {
284 log.trace("Relaying packet to destination {}", packet.destLocation);
285 }
286 packetService.emit(o);
287 } // if
288 }
289
290 /**
291 * Check if the host is directly connected to the network or not.
292 *
293 * @param dhcp6Payload the dhcp6 payload
294 * @return true if the host is directly connected to the network; false otherwise
295 */
296 private boolean directlyConnected(DHCP6 dhcp6Payload) {
297 log.debug("directlyConnected enters");
298
299 if (dhcp6Payload.getMsgType() != DHCP6.MsgType.RELAY_FORW.value() &&
300 dhcp6Payload.getMsgType() != DHCP6.MsgType.RELAY_REPL.value()) {
301 log.debug("directlyConnected true. MsgType {}", dhcp6Payload.getMsgType());
302
303 return true;
304 }
305
306 // Regardless of relay-forward or relay-replay, check if we see another relay message
307 DHCP6 dhcp6Payload2 = dhcp6PacketFromRelayPacket(dhcp6Payload);
308 if (dhcp6Payload2 != null) {
309 if (dhcp6Payload.getMsgType() == DHCP6.MsgType.RELAY_FORW.value()) {
310 log.debug("directlyConnected false. 1st realy-foward, 2nd MsgType {}", dhcp6Payload2.getMsgType());
311 return false;
312 } else {
313 // relay-reply
314 if (dhcp6Payload2.getMsgType() != DHCP6.MsgType.RELAY_REPL.value()) {
315 log.debug("directlyConnected true. 2nd MsgType {}", dhcp6Payload2.getMsgType());
316 return true; // must be directly connected
317 } else {
318 log.debug("directlyConnected false. 1st relay-reply, 2nd relay-reply MsgType {}",
319 dhcp6Payload2.getMsgType());
320 return false; // must be indirectly connected
321 }
322 }
323 } else {
324 log.warn("directlyConnected true.");
325 return true;
326 }
327 }
328
329 /**
330 * extract DHCP6 payload from dhcp6 relay message within relay-forwrd/reply.
331 *
332 * @param dhcp6 dhcp6 relay-reply or relay-foward
333 * @return dhcp6Packet dhcp6 packet extracted from relay-message
334 */
335 private DHCP6 dhcp6PacketFromRelayPacket(DHCP6 dhcp6) {
336 log.debug("dhcp6PacketFromRelayPacket enters. dhcp6 {}", dhcp6);
337
338 // extract the relay message if exist
339 DHCP6 dhcp6Payload = dhcp6.getOptions().stream()
340 .filter(opt -> opt instanceof Dhcp6RelayOption)
341 .map(BasePacket::getPayload)
342 .map(pld -> (DHCP6) pld)
343 .findFirst()
344 .orElse(null);
345
346
347 if (dhcp6Payload == null) {
348 // Can't find dhcp payload
349 log.debug("Can't find dhcp6 payload from relay message");
350 } else {
351 log.debug("dhcp6 payload found from relay message {}", dhcp6Payload);
352 }
353
354 return dhcp6Payload;
355 }
356
357 /**
358 * find the leaf DHCP6 packet from multi-level relay packet.
359 *
360 * @param relayPacket dhcp6 relay packet
361 * @return leafPacket non-relay dhcp6 packet
362 */
363 private DHCP6 getDhcp6Leaf(DHCP6 relayPacket) {
364 DHCP6 dhcp6Parent = relayPacket;
365 DHCP6 dhcp6Child = null;
366
367 log.debug("getDhcp6Leaf entered.");
368 while (dhcp6Parent != null) {
369 dhcp6Child = dhcp6PacketFromRelayPacket(dhcp6Parent);
370
371 if (dhcp6Child != null) {
372 if (dhcp6Child.getMsgType() != DHCP6.MsgType.RELAY_FORW.value() &&
373 dhcp6Child.getMsgType() != DHCP6.MsgType.RELAY_REPL.value()) {
374 log.debug("leaf dhcp6 packet found.");
375 break;
376 } else {
377 // found another relay
378 // go for another loop
379 dhcp6Parent = dhcp6Child;
380 }
381 } else {
382 log.warn("malformed pkt! Expected dhcp6 within relay pkt, but no dhcp6 leaf found.");
383 break;
384 }
385 }
386 return dhcp6Child;
387 }
388
389 /**
390 * check if DHCP6 relay-reply is reply.
391 *
392 * @param relayPacket dhcp6 relay-reply
393 * @return boolean relay-reply contains ack
394 */
395 private boolean isDhcp6Reply(DHCP6 relayPacket) {
396 log.debug("isDhcp6Reply entered.");
397
398 DHCP6 leafDhcp6 = getDhcp6Leaf(relayPacket);
399
400 if (leafDhcp6 != null) {
401 if (leafDhcp6.getMsgType() == DHCP6.MsgType.REPLY.value()) {
402 log.debug("isDhcp6Reply true.");
403 return true; // must be directly connected
404 } else {
405 log.debug("isDhcp6Reply false. leaf dhcp6 is not replay. MsgType {}", leafDhcp6.getMsgType());
406 }
407 } else {
408 log.debug("isDhcp6Reply false. Expected dhcp6 within relay pkt but not found.");
409 }
410 log.debug("isDhcp6Reply false.");
411 return false;
412 }
413
414 /**
415 * check if DHCP6 is release or relay-forward contains release.
416 *
417 * @param dhcp6Payload dhcp6 packet
418 * @return boolean dhcp6 contains release
419 */
420 private boolean isDhcp6Release(DHCP6 dhcp6Payload) {
421
422 log.debug("isDhcp6Release entered.");
423
424 if (dhcp6Payload.getMsgType() == DHCP6.MsgType.RELEASE.value()) {
425 log.debug("isDhcp6Release true.");
426 return true; // must be directly connected
427 } else {
428 DHCP6 dhcp6Leaf = getDhcp6Leaf(dhcp6Payload);
429 if (dhcp6Leaf != null) {
430 if (dhcp6Leaf.getMsgType() == DHCP6.MsgType.RELEASE.value()) {
431 log.debug("isDhcp6Release true. indirectlry connected");
432 return true;
433 } else {
434 log.debug("leaf dhcp6 is not release. MsgType {}", dhcp6Leaf.getMsgType());
435 return false;
436 }
437 } else {
438 log.debug("isDhcp6Release false. dhcp6 is niether relay nor release.");
439 return false;
440 }
441 }
442 }
443
444 /**
445 * extract from dhcp6 packet client ipv6 address of given by dhcp server.
446 *
447 * @param dhcp6 the dhcp6 packet
448 * @return Ip6Address Ip6Address given by dhcp server, or null if not exists
449 */
450 private Ip6Address extractIpAddress(DHCP6 dhcp6) {
451 Ip6Address ip = null;
452
453 log.debug("extractIpAddress enters dhcp6 {}.", dhcp6);
454 // Extract IPv6 address from IA NA ot IA TA option
455 Optional<Dhcp6IaNaOption> iaNaOption = dhcp6.getOptions()
456 .stream()
457 .filter(opt -> opt instanceof Dhcp6IaNaOption)
458 .map(opt -> (Dhcp6IaNaOption) opt)
459 .findFirst();
460 Optional<Dhcp6IaTaOption> iaTaOption = dhcp6.getOptions()
461 .stream()
462 .filter(opt -> opt instanceof Dhcp6IaTaOption)
463 .map(opt -> (Dhcp6IaTaOption) opt)
464 .findFirst();
465 Optional<Dhcp6IaAddressOption> iaAddressOption;
466 if (iaNaOption.isPresent()) {
467 log.debug("Found IPv6 address from iaNaOption {}", iaNaOption);
468
469 iaAddressOption = iaNaOption.get().getOptions().stream()
470 .filter(opt -> opt instanceof Dhcp6IaAddressOption)
471 .map(opt -> (Dhcp6IaAddressOption) opt)
472 .findFirst();
473 } else if (iaTaOption.isPresent()) {
474 log.debug("Found IPv6 address from iaTaOption {}", iaTaOption);
475
476 iaAddressOption = iaTaOption.get().getOptions().stream()
477 .filter(opt -> opt instanceof Dhcp6IaAddressOption)
478 .map(opt -> (Dhcp6IaAddressOption) opt)
479 .findFirst();
480 } else {
481 iaAddressOption = Optional.empty();
482 }
483 if (iaAddressOption.isPresent()) {
484 ip = iaAddressOption.get().getIp6Address();
485 log.debug("Found IPv6 address from iaAddressOption {}", iaAddressOption);
486
487
488 } else {
489 log.debug("Can't find IPv6 address from DHCPv6 {}", dhcp6);
490 }
491
492 return ip;
493 }
494 /**
495 * extract from dhcp6 packet Prefix prefix provided by dhcp server.
496 *
497 * @param dhcp6 the dhcp6 payload
498 * @return IpPrefix Prefix Delegation prefix, or null if not exists.
499 */
500 private IpPrefix extractPrefix(DHCP6 dhcp6) {
501 log.warn("extractPrefix enters {}", dhcp6);
502
503 // extract prefix
504 IpPrefix prefixPrefix = null;
505
506 Ip6Address prefixAddress = null;
507
508 // Extract IPv6 prefix from IA PD option
509 Optional<Dhcp6IaPdOption> iaPdOption = dhcp6.getOptions()
510 .stream()
511 .filter(opt -> opt instanceof Dhcp6IaPdOption)
512 .map(opt -> (Dhcp6IaPdOption) opt)
513 .findFirst();
514
515 Optional<Dhcp6IaPrefixOption> iaPrefixOption;
516 if (iaPdOption.isPresent()) {
517 log.warn("IA_PD option found {}", iaPdOption);
518
519 iaPrefixOption = iaPdOption.get().getOptions().stream()
520 .filter(opt -> opt instanceof Dhcp6IaPrefixOption)
521 .map(opt -> (Dhcp6IaPrefixOption) opt)
522 .findFirst();
523 } else {
524 log.warn("IA_PD option NOT found");
525
526 iaPrefixOption = Optional.empty();
527 }
528 if (iaPrefixOption.isPresent()) {
529 log.warn("IAPrefix Option within IA_PD option found {}", iaPrefixOption);
530
531 prefixAddress = iaPrefixOption.get().getIp6Prefix();
532 int prefixLen = (int) iaPrefixOption.get().getPrefixLength();
533 log.warn("Prefix length is {} bits", prefixLen);
534 prefixPrefix = IpPrefix.valueOf(prefixAddress, prefixLen);
535
536 } else {
537 log.warn("Can't find IPv6 prefix from DHCPv6 {}", dhcp6);
538 }
539
540 return prefixPrefix;
541 }
542
543 /**
544 * remove host or route.
545 *
546 * @param directConnFlag flag to show that packet is from directly connected client
547 * @param dhcp6Packet the dhcp6 payload
548 * @param clientPacket client's ethernet packet
549 * @param clientIpv6 client's Ipv6 packet
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000550 * @param clientInterface client interfaces
Kalhee Kim45fede42017-09-05 19:05:06 +0000551 */
552 private void removeHostOrRoute(boolean directConnFlag, DHCP6 dhcp6Packet,
553 Ethernet clientPacket, IPv6 clientIpv6,
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000554 Interface clientInterface) {
Kalhee Kim45fede42017-09-05 19:05:06 +0000555 log.debug("extractPrefix enters {}", dhcp6Packet);
556 // add host or route
557 if (isDhcp6Release(dhcp6Packet)) {
558 IpAddress ip = null;
559 if (directConnFlag) {
560 // Add to host store if it is connected to network directly
561 ip = extractIpAddress(dhcp6Packet);
562 if (ip != null) {
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000563 VlanId vlanId = clientInterface.vlan();
Kalhee Kim45fede42017-09-05 19:05:06 +0000564 MacAddress clientMac = clientPacket.getSourceMAC();
565 HostId hostId = HostId.hostId(clientMac, vlanId);
566 log.debug("remove Host {} ip for directly connected.", hostId.toString());
567
568 log.debug("client mac {} client vlan {}", HexString.toHexString(clientMac.toBytes(), ":"), vlanId);
569
Kalhee Kim45fede42017-09-05 19:05:06 +0000570 // Remove host's ip of when dhcp release msg is received
Yi Tsengaa417a62017-09-08 17:22:51 -0700571 providerService.removeIpFromHost(hostId, ip);
Kalhee Kim45fede42017-09-05 19:05:06 +0000572 } else {
573 log.debug("ipAddress not found. Do not add Host for directly connected.");
574 }
575 } else {
576 // Remove from route store if it is not connected to network directly
577 IpAddress nextHopIp = IpAddress.valueOf(IpAddress.Version.INET6, clientIpv6.getSourceAddress());
578
579 DHCP6 leafDhcp = getDhcp6Leaf(dhcp6Packet);
580 ip = extractIpAddress(leafDhcp);
581 if (ip == null) {
582 log.debug("ip is null");
583 } else {
584 Route routeForIP = new Route(Route.Source.STATIC, ip.toIpPrefix(), nextHopIp);
585 log.debug("removing route of 128 address for indirectly connected.");
586 log.debug("128 ip {}, nexthop {}", HexString.toHexString(ip.toOctets(), ":"),
587 HexString.toHexString(nextHopIp.toOctets(), ":"));
588 routeStore.removeRoute(routeForIP);
589 }
590
591 IpPrefix ipPrefix = extractPrefix(leafDhcp);
592 if (ipPrefix == null) {
593 log.debug("ipPrefix is null ");
594 } else {
595 Route routeForPrefix = new Route(Route.Source.STATIC, ipPrefix, nextHopIp);
596 log.debug("removing route of PD for indirectly connected.");
597 log.debug("pd ip {}, nexthop {}", HexString.toHexString(ipPrefix.address().toOctets(), ":"),
598 HexString.toHexString(nextHopIp.toOctets(), ":"));
599
600 routeStore.removeRoute(routeForPrefix);
601 }
602 }
603 }
604 }
605
606 /**
607 * add host or route.
608 *
609 * @param directConnFlag flag to show that packet is from directly connected client
610 * @param dhcp6Relay the dhcp6 payload
611 * @param embeddedDhcp6 client's ethernet packetthe dhcp6 payload within relay
612 * @param clientMac client macAddress
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000613 * @param clientInterface client interface
Kalhee Kim45fede42017-09-05 19:05:06 +0000614 */
615 private void addHostOrRoute(boolean directConnFlag, DHCP6 dhcp6Relay,
616 DHCP6 embeddedDhcp6,
617 MacAddress clientMac,
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000618 Interface clientInterface) {
Kalhee Kim45fede42017-09-05 19:05:06 +0000619 log.debug("addHostOrRoute entered.");
620 // add host or route
621 if (isDhcp6Reply(dhcp6Relay)) {
622 IpAddress ip = null;
623 if (directConnFlag) {
624 // Add to host store if it connect to network directly
625 ip = extractIpAddress(embeddedDhcp6);
626 if (ip != null) {
627 Set<IpAddress> ips = Sets.newHashSet(ip);
Yi Tsengaa417a62017-09-08 17:22:51 -0700628
629 // FIXME: we should use vlan id from original packet (solicit, request)
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000630 VlanId vlanId = clientInterface.vlan();
Kalhee Kim45fede42017-09-05 19:05:06 +0000631 HostId hostId = HostId.hostId(clientMac, vlanId);
Yi Tsengaa417a62017-09-08 17:22:51 -0700632 Host host = hostService.getHost(hostId);
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000633 HostLocation hostLocation = new HostLocation(clientInterface.connectPoint(),
Yi Tsengaa417a62017-09-08 17:22:51 -0700634 System.currentTimeMillis());
635 Set<HostLocation> hostLocations = Sets.newHashSet(hostLocation);
636
637 if (host != null) {
638 // Dual homing support:
639 // if host exists, use old locations and new location
640 hostLocations.addAll(host.locations());
641 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000642 HostDescription desc = new DefaultHostDescription(clientMac, vlanId,
Yi Tsengaa417a62017-09-08 17:22:51 -0700643 hostLocations, ips,
644 false);
Kalhee Kim45fede42017-09-05 19:05:06 +0000645 log.debug("adding Host for directly connected.");
646 log.debug("client mac {} client vlan {} hostlocation {}",
647 HexString.toHexString(clientMac.toBytes(), ":"),
648 vlanId, hostLocation.toString());
649
650 // Replace the ip when dhcp server give the host new ip address
Yi Tsengaa417a62017-09-08 17:22:51 -0700651 providerService.hostDetected(hostId, desc, false);
Kalhee Kim45fede42017-09-05 19:05:06 +0000652 } else {
653 log.warn("ipAddress not found. Do not add Host for directly connected.");
654 }
655 } else {
656 // Add to route store if it does not connect to network directly
657 IpAddress nextHopIp = IpAddress.valueOf(IpAddress.Version.INET6, dhcp6Relay.getPeerAddress());
658
659 DHCP6 leafDhcp = getDhcp6Leaf(embeddedDhcp6);
660 ip = extractIpAddress(leafDhcp);
661 if (ip == null) {
662 log.warn("ip is null");
663 } else {
664 Route routeForIP = new Route(Route.Source.STATIC, ip.toIpPrefix(), nextHopIp);
665 log.warn("adding Route of 128 address for indirectly connected.");
666 routeStore.updateRoute(routeForIP);
667 }
668
669 IpPrefix ipPrefix = extractPrefix(leafDhcp);
670 if (ipPrefix == null) {
671 log.warn("ipPrefix is null ");
672 } else {
673 Route routeForPrefix = new Route(Route.Source.STATIC, ipPrefix, nextHopIp);
674 log.warn("adding Route of PD for indirectly connected.");
675 routeStore.updateRoute(routeForPrefix);
676 }
677 }
678 }
679 }
680
681 /**
682 *
683 * build the DHCP6 solicit/request packet with gatewayip.
684 *
685 * @param context packet context
686 * @param clientPacket client ethernet packet
687 * @param clientInterfaces set of client side interfaces
688 */
689 private InternalPacket processDhcp6PacketFromClient(PacketContext context,
690 Ethernet clientPacket, Set<Interface> clientInterfaces) {
Kalhee Kim45b24182017-10-18 18:30:23 +0000691 Ip6Address relayAgentIp = getRelayAgentIPv6Address(clientInterfaces);
692 MacAddress relayAgentMac = clientInterfaces.iterator().next().mac();
693 if (relayAgentIp == null || relayAgentMac == null) {
694 log.warn("Missing DHCP relay agent interface Ipv6 addr config for "
695 + "packet from client on port: {}. Aborting packet processing",
696 clientInterfaces.iterator().next().connectPoint());
697 return null;
698 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000699
Kalhee Kim45b24182017-10-18 18:30:23 +0000700 // get dhcp6 header.
Kalhee Kim45fede42017-09-05 19:05:06 +0000701
Kalhee Kim45b24182017-10-18 18:30:23 +0000702 IPv6 clientIpv6 = (IPv6) clientPacket.getPayload();
703 UDP clientUdp = (UDP) clientIpv6.getPayload();
704 DHCP6 clientDhcp6 = (DHCP6) clientUdp.getPayload();
Kalhee Kim45fede42017-09-05 19:05:06 +0000705
Kalhee Kim45b24182017-10-18 18:30:23 +0000706 boolean directConnFlag = directlyConnected(clientDhcp6);
707 Interface serverInterface = directConnFlag ? getServerInterface() : getIndirectServerInterface();
708 if (serverInterface == null) {
709 log.warn("Can't get {} server interface, ignore", directConnFlag ? "direct" : "indirect");
710 return null;
711 }
712 Ip6Address ipFacingServer = getFirstIpFromInterface(serverInterface);
713 MacAddress macFacingServer = serverInterface.mac();
714 if (ipFacingServer == null || macFacingServer == null) {
715 log.warn("No IP v6 address for server Interface {}", serverInterface);
716 return null;
717 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000718
Kalhee Kim45b24182017-10-18 18:30:23 +0000719 Ethernet etherReply = clientPacket.duplicate();
720 etherReply.setSourceMACAddress(macFacingServer);
Kalhee Kim45fede42017-09-05 19:05:06 +0000721
Kalhee Kim45b24182017-10-18 18:30:23 +0000722 if ((directConnFlag && this.dhcpConnectMac == null) ||
723 !directConnFlag && this.indirectDhcpConnectMac == null && this.dhcpConnectMac == null) {
724 log.warn("Packet received from {} connected client.", directConnFlag ? "directly" : "indirectly");
725 log.warn("DHCP6 {} not yet resolved .. Aborting DHCP "
726 + "packet processing from client on port: {}",
727 (this.dhcpGatewayIp == null) ? "server IP " + this.dhcpServerIp
728 : "gateway IP " + this.dhcpGatewayIp,
729 clientInterfaces.iterator().next().connectPoint());
Kalhee Kim45fede42017-09-05 19:05:06 +0000730
Kalhee Kim45b24182017-10-18 18:30:23 +0000731 return null;
732 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000733
Kalhee Kim45b24182017-10-18 18:30:23 +0000734 if (this.dhcpServerConnectPoint == null) {
735 log.warn("DHCP6 server connection point direct {} directConn {} indirectConn {} is not set up yet",
736 directConnFlag, this.dhcpServerConnectPoint, this.indirectDhcpServerConnectPoint);
737 return null;
738 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000739
Kalhee Kim45b24182017-10-18 18:30:23 +0000740 etherReply.setDestinationMACAddress(this.dhcpConnectMac);
741 etherReply.setVlanID(this.dhcpConnectVlan.toShort());
Kalhee Kim45fede42017-09-05 19:05:06 +0000742
Kalhee Kim45b24182017-10-18 18:30:23 +0000743 IPv6 ipv6Packet = (IPv6) etherReply.getPayload();
744 byte[] peerAddress = clientIpv6.getSourceAddress();
745 ipv6Packet.setSourceAddress(ipFacingServer.toOctets());
Kalhee Kim45fede42017-09-05 19:05:06 +0000746
Kalhee Kim45b24182017-10-18 18:30:23 +0000747 ipv6Packet.setDestinationAddress(this.dhcpServerIp.toOctets());
Kalhee Kim45fede42017-09-05 19:05:06 +0000748
Kalhee Kim45b24182017-10-18 18:30:23 +0000749 UDP udpPacket = (UDP) ipv6Packet.getPayload();
750 udpPacket.setSourcePort(UDP.DHCP_V6_SERVER_PORT);
751 DHCP6 dhcp6Packet = (DHCP6) udpPacket.getPayload();
752 byte[] dhcp6PacketByte = dhcp6Packet.serialize();
753
754 // notify onos and quagga to release PD
755 //releasePD(dhcp6Packet);
756 ConnectPoint clientConnectionPoint = context.inPacket().receivedFrom();
757 VlanId vlanIdInUse = VlanId.vlanId(clientPacket.getVlanID());
758 Interface clientInterface = interfaceService.getInterfacesByPort(clientConnectionPoint)
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000759 .stream()
760 .filter(iface -> interfaceContainsVlan(iface, vlanIdInUse))
761 .findFirst()
762 .orElse(null);
Kalhee Kim45fede42017-09-05 19:05:06 +0000763
Kalhee Kim45b24182017-10-18 18:30:23 +0000764 removeHostOrRoute(directConnFlag, dhcp6Packet, clientPacket, clientIpv6, clientInterface);
Kalhee Kim45fede42017-09-05 19:05:06 +0000765
Kalhee Kim45b24182017-10-18 18:30:23 +0000766 DHCP6 dhcp6Relay = new DHCP6();
767 dhcp6Relay.setMsgType(DHCP6.MsgType.RELAY_FORW.value());
768 // link address: server uses the address to identify the link on which the client
769 // is located.
Kalhee Kim45fede42017-09-05 19:05:06 +0000770 if (directConnFlag) {
771 dhcp6Relay.setLinkAddress(relayAgentIp.toOctets());
772 log.debug("direct connection: relayAgentIp obtained dynamically {}",
773 HexString.toHexString(relayAgentIp.toOctets(), ":"));
774
775 } else {
Kalhee Kimd21029f2017-09-26 20:21:53 +0000776 if (this.indirectDhcpServerIp == null) {
777 log.warn("indirect DhcpServerIp not available, use default DhcpServerIp {}",
778 HexString.toHexString(this.dhcpServerIp.toOctets()));
779 } else {
780 // Indirect case, replace destination to indirect dhcp server if exist
781 // Check if mac is obtained for valid server ip
782 if (this.indirectDhcpConnectMac == null) {
783 log.warn("DHCP6 {} not yet resolved .. Aborting DHCP "
784 + "packet processing from client on port: {}",
785 (this.indirectDhcpGatewayIp == null) ? "server IP " + this.indirectDhcpServerIp
786 : "gateway IP " + this.indirectDhcpGatewayIp,
787 clientInterfaces.iterator().next().connectPoint());
788 return null;
789 }
790 etherReply.setDestinationMACAddress(this.indirectDhcpConnectMac);
791 etherReply.setVlanID(this.indirectDhcpConnectVlan.toShort());
792 ipv6Packet.setDestinationAddress(this.indirectDhcpServerIp.toOctets());
793
794 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000795 if (this.indirectRelayAgentIpFromCfg == null) {
796 dhcp6Relay.setLinkAddress(relayAgentIp.toOctets());
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000797 log.warn("indirect connection: relayAgentIp NOT availale from config file! Use dynamic. {}",
Kalhee Kim45fede42017-09-05 19:05:06 +0000798 HexString.toHexString(relayAgentIp.toOctets(), ":"));
799
800 } else {
801 dhcp6Relay.setLinkAddress(this.indirectRelayAgentIpFromCfg.toOctets());
802 log.debug("indirect connection: relayAgentIp from config file is available! {}",
803 HexString.toHexString(this.indirectRelayAgentIpFromCfg.toOctets(), ":"));
804 }
805 }
806
Kalhee Kim45b24182017-10-18 18:30:23 +0000807 // peer address: address of the client or relay agent from which
808 // the message to be relayed was received.
809 dhcp6Relay.setPeerAddress(peerAddress);
810 List<Dhcp6Option> options = new ArrayList<Dhcp6Option>();
Kalhee Kim45fede42017-09-05 19:05:06 +0000811
Kalhee Kim45b24182017-10-18 18:30:23 +0000812 // directly connected case, hop count is zero
813 // otherwise, hop count + 1
814 if (directConnFlag) {
815 dhcp6Relay.setHopCount((byte) 0);
816 } else {
817 dhcp6Relay.setHopCount((byte) (dhcp6Packet.getHopCount() + 1));
818 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000819
Kalhee Kim45b24182017-10-18 18:30:23 +0000820 // create relay message option
821 Dhcp6Option relayMessage = new Dhcp6Option();
822 relayMessage.setCode(DHCP6.OptionCode.RELAY_MSG.value());
823 relayMessage.setLength((short) dhcp6PacketByte.length);
824 relayMessage.setData(dhcp6PacketByte);
825 options.add(relayMessage);
Kalhee Kim45fede42017-09-05 19:05:06 +0000826
Kalhee Kim45b24182017-10-18 18:30:23 +0000827 // create interfaceId option
828 String inPortString = "-" + context.inPacket().receivedFrom().toString() + ":";
829 Dhcp6Option interfaceId = new Dhcp6Option();
830 interfaceId.setCode(DHCP6.OptionCode.INTERFACE_ID.value());
831 byte[] clientSoureMacBytes = clientPacket.getSourceMACAddress();
832 byte[] inPortStringBytes = inPortString.getBytes();
833 byte[] vlanIdBytes = new byte[2];
834 vlanIdBytes[0] = (byte) (clientPacket.getVlanID() & 0xff);
835 vlanIdBytes[1] = (byte) ((clientPacket.getVlanID() >> 8) & 0xff);
836 byte[] interfaceIdBytes = new byte[clientSoureMacBytes.length +
837 inPortStringBytes.length + vlanIdBytes.length];
838 log.debug("Length: interfaceIdBytes {} clientSoureMacBytes {} inPortStringBytes {} vlan {}",
839 interfaceIdBytes.length, clientSoureMacBytes.length, inPortStringBytes.length,
840 vlanIdBytes.length);
Kalhee Kim45fede42017-09-05 19:05:06 +0000841
Kalhee Kim45b24182017-10-18 18:30:23 +0000842 System.arraycopy(clientSoureMacBytes, 0, interfaceIdBytes, 0, clientSoureMacBytes.length);
843 System.arraycopy(inPortStringBytes, 0, interfaceIdBytes, clientSoureMacBytes.length, inPortStringBytes.length);
844 System.arraycopy(vlanIdBytes, 0, interfaceIdBytes, clientSoureMacBytes.length + inPortStringBytes.length,
845 vlanIdBytes.length);
Kalhee Kim45fede42017-09-05 19:05:06 +0000846
Kalhee Kim45b24182017-10-18 18:30:23 +0000847 interfaceId.setData(interfaceIdBytes);
848 interfaceId.setLength((short) interfaceIdBytes.length);
Kalhee Kim45fede42017-09-05 19:05:06 +0000849
Kalhee Kim45b24182017-10-18 18:30:23 +0000850 options.add(interfaceId);
Kalhee Kim45fede42017-09-05 19:05:06 +0000851
Kalhee Kim45b24182017-10-18 18:30:23 +0000852 log.debug("interfaceId write srcMac {} portString {}",
853 HexString.toHexString(clientSoureMacBytes, ":"), inPortString);
854 dhcp6Relay.setOptions(options);
855 udpPacket.setPayload(dhcp6Relay);
856 udpPacket.resetChecksum();
857 ipv6Packet.setPayload(udpPacket);
858 ipv6Packet.setHopLimit((byte) 64);
859 etherReply.setPayload(ipv6Packet);
Kalhee Kim45fede42017-09-05 19:05:06 +0000860
Kalhee Kim45b24182017-10-18 18:30:23 +0000861 if (directConnFlag) {
862 return new InternalPacket(etherReply, this.dhcpServerConnectPoint);
863 } else {
864 if (this.indirectDhcpServerIp == null) {
865 return new InternalPacket(etherReply, this.dhcpServerConnectPoint);
866 } else {
867 return new InternalPacket(etherReply, this.indirectDhcpServerConnectPoint);
868 }
869 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000870 }
871
872 /**
873 *
874 * process the DHCP6 relay-reply packet from dhcp server.
875 *
876 * @param context packet context
877 * @param receivedPacket server ethernet packet
878 * @param recevingInterfaces set of server side interfaces
879 */
880 private InternalPacket processDhcp6PacketFromServer(PacketContext context,
881 Ethernet receivedPacket, Set<Interface> recevingInterfaces) {
Kalhee Kim45fede42017-09-05 19:05:06 +0000882 // get dhcp6 header.
Ray Milkeyf0c47612017-09-28 11:29:38 -0700883 Ethernet etherReply = receivedPacket.duplicate();
Kalhee Kim45fede42017-09-05 19:05:06 +0000884 IPv6 ipv6Packet = (IPv6) etherReply.getPayload();
885 UDP udpPacket = (UDP) ipv6Packet.getPayload();
886 DHCP6 dhcp6Relay = (DHCP6) udpPacket.getPayload();
887
888 Boolean directConnFlag = directlyConnected(dhcp6Relay);
Kalhee Kimd21029f2017-09-26 20:21:53 +0000889 ConnectPoint inPort = context.inPacket().receivedFrom();
890 if ((directConnFlag || (!directConnFlag && this.indirectDhcpServerIp == null))
891 && !inPort.equals(this.dhcpServerConnectPoint)) {
892 log.warn("Receiving port {} is not the same as server connect point {} for direct or indirect-null",
893 inPort, this.dhcpServerConnectPoint);
894 return null;
895 }
896
897 if (!directConnFlag && this.indirectDhcpServerIp != null &&
898 !inPort.equals(this.indirectDhcpServerConnectPoint)) {
899 log.warn("Receiving port {} is not the same as server connect point {} for indirect",
900 inPort, this.indirectDhcpServerConnectPoint);
901 return null;
902 }
903
Kalhee Kim45fede42017-09-05 19:05:06 +0000904
905 Dhcp6InterfaceIdOption interfaceIdOption = dhcp6Relay.getOptions().stream()
906 .filter(opt -> opt instanceof Dhcp6InterfaceIdOption)
907 .map(opt -> (Dhcp6InterfaceIdOption) opt)
908 .findFirst()
909 .orElse(null);
910
911 if (interfaceIdOption == null) {
912 log.warn("Interface Id option is not present, abort packet...");
913 return null;
914 }
915
916 MacAddress peerMac = interfaceIdOption.getMacAddress();
917 String clientConnectionPointStr = new String(interfaceIdOption.getInPort());
918
919 ConnectPoint clientConnectionPoint = ConnectPoint.deviceConnectPoint(clientConnectionPointStr);
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000920 VlanId vlanIdInUse = VlanId.vlanId(interfaceIdOption.getVlanId());
921 Interface clientInterface = interfaceService.getInterfacesByPort(clientConnectionPoint)
922 .stream()
923 .filter(iface -> interfaceContainsVlan(iface, vlanIdInUse))
924 .findFirst()
925 .orElse(null);
926 if (clientInterface == null) {
927 log.warn("Cannot get client interface for from packet, abort... vlan {}", vlanIdInUse.toString());
Kalhee Kim45fede42017-09-05 19:05:06 +0000928 return null;
929 }
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000930 MacAddress relayAgentMac = clientInterface.mac();
Kalhee Kim45fede42017-09-05 19:05:06 +0000931 if (relayAgentMac == null) {
932 log.warn("Can not get interface mac, abort packet..");
933 return null;
934 }
935 etherReply.setSourceMACAddress(relayAgentMac);
936
937 // find destMac
938 MacAddress clientMac = null;
Yi Tsengaa417a62017-09-08 17:22:51 -0700939 Ip6Address peerAddress = Ip6Address.valueOf(dhcp6Relay.getPeerAddress());
940 Set<Host> clients = hostService.getHostsByIp(peerAddress);
Kalhee Kim45fede42017-09-05 19:05:06 +0000941 if (clients.isEmpty()) {
942 log.warn("There's no host found for this address {}",
943 HexString.toHexString(dhcp6Relay.getPeerAddress(), ":"));
944 log.warn("Let's look up interfaceId {}", HexString.toHexString(peerMac.toBytes(), ":"));
945 clientMac = peerMac;
946 } else {
947 clientMac = clients.iterator().next().mac();
948 if (clientMac == null) {
949 log.warn("No client mac address found, abort packet...");
950 return null;
951 }
952 log.warn("Client mac address found from getHostByIp");
953
954 }
955 etherReply.setDestinationMACAddress(clientMac);
956
957 // ip header
958 ipv6Packet.setSourceAddress(dhcp6Relay.getLinkAddress());
959 ipv6Packet.setDestinationAddress(dhcp6Relay.getPeerAddress());
960 // udp header
961 udpPacket.setSourcePort(UDP.DHCP_V6_SERVER_PORT);
962 if (directConnFlag) {
963 udpPacket.setDestinationPort(UDP.DHCP_V6_CLIENT_PORT);
964 } else {
965 udpPacket.setDestinationPort(UDP.DHCP_V6_SERVER_PORT);
966 }
967
968 DHCP6 embeddedDhcp6 = dhcp6Relay.getOptions().stream()
969 .filter(opt -> opt instanceof Dhcp6RelayOption)
970 .map(BasePacket::getPayload)
971 .map(pld -> (DHCP6) pld)
972 .findFirst()
973 .orElse(null);
974
975
976 // add host or route
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000977 addHostOrRoute(directConnFlag, dhcp6Relay, embeddedDhcp6, clientMac, clientInterface);
Kalhee Kim45fede42017-09-05 19:05:06 +0000978
979 udpPacket.setPayload(embeddedDhcp6);
980 udpPacket.resetChecksum();
981 ipv6Packet.setPayload(udpPacket);
982 etherReply.setPayload(ipv6Packet);
983
984 return new InternalPacket(etherReply, clientConnectionPoint);
985 }
986
Yi Tseng919b2df2017-09-07 16:22:51 -0700987 // Returns the first v6 interface ip out of a set of interfaces or null.
Kalhee Kim45fede42017-09-05 19:05:06 +0000988 // Checks all interfaces, and ignores v6 interface ips
989 private Ip6Address getRelayAgentIPv6Address(Set<Interface> intfs) {
990 for (Interface intf : intfs) {
991 for (InterfaceIpAddress ip : intf.ipAddressesList()) {
992 Ip6Address relayAgentIp = ip.ipAddress().getIp6Address();
993 if (relayAgentIp != null) {
994 return relayAgentIp;
995 }
996 }
997 }
998 return null;
Yi Tseng51301292017-07-28 13:02:59 -0700999 }
Yi Tseng483ac6f2017-08-02 15:03:31 -07001000
1001 @Override
1002 public void setDefaultDhcpServerConfigs(Collection<DhcpServerConfig> configs) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001003 setDhcpServerConfigs(configs, defaultServerInfoList);
1004 reloadServerSettings();
1005 }
1006
1007 @Override
1008 public void setIndirectDhcpServerConfigs(Collection<DhcpServerConfig> configs) {
1009 setDhcpServerConfigs(configs, indirectServerInfoList);
1010 reloadServerSettings();
1011 }
1012
1013 public void setDhcpServerConfigs(Collection<DhcpServerConfig> configs, List<DhcpServerInfo> serverInfoList) {
Kalhee Kim45fede42017-09-05 19:05:06 +00001014 if (configs.size() == 0) {
1015 // no config to update
1016 return;
1017 }
1018
1019 // TODO: currently we pick up first DHCP server config.
1020 // Will use other server configs in the future for HA.
1021 DhcpServerConfig serverConfig = configs.iterator().next();
Yi Tseng919b2df2017-09-07 16:22:51 -07001022
Kalhee Kim45fede42017-09-05 19:05:06 +00001023 if (!serverConfig.getDhcpServerIp6().isPresent()) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001024 // not a DHCPv6 config
Kalhee Kim45fede42017-09-05 19:05:06 +00001025 return;
1026 }
1027
Yi Tseng919b2df2017-09-07 16:22:51 -07001028 if (!serverInfoList.isEmpty()) {
1029 // remove old server info
1030 DhcpServerInfo oldServerInfo = serverInfoList.remove(0);
1031
1032 // stop monitoring gateway or server
1033 oldServerInfo.getDhcpGatewayIp6().ifPresent(gatewayIp -> {
1034 hostService.stopMonitoringIp(gatewayIp);
1035 });
1036 oldServerInfo.getDhcpServerIp6().ifPresent(serverIp -> {
1037 hostService.stopMonitoringIp(serverIp);
1038 });
1039 }
1040
1041 // Create new server info according to the config
1042 DhcpServerInfo newServerInfo = new DhcpServerInfo(serverConfig,
1043 DhcpServerInfo.Version.DHCP_V6);
1044 checkState(newServerInfo.getDhcpServerConnectPoint().isPresent(),
1045 "Connect point not exists");
1046 checkState(newServerInfo.getDhcpServerIp6().isPresent(),
1047 "IP of DHCP server not exists");
1048
1049 log.debug("DHCP server connect point: {}", newServerInfo.getDhcpServerConnectPoint().orElse(null));
1050 log.debug("DHCP server IP: {}", newServerInfo.getDhcpServerIp6().orElse(null));
1051
1052 IpAddress ipToProbe;
1053 if (newServerInfo.getDhcpGatewayIp6().isPresent()) {
1054 ipToProbe = newServerInfo.getDhcpGatewayIp6().get();
1055 } else {
1056 ipToProbe = newServerInfo.getDhcpServerIp6().orElse(null);
1057 }
1058 String hostToProbe = newServerInfo.getDhcpGatewayIp6()
1059 .map(ip -> "gateway").orElse("server");
1060
1061 log.debug("Probing to resolve {} IP {}", hostToProbe, ipToProbe);
Kalhee Kim45fede42017-09-05 19:05:06 +00001062 hostService.startMonitoringIp(ipToProbe);
1063
1064 Set<Host> hosts = hostService.getHostsByIp(ipToProbe);
1065 if (!hosts.isEmpty()) {
1066 Host host = hosts.iterator().next();
Yi Tseng919b2df2017-09-07 16:22:51 -07001067 newServerInfo.setDhcpConnectVlan(host.vlan());
1068 newServerInfo.setDhcpConnectMac(host.mac());
Kalhee Kim45fede42017-09-05 19:05:06 +00001069 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001070 // Add new server info
1071 serverInfoList.add(0, newServerInfo);
Yi Tseng483ac6f2017-08-02 15:03:31 -07001072
Yi Tseng919b2df2017-09-07 16:22:51 -07001073 // Remove duplicated server info
1074 Set<DhcpServerInfo> nonDupServerInfoList = Sets.newLinkedHashSet();
1075 nonDupServerInfoList.addAll(serverInfoList);
1076 serverInfoList.clear();
1077 serverInfoList.addAll(nonDupServerInfoList);
Kalhee Kim45fede42017-09-05 19:05:06 +00001078 }
1079
1080 class InternalHostListener implements HostListener {
1081 @Override
1082 public void event(HostEvent event) {
1083 switch (event.type()) {
1084 case HOST_ADDED:
1085 case HOST_UPDATED:
1086 hostUpdated(event.subject());
1087 break;
1088 case HOST_REMOVED:
1089 hostRemoved(event.subject());
1090 break;
1091 case HOST_MOVED:
1092 hostMoved(event.subject());
1093 break;
1094 default:
1095 break;
1096 }
1097 }
1098 }
1099
1100 /**
1101 * Handle host move.
1102 * If the host DHCP server or gateway and it moved to the location different
1103 * to user configured, unsets the connect mac and vlan
1104 *
1105 * @param host the host
1106 */
1107 private void hostMoved(Host host) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001108 Set<ConnectPoint> hostConnectPoints = host.locations().stream()
1109 .map(hl -> new ConnectPoint(hl.elementId(), hl.port()))
1110 .collect(Collectors.toSet());
1111 DhcpServerInfo serverInfo;
1112 ConnectPoint dhcpServerConnectPoint;
1113 Ip6Address dhcpGatewayIp;
1114 Ip6Address dhcpServerIp;
1115
1116 if (!defaultServerInfoList.isEmpty()) {
1117 serverInfo = defaultServerInfoList.get(0);
1118 dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1119 dhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1120 dhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
1121 if (dhcpServerConnectPoint == null) {
1122 return;
1123 }
1124 if (dhcpGatewayIp != null) {
1125 if (host.ipAddresses().contains(dhcpGatewayIp) &&
1126 !hostConnectPoints.contains(dhcpServerConnectPoint)) {
1127 serverInfo.setDhcpConnectVlan(null);
1128 serverInfo.setDhcpConnectMac(null);
1129 }
1130 }
1131 if (dhcpServerIp != null) {
1132 if (host.ipAddresses().contains(dhcpServerIp) &&
1133 !hostConnectPoints.contains(dhcpServerConnectPoint)) {
1134 serverInfo.setDhcpConnectVlan(null);
1135 serverInfo.setDhcpConnectMac(null);
1136 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001137 }
1138 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001139
1140 if (!indirectServerInfoList.isEmpty()) {
1141 serverInfo = indirectServerInfoList.get(0);
1142 dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1143 dhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1144 dhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
1145 if (dhcpServerConnectPoint == null) {
1146 return;
1147 }
1148 if (dhcpGatewayIp != null) {
1149 if (host.ipAddresses().contains(dhcpGatewayIp) &&
1150 !hostConnectPoints.contains(dhcpServerConnectPoint)) {
1151 serverInfo.setDhcpConnectVlan(null);
1152 serverInfo.setDhcpConnectMac(null);
1153 }
1154 }
1155 if (dhcpServerIp != null) {
1156 if (host.ipAddresses().contains(dhcpServerIp) &&
1157 !hostConnectPoints.contains(dhcpServerConnectPoint)) {
1158 serverInfo.setDhcpConnectVlan(null);
1159 serverInfo.setDhcpConnectMac(null);
1160 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001161 }
1162 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001163 reloadServerSettings();
Kalhee Kim45fede42017-09-05 19:05:06 +00001164 }
1165
1166 /**
1167 * Handle host updated.
1168 * If the host is DHCP server or gateway, update connect mac and vlan.
1169 *
1170 * @param host the host
1171 */
1172 private void hostUpdated(Host host) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001173 DhcpServerInfo serverInfo;
1174 Ip6Address dhcpGatewayIp;
1175 Ip6Address dhcpServerIp;
1176 if (!defaultServerInfoList.isEmpty()) {
1177 serverInfo = defaultServerInfoList.get(0);
1178 dhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1179 dhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
1180 if (dhcpGatewayIp != null) {
1181 if (host.ipAddresses().contains(dhcpGatewayIp)) {
1182 serverInfo.setDhcpConnectMac(host.mac());
1183 serverInfo.setDhcpConnectVlan(host.vlan());
1184 }
1185 }
1186 if (dhcpServerIp != null) {
1187 if (host.ipAddresses().contains(dhcpServerIp)) {
1188 serverInfo.setDhcpConnectMac(host.mac());
1189 serverInfo.setDhcpConnectVlan(host.vlan());
1190 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001191 }
1192 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001193
1194 if (!indirectServerInfoList.isEmpty()) {
1195 serverInfo = indirectServerInfoList.get(0);
1196 dhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1197 dhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
1198 if (dhcpGatewayIp != null) {
1199 if (host.ipAddresses().contains(dhcpGatewayIp)) {
1200 serverInfo.setDhcpConnectMac(host.mac());
1201 serverInfo.setDhcpConnectVlan(host.vlan());
1202 }
1203 }
1204 if (dhcpServerIp != null) {
1205 if (host.ipAddresses().contains(dhcpServerIp)) {
1206 serverInfo.setDhcpConnectMac(host.mac());
1207 serverInfo.setDhcpConnectVlan(host.vlan());
1208 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001209 }
1210 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001211 reloadServerSettings();
Kalhee Kim45fede42017-09-05 19:05:06 +00001212 }
1213
1214 /**
1215 * Handle host removed.
1216 * If the host is DHCP server or gateway, unset connect mac and vlan.
1217 *
1218 * @param host the host
1219 */
1220 private void hostRemoved(Host host) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001221 DhcpServerInfo serverInfo;
1222 Ip6Address dhcpGatewayIp;
1223 Ip6Address dhcpServerIp;
1224
1225 if (!defaultServerInfoList.isEmpty()) {
1226 serverInfo = defaultServerInfoList.get(0);
1227 dhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1228 dhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
1229
1230 if (dhcpGatewayIp != null) {
1231 if (host.ipAddresses().contains(dhcpGatewayIp)) {
1232 serverInfo.setDhcpConnectVlan(null);
1233 serverInfo.setDhcpConnectMac(null);
1234 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001235 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001236 if (dhcpServerIp != null) {
1237 if (host.ipAddresses().contains(dhcpServerIp)) {
1238 serverInfo.setDhcpConnectVlan(null);
1239 serverInfo.setDhcpConnectMac(null);
1240 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001241 }
1242 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001243
1244 if (!indirectServerInfoList.isEmpty()) {
1245 serverInfo = indirectServerInfoList.get(0);
1246 dhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1247 dhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
1248
1249 if (dhcpGatewayIp != null) {
1250 if (host.ipAddresses().contains(dhcpGatewayIp)) {
1251 serverInfo.setDhcpConnectVlan(null);
1252 serverInfo.setDhcpConnectMac(null);
1253 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001254 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001255 if (dhcpServerIp != null) {
1256 if (host.ipAddresses().contains(dhcpServerIp)) {
1257 serverInfo.setDhcpConnectVlan(null);
1258 serverInfo.setDhcpConnectMac(null);
1259 }
1260 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001261 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001262 reloadServerSettings();
1263 }
1264
1265 private void reloadServerSettings() {
1266 DhcpServerInfo serverInfo;
1267 if (!defaultServerInfoList.isEmpty()) {
1268 serverInfo = defaultServerInfoList.get(0);
1269 this.dhcpConnectMac = serverInfo.getDhcpConnectMac().orElse(null);
1270 this.dhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1271 this.dhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
1272 this.dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1273 this.dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1274 }
1275
1276 if (!indirectServerInfoList.isEmpty()) {
1277 serverInfo = indirectServerInfoList.get(0);
1278 this.indirectDhcpConnectMac = serverInfo.getDhcpConnectMac().orElse(null);
1279 this.indirectDhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1280 this.indirectDhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
1281 this.indirectDhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1282 this.indirectDhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1283 this.indirectRelayAgentIpFromCfg = serverInfo.getRelayAgentIp6().orElse(null);
Kalhee Kim45fede42017-09-05 19:05:06 +00001284 }
Yi Tseng483ac6f2017-08-02 15:03:31 -07001285 }
Kalhee Kim45b24182017-10-18 18:30:23 +00001286
1287 /**
1288 * Returns the first interface ip from interface.
1289 *
1290 * @param iface interface of one connect point
1291 * @return the first interface IP; null if not exists an IP address in
1292 * these interfaces
1293 */
1294 private Ip6Address getFirstIpFromInterface(Interface iface) {
1295 checkNotNull(iface, "Interface can't be null");
1296 return iface.ipAddressesList().stream()
1297 .map(InterfaceIpAddress::ipAddress)
1298 .filter(IpAddress::isIp6)
1299 .map(IpAddress::getIp6Address)
1300 .findFirst()
1301 .orElse(null);
1302 }
1303
1304 /**
1305 * Gets Interface facing to the server for default host.
1306 *
1307 * @return the Interface facing to the server; null if not found
1308 */
1309 private Interface getServerInterface() {
1310 if (dhcpServerConnectPoint == null || dhcpConnectVlan == null) {
1311 return null;
1312 }
1313 return interfaceService.getInterfacesByPort(dhcpServerConnectPoint)
1314 .stream()
1315 .filter(iface -> interfaceContainsVlan(iface, dhcpConnectVlan))
1316 .findFirst()
1317 .orElse(null);
1318 }
1319
1320 /**
1321 * Gets Interface facing to the server for indirect hosts.
1322 * Use default server Interface if indirect server not configured.
1323 *
1324 * @return the Interface facing to the server; null if not found
1325 */
1326 private Interface getIndirectServerInterface() {
1327 if (indirectDhcpServerConnectPoint == null || indirectDhcpConnectVlan == null) {
1328 return getServerInterface();
1329 }
1330 return interfaceService.getInterfacesByPort(indirectDhcpServerConnectPoint)
1331 .stream()
1332 .filter(iface -> interfaceContainsVlan(iface, indirectDhcpConnectVlan))
1333 .findFirst()
1334 .orElse(null);
1335 }
1336
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +00001337 /**
1338 * Determind if an Interface contains a vlan id.
1339 *
1340 * @param iface the Interface
1341 * @param vlanId the vlan id
1342 * @return true if the Interface contains the vlan id
1343 */
1344 private boolean interfaceContainsVlan(Interface iface, VlanId vlanId) {
1345 if (vlanId.equals(VlanId.NONE)) {
1346 // untagged packet, check if vlan untagged or vlan native is not NONE
1347 return !iface.vlanUntagged().equals(VlanId.NONE) ||
1348 !iface.vlanNative().equals(VlanId.NONE);
1349 }
1350 // tagged packet, check if the interface contains the vlan
1351 return iface.vlanTagged().contains(vlanId);
1352 }
1353
Yi Tseng51301292017-07-28 13:02:59 -07001354}