blob: d72f4fc4f195610191ef39b61ab6adb08edd68b2 [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();
Charles Chana990ce92017-10-30 10:22:50 -0700744 Ip6Address peerAddress = null;
745 if (directConnFlag) {
746 peerAddress = Ip6Address.valueOf(ipv6Packet.getSourceAddress());
Kalhee Kim45fede42017-09-05 19:05:06 +0000747
Charles Chana990ce92017-10-30 10:22:50 -0700748 } else {
749 MacAddress gwOrClientMac = MacAddress.valueOf(clientPacket.getSourceMACAddress());
750 VlanId vlanId = VlanId.vlanId(clientPacket.getVlanID());
751 HostId gwOrClientHostId = HostId.hostId(gwOrClientMac, vlanId);
752 Host gwOrClientHost = hostService.getHost(gwOrClientHostId);
753
754 if (gwOrClientHost == null) {
755 log.warn("Can't find client gateway/server host {}", gwOrClientHostId);
756 return null;
757 }
758 // pick out the first gloabl ip address
759 peerAddress = gwOrClientHost.ipAddresses()
760 .stream()
761 .filter(IpAddress::isIp6)
762 .filter(ip6 -> !ip6.isLinkLocal())
763 .map(IpAddress::getIp6Address)
764 .findFirst()
765 .orElse(null);
766
767 if (peerAddress == null) {
768 log.warn("Can't find client gateway/server for mac {} ip {}", gwOrClientMac,
769 HexString.toHexString(ipv6Packet.getSourceAddress()));
770 log.warn("Can't find IP address of client gateway/ClienHost address {} for peerAddress", gwOrClientHost);
771 return null;
772 }
773 }
774 ipv6Packet.setSourceAddress(ipFacingServer.toOctets());
Kalhee Kim45b24182017-10-18 18:30:23 +0000775 ipv6Packet.setDestinationAddress(this.dhcpServerIp.toOctets());
Kalhee Kim45fede42017-09-05 19:05:06 +0000776
Kalhee Kim45b24182017-10-18 18:30:23 +0000777 UDP udpPacket = (UDP) ipv6Packet.getPayload();
778 udpPacket.setSourcePort(UDP.DHCP_V6_SERVER_PORT);
779 DHCP6 dhcp6Packet = (DHCP6) udpPacket.getPayload();
780 byte[] dhcp6PacketByte = dhcp6Packet.serialize();
781
782 // notify onos and quagga to release PD
783 //releasePD(dhcp6Packet);
784 ConnectPoint clientConnectionPoint = context.inPacket().receivedFrom();
785 VlanId vlanIdInUse = VlanId.vlanId(clientPacket.getVlanID());
786 Interface clientInterface = interfaceService.getInterfacesByPort(clientConnectionPoint)
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000787 .stream()
788 .filter(iface -> interfaceContainsVlan(iface, vlanIdInUse))
789 .findFirst()
790 .orElse(null);
Kalhee Kim45fede42017-09-05 19:05:06 +0000791
Kalhee Kim45b24182017-10-18 18:30:23 +0000792 removeHostOrRoute(directConnFlag, dhcp6Packet, clientPacket, clientIpv6, clientInterface);
Kalhee Kim45fede42017-09-05 19:05:06 +0000793
Kalhee Kim45b24182017-10-18 18:30:23 +0000794 DHCP6 dhcp6Relay = new DHCP6();
795 dhcp6Relay.setMsgType(DHCP6.MsgType.RELAY_FORW.value());
796 // link address: server uses the address to identify the link on which the client
797 // is located.
Kalhee Kim45fede42017-09-05 19:05:06 +0000798 if (directConnFlag) {
799 dhcp6Relay.setLinkAddress(relayAgentIp.toOctets());
800 log.debug("direct connection: relayAgentIp obtained dynamically {}",
801 HexString.toHexString(relayAgentIp.toOctets(), ":"));
802
803 } else {
Kalhee Kimd21029f2017-09-26 20:21:53 +0000804 if (this.indirectDhcpServerIp == null) {
805 log.warn("indirect DhcpServerIp not available, use default DhcpServerIp {}",
806 HexString.toHexString(this.dhcpServerIp.toOctets()));
807 } else {
808 // Indirect case, replace destination to indirect dhcp server if exist
809 // Check if mac is obtained for valid server ip
810 if (this.indirectDhcpConnectMac == null) {
811 log.warn("DHCP6 {} not yet resolved .. Aborting DHCP "
812 + "packet processing from client on port: {}",
813 (this.indirectDhcpGatewayIp == null) ? "server IP " + this.indirectDhcpServerIp
814 : "gateway IP " + this.indirectDhcpGatewayIp,
815 clientInterfaces.iterator().next().connectPoint());
816 return null;
817 }
818 etherReply.setDestinationMACAddress(this.indirectDhcpConnectMac);
819 etherReply.setVlanID(this.indirectDhcpConnectVlan.toShort());
820 ipv6Packet.setDestinationAddress(this.indirectDhcpServerIp.toOctets());
821
822 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000823 if (this.indirectRelayAgentIpFromCfg == null) {
824 dhcp6Relay.setLinkAddress(relayAgentIp.toOctets());
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000825 log.warn("indirect connection: relayAgentIp NOT availale from config file! Use dynamic. {}",
Kalhee Kim45fede42017-09-05 19:05:06 +0000826 HexString.toHexString(relayAgentIp.toOctets(), ":"));
827
828 } else {
829 dhcp6Relay.setLinkAddress(this.indirectRelayAgentIpFromCfg.toOctets());
830 log.debug("indirect connection: relayAgentIp from config file is available! {}",
831 HexString.toHexString(this.indirectRelayAgentIpFromCfg.toOctets(), ":"));
832 }
833 }
834
Kalhee Kim45b24182017-10-18 18:30:23 +0000835 // peer address: address of the client or relay agent from which
836 // the message to be relayed was received.
Charles Chana990ce92017-10-30 10:22:50 -0700837 dhcp6Relay.setPeerAddress(peerAddress.toOctets());
Kalhee Kim45b24182017-10-18 18:30:23 +0000838 List<Dhcp6Option> options = new ArrayList<Dhcp6Option>();
Kalhee Kim45fede42017-09-05 19:05:06 +0000839
Kalhee Kim45b24182017-10-18 18:30:23 +0000840 // directly connected case, hop count is zero
841 // otherwise, hop count + 1
842 if (directConnFlag) {
843 dhcp6Relay.setHopCount((byte) 0);
844 } else {
845 dhcp6Relay.setHopCount((byte) (dhcp6Packet.getHopCount() + 1));
846 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000847
Kalhee Kim45b24182017-10-18 18:30:23 +0000848 // create relay message option
849 Dhcp6Option relayMessage = new Dhcp6Option();
850 relayMessage.setCode(DHCP6.OptionCode.RELAY_MSG.value());
851 relayMessage.setLength((short) dhcp6PacketByte.length);
852 relayMessage.setData(dhcp6PacketByte);
853 options.add(relayMessage);
Kalhee Kim45fede42017-09-05 19:05:06 +0000854
Kalhee Kim45b24182017-10-18 18:30:23 +0000855 // create interfaceId option
856 String inPortString = "-" + context.inPacket().receivedFrom().toString() + ":";
857 Dhcp6Option interfaceId = new Dhcp6Option();
858 interfaceId.setCode(DHCP6.OptionCode.INTERFACE_ID.value());
859 byte[] clientSoureMacBytes = clientPacket.getSourceMACAddress();
860 byte[] inPortStringBytes = inPortString.getBytes();
861 byte[] vlanIdBytes = new byte[2];
862 vlanIdBytes[0] = (byte) (clientPacket.getVlanID() & 0xff);
863 vlanIdBytes[1] = (byte) ((clientPacket.getVlanID() >> 8) & 0xff);
864 byte[] interfaceIdBytes = new byte[clientSoureMacBytes.length +
865 inPortStringBytes.length + vlanIdBytes.length];
866 log.debug("Length: interfaceIdBytes {} clientSoureMacBytes {} inPortStringBytes {} vlan {}",
867 interfaceIdBytes.length, clientSoureMacBytes.length, inPortStringBytes.length,
868 vlanIdBytes.length);
Kalhee Kim45fede42017-09-05 19:05:06 +0000869
Kalhee Kim45b24182017-10-18 18:30:23 +0000870 System.arraycopy(clientSoureMacBytes, 0, interfaceIdBytes, 0, clientSoureMacBytes.length);
871 System.arraycopy(inPortStringBytes, 0, interfaceIdBytes, clientSoureMacBytes.length, inPortStringBytes.length);
872 System.arraycopy(vlanIdBytes, 0, interfaceIdBytes, clientSoureMacBytes.length + inPortStringBytes.length,
873 vlanIdBytes.length);
Kalhee Kim45fede42017-09-05 19:05:06 +0000874
Kalhee Kim45b24182017-10-18 18:30:23 +0000875 interfaceId.setData(interfaceIdBytes);
876 interfaceId.setLength((short) interfaceIdBytes.length);
Kalhee Kim45fede42017-09-05 19:05:06 +0000877
Kalhee Kim45b24182017-10-18 18:30:23 +0000878 options.add(interfaceId);
Kalhee Kim45fede42017-09-05 19:05:06 +0000879
Kalhee Kim45b24182017-10-18 18:30:23 +0000880 log.debug("interfaceId write srcMac {} portString {}",
881 HexString.toHexString(clientSoureMacBytes, ":"), inPortString);
882 dhcp6Relay.setOptions(options);
883 udpPacket.setPayload(dhcp6Relay);
884 udpPacket.resetChecksum();
885 ipv6Packet.setPayload(udpPacket);
886 ipv6Packet.setHopLimit((byte) 64);
887 etherReply.setPayload(ipv6Packet);
Kalhee Kim45fede42017-09-05 19:05:06 +0000888
Kalhee Kim45b24182017-10-18 18:30:23 +0000889 if (directConnFlag) {
890 return new InternalPacket(etherReply, this.dhcpServerConnectPoint);
891 } else {
892 if (this.indirectDhcpServerIp == null) {
893 return new InternalPacket(etherReply, this.dhcpServerConnectPoint);
894 } else {
895 return new InternalPacket(etherReply, this.indirectDhcpServerConnectPoint);
896 }
897 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000898 }
899
900 /**
901 *
902 * process the DHCP6 relay-reply packet from dhcp server.
903 *
904 * @param context packet context
905 * @param receivedPacket server ethernet packet
906 * @param recevingInterfaces set of server side interfaces
907 */
908 private InternalPacket processDhcp6PacketFromServer(PacketContext context,
909 Ethernet receivedPacket, Set<Interface> recevingInterfaces) {
Kalhee Kim45fede42017-09-05 19:05:06 +0000910 // get dhcp6 header.
Ray Milkeyf0c47612017-09-28 11:29:38 -0700911 Ethernet etherReply = receivedPacket.duplicate();
Kalhee Kim45fede42017-09-05 19:05:06 +0000912 IPv6 ipv6Packet = (IPv6) etherReply.getPayload();
913 UDP udpPacket = (UDP) ipv6Packet.getPayload();
914 DHCP6 dhcp6Relay = (DHCP6) udpPacket.getPayload();
915
916 Boolean directConnFlag = directlyConnected(dhcp6Relay);
Kalhee Kimd21029f2017-09-26 20:21:53 +0000917 ConnectPoint inPort = context.inPacket().receivedFrom();
918 if ((directConnFlag || (!directConnFlag && this.indirectDhcpServerIp == null))
919 && !inPort.equals(this.dhcpServerConnectPoint)) {
920 log.warn("Receiving port {} is not the same as server connect point {} for direct or indirect-null",
921 inPort, this.dhcpServerConnectPoint);
922 return null;
923 }
924
925 if (!directConnFlag && this.indirectDhcpServerIp != null &&
926 !inPort.equals(this.indirectDhcpServerConnectPoint)) {
927 log.warn("Receiving port {} is not the same as server connect point {} for indirect",
928 inPort, this.indirectDhcpServerConnectPoint);
929 return null;
930 }
931
Kalhee Kim45fede42017-09-05 19:05:06 +0000932
933 Dhcp6InterfaceIdOption interfaceIdOption = dhcp6Relay.getOptions().stream()
934 .filter(opt -> opt instanceof Dhcp6InterfaceIdOption)
935 .map(opt -> (Dhcp6InterfaceIdOption) opt)
936 .findFirst()
937 .orElse(null);
938
939 if (interfaceIdOption == null) {
940 log.warn("Interface Id option is not present, abort packet...");
941 return null;
942 }
943
944 MacAddress peerMac = interfaceIdOption.getMacAddress();
945 String clientConnectionPointStr = new String(interfaceIdOption.getInPort());
946
947 ConnectPoint clientConnectionPoint = ConnectPoint.deviceConnectPoint(clientConnectionPointStr);
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000948 VlanId vlanIdInUse = VlanId.vlanId(interfaceIdOption.getVlanId());
949 Interface clientInterface = interfaceService.getInterfacesByPort(clientConnectionPoint)
950 .stream()
951 .filter(iface -> interfaceContainsVlan(iface, vlanIdInUse))
952 .findFirst()
953 .orElse(null);
954 if (clientInterface == null) {
955 log.warn("Cannot get client interface for from packet, abort... vlan {}", vlanIdInUse.toString());
Kalhee Kim45fede42017-09-05 19:05:06 +0000956 return null;
957 }
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000958 MacAddress relayAgentMac = clientInterface.mac();
Kalhee Kim45fede42017-09-05 19:05:06 +0000959 if (relayAgentMac == null) {
960 log.warn("Can not get interface mac, abort packet..");
961 return null;
962 }
963 etherReply.setSourceMACAddress(relayAgentMac);
964
965 // find destMac
966 MacAddress clientMac = null;
Yi Tsengaa417a62017-09-08 17:22:51 -0700967 Ip6Address peerAddress = Ip6Address.valueOf(dhcp6Relay.getPeerAddress());
968 Set<Host> clients = hostService.getHostsByIp(peerAddress);
Kalhee Kim45fede42017-09-05 19:05:06 +0000969 if (clients.isEmpty()) {
970 log.warn("There's no host found for this address {}",
971 HexString.toHexString(dhcp6Relay.getPeerAddress(), ":"));
972 log.warn("Let's look up interfaceId {}", HexString.toHexString(peerMac.toBytes(), ":"));
973 clientMac = peerMac;
974 } else {
975 clientMac = clients.iterator().next().mac();
976 if (clientMac == null) {
977 log.warn("No client mac address found, abort packet...");
978 return null;
979 }
980 log.warn("Client mac address found from getHostByIp");
981
982 }
983 etherReply.setDestinationMACAddress(clientMac);
984
985 // ip header
986 ipv6Packet.setSourceAddress(dhcp6Relay.getLinkAddress());
987 ipv6Packet.setDestinationAddress(dhcp6Relay.getPeerAddress());
988 // udp header
989 udpPacket.setSourcePort(UDP.DHCP_V6_SERVER_PORT);
990 if (directConnFlag) {
991 udpPacket.setDestinationPort(UDP.DHCP_V6_CLIENT_PORT);
992 } else {
993 udpPacket.setDestinationPort(UDP.DHCP_V6_SERVER_PORT);
994 }
995
996 DHCP6 embeddedDhcp6 = dhcp6Relay.getOptions().stream()
997 .filter(opt -> opt instanceof Dhcp6RelayOption)
998 .map(BasePacket::getPayload)
999 .map(pld -> (DHCP6) pld)
1000 .findFirst()
1001 .orElse(null);
1002
1003
1004 // add host or route
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +00001005 addHostOrRoute(directConnFlag, dhcp6Relay, embeddedDhcp6, clientMac, clientInterface);
Kalhee Kim45fede42017-09-05 19:05:06 +00001006
1007 udpPacket.setPayload(embeddedDhcp6);
1008 udpPacket.resetChecksum();
1009 ipv6Packet.setPayload(udpPacket);
1010 etherReply.setPayload(ipv6Packet);
1011
1012 return new InternalPacket(etherReply, clientConnectionPoint);
1013 }
1014
Yi Tseng919b2df2017-09-07 16:22:51 -07001015 // Returns the first v6 interface ip out of a set of interfaces or null.
Kalhee Kim45fede42017-09-05 19:05:06 +00001016 // Checks all interfaces, and ignores v6 interface ips
1017 private Ip6Address getRelayAgentIPv6Address(Set<Interface> intfs) {
1018 for (Interface intf : intfs) {
1019 for (InterfaceIpAddress ip : intf.ipAddressesList()) {
1020 Ip6Address relayAgentIp = ip.ipAddress().getIp6Address();
1021 if (relayAgentIp != null) {
1022 return relayAgentIp;
1023 }
1024 }
1025 }
1026 return null;
Yi Tseng51301292017-07-28 13:02:59 -07001027 }
Yi Tseng483ac6f2017-08-02 15:03:31 -07001028
1029 @Override
1030 public void setDefaultDhcpServerConfigs(Collection<DhcpServerConfig> configs) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001031 setDhcpServerConfigs(configs, defaultServerInfoList);
1032 reloadServerSettings();
1033 }
1034
1035 @Override
1036 public void setIndirectDhcpServerConfigs(Collection<DhcpServerConfig> configs) {
1037 setDhcpServerConfigs(configs, indirectServerInfoList);
1038 reloadServerSettings();
1039 }
1040
1041 public void setDhcpServerConfigs(Collection<DhcpServerConfig> configs, List<DhcpServerInfo> serverInfoList) {
Kalhee Kim45fede42017-09-05 19:05:06 +00001042 if (configs.size() == 0) {
1043 // no config to update
1044 return;
1045 }
1046
1047 // TODO: currently we pick up first DHCP server config.
1048 // Will use other server configs in the future for HA.
1049 DhcpServerConfig serverConfig = configs.iterator().next();
Yi Tseng919b2df2017-09-07 16:22:51 -07001050
Kalhee Kim45fede42017-09-05 19:05:06 +00001051 if (!serverConfig.getDhcpServerIp6().isPresent()) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001052 // not a DHCPv6 config
Kalhee Kim45fede42017-09-05 19:05:06 +00001053 return;
1054 }
1055
Yi Tseng919b2df2017-09-07 16:22:51 -07001056 if (!serverInfoList.isEmpty()) {
1057 // remove old server info
1058 DhcpServerInfo oldServerInfo = serverInfoList.remove(0);
1059
1060 // stop monitoring gateway or server
1061 oldServerInfo.getDhcpGatewayIp6().ifPresent(gatewayIp -> {
1062 hostService.stopMonitoringIp(gatewayIp);
1063 });
1064 oldServerInfo.getDhcpServerIp6().ifPresent(serverIp -> {
1065 hostService.stopMonitoringIp(serverIp);
1066 });
1067 }
1068
1069 // Create new server info according to the config
1070 DhcpServerInfo newServerInfo = new DhcpServerInfo(serverConfig,
1071 DhcpServerInfo.Version.DHCP_V6);
1072 checkState(newServerInfo.getDhcpServerConnectPoint().isPresent(),
1073 "Connect point not exists");
1074 checkState(newServerInfo.getDhcpServerIp6().isPresent(),
1075 "IP of DHCP server not exists");
1076
1077 log.debug("DHCP server connect point: {}", newServerInfo.getDhcpServerConnectPoint().orElse(null));
1078 log.debug("DHCP server IP: {}", newServerInfo.getDhcpServerIp6().orElse(null));
1079
1080 IpAddress ipToProbe;
1081 if (newServerInfo.getDhcpGatewayIp6().isPresent()) {
1082 ipToProbe = newServerInfo.getDhcpGatewayIp6().get();
1083 } else {
1084 ipToProbe = newServerInfo.getDhcpServerIp6().orElse(null);
1085 }
1086 String hostToProbe = newServerInfo.getDhcpGatewayIp6()
1087 .map(ip -> "gateway").orElse("server");
1088
1089 log.debug("Probing to resolve {} IP {}", hostToProbe, ipToProbe);
Kalhee Kim45fede42017-09-05 19:05:06 +00001090 hostService.startMonitoringIp(ipToProbe);
1091
1092 Set<Host> hosts = hostService.getHostsByIp(ipToProbe);
1093 if (!hosts.isEmpty()) {
1094 Host host = hosts.iterator().next();
Yi Tseng919b2df2017-09-07 16:22:51 -07001095 newServerInfo.setDhcpConnectVlan(host.vlan());
1096 newServerInfo.setDhcpConnectMac(host.mac());
Kalhee Kim45fede42017-09-05 19:05:06 +00001097 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001098 // Add new server info
1099 serverInfoList.add(0, newServerInfo);
Yi Tseng483ac6f2017-08-02 15:03:31 -07001100
Yi Tseng919b2df2017-09-07 16:22:51 -07001101 // Remove duplicated server info
1102 Set<DhcpServerInfo> nonDupServerInfoList = Sets.newLinkedHashSet();
1103 nonDupServerInfoList.addAll(serverInfoList);
1104 serverInfoList.clear();
1105 serverInfoList.addAll(nonDupServerInfoList);
Kalhee Kim45fede42017-09-05 19:05:06 +00001106 }
1107
1108 class InternalHostListener implements HostListener {
1109 @Override
1110 public void event(HostEvent event) {
1111 switch (event.type()) {
1112 case HOST_ADDED:
1113 case HOST_UPDATED:
1114 hostUpdated(event.subject());
1115 break;
1116 case HOST_REMOVED:
1117 hostRemoved(event.subject());
1118 break;
1119 case HOST_MOVED:
1120 hostMoved(event.subject());
1121 break;
1122 default:
1123 break;
1124 }
1125 }
1126 }
1127
1128 /**
1129 * Handle host move.
1130 * If the host DHCP server or gateway and it moved to the location different
1131 * to user configured, unsets the connect mac and vlan
1132 *
1133 * @param host the host
1134 */
1135 private void hostMoved(Host host) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001136 Set<ConnectPoint> hostConnectPoints = host.locations().stream()
1137 .map(hl -> new ConnectPoint(hl.elementId(), hl.port()))
1138 .collect(Collectors.toSet());
1139 DhcpServerInfo serverInfo;
1140 ConnectPoint dhcpServerConnectPoint;
1141 Ip6Address dhcpGatewayIp;
1142 Ip6Address dhcpServerIp;
1143
1144 if (!defaultServerInfoList.isEmpty()) {
1145 serverInfo = defaultServerInfoList.get(0);
1146 dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1147 dhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1148 dhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
1149 if (dhcpServerConnectPoint == null) {
1150 return;
1151 }
1152 if (dhcpGatewayIp != null) {
1153 if (host.ipAddresses().contains(dhcpGatewayIp) &&
1154 !hostConnectPoints.contains(dhcpServerConnectPoint)) {
1155 serverInfo.setDhcpConnectVlan(null);
1156 serverInfo.setDhcpConnectMac(null);
1157 }
1158 }
1159 if (dhcpServerIp != null) {
1160 if (host.ipAddresses().contains(dhcpServerIp) &&
1161 !hostConnectPoints.contains(dhcpServerConnectPoint)) {
1162 serverInfo.setDhcpConnectVlan(null);
1163 serverInfo.setDhcpConnectMac(null);
1164 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001165 }
1166 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001167
1168 if (!indirectServerInfoList.isEmpty()) {
1169 serverInfo = indirectServerInfoList.get(0);
1170 dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1171 dhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1172 dhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
1173 if (dhcpServerConnectPoint == null) {
1174 return;
1175 }
1176 if (dhcpGatewayIp != null) {
1177 if (host.ipAddresses().contains(dhcpGatewayIp) &&
1178 !hostConnectPoints.contains(dhcpServerConnectPoint)) {
1179 serverInfo.setDhcpConnectVlan(null);
1180 serverInfo.setDhcpConnectMac(null);
1181 }
1182 }
1183 if (dhcpServerIp != null) {
1184 if (host.ipAddresses().contains(dhcpServerIp) &&
1185 !hostConnectPoints.contains(dhcpServerConnectPoint)) {
1186 serverInfo.setDhcpConnectVlan(null);
1187 serverInfo.setDhcpConnectMac(null);
1188 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001189 }
1190 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001191 reloadServerSettings();
Kalhee Kim45fede42017-09-05 19:05:06 +00001192 }
1193
1194 /**
1195 * Handle host updated.
1196 * If the host is DHCP server or gateway, update connect mac and vlan.
1197 *
1198 * @param host the host
1199 */
1200 private void hostUpdated(Host host) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001201 DhcpServerInfo serverInfo;
1202 Ip6Address dhcpGatewayIp;
1203 Ip6Address dhcpServerIp;
1204 if (!defaultServerInfoList.isEmpty()) {
1205 serverInfo = defaultServerInfoList.get(0);
1206 dhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1207 dhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
1208 if (dhcpGatewayIp != null) {
1209 if (host.ipAddresses().contains(dhcpGatewayIp)) {
1210 serverInfo.setDhcpConnectMac(host.mac());
1211 serverInfo.setDhcpConnectVlan(host.vlan());
1212 }
1213 }
1214 if (dhcpServerIp != null) {
1215 if (host.ipAddresses().contains(dhcpServerIp)) {
1216 serverInfo.setDhcpConnectMac(host.mac());
1217 serverInfo.setDhcpConnectVlan(host.vlan());
1218 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001219 }
1220 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001221
1222 if (!indirectServerInfoList.isEmpty()) {
1223 serverInfo = indirectServerInfoList.get(0);
1224 dhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1225 dhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
1226 if (dhcpGatewayIp != null) {
1227 if (host.ipAddresses().contains(dhcpGatewayIp)) {
1228 serverInfo.setDhcpConnectMac(host.mac());
1229 serverInfo.setDhcpConnectVlan(host.vlan());
1230 }
1231 }
1232 if (dhcpServerIp != null) {
1233 if (host.ipAddresses().contains(dhcpServerIp)) {
1234 serverInfo.setDhcpConnectMac(host.mac());
1235 serverInfo.setDhcpConnectVlan(host.vlan());
1236 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001237 }
1238 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001239 reloadServerSettings();
Kalhee Kim45fede42017-09-05 19:05:06 +00001240 }
1241
1242 /**
1243 * Handle host removed.
1244 * If the host is DHCP server or gateway, unset connect mac and vlan.
1245 *
1246 * @param host the host
1247 */
1248 private void hostRemoved(Host host) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001249 DhcpServerInfo serverInfo;
1250 Ip6Address dhcpGatewayIp;
1251 Ip6Address dhcpServerIp;
1252
1253 if (!defaultServerInfoList.isEmpty()) {
1254 serverInfo = defaultServerInfoList.get(0);
1255 dhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1256 dhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
1257
1258 if (dhcpGatewayIp != null) {
1259 if (host.ipAddresses().contains(dhcpGatewayIp)) {
1260 serverInfo.setDhcpConnectVlan(null);
1261 serverInfo.setDhcpConnectMac(null);
1262 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001263 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001264 if (dhcpServerIp != null) {
1265 if (host.ipAddresses().contains(dhcpServerIp)) {
1266 serverInfo.setDhcpConnectVlan(null);
1267 serverInfo.setDhcpConnectMac(null);
1268 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001269 }
1270 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001271
1272 if (!indirectServerInfoList.isEmpty()) {
1273 serverInfo = indirectServerInfoList.get(0);
1274 dhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1275 dhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
1276
1277 if (dhcpGatewayIp != null) {
1278 if (host.ipAddresses().contains(dhcpGatewayIp)) {
1279 serverInfo.setDhcpConnectVlan(null);
1280 serverInfo.setDhcpConnectMac(null);
1281 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001282 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001283 if (dhcpServerIp != null) {
1284 if (host.ipAddresses().contains(dhcpServerIp)) {
1285 serverInfo.setDhcpConnectVlan(null);
1286 serverInfo.setDhcpConnectMac(null);
1287 }
1288 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001289 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001290 reloadServerSettings();
1291 }
1292
1293 private void reloadServerSettings() {
1294 DhcpServerInfo serverInfo;
1295 if (!defaultServerInfoList.isEmpty()) {
1296 serverInfo = defaultServerInfoList.get(0);
1297 this.dhcpConnectMac = serverInfo.getDhcpConnectMac().orElse(null);
1298 this.dhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1299 this.dhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
1300 this.dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1301 this.dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1302 }
1303
1304 if (!indirectServerInfoList.isEmpty()) {
1305 serverInfo = indirectServerInfoList.get(0);
1306 this.indirectDhcpConnectMac = serverInfo.getDhcpConnectMac().orElse(null);
1307 this.indirectDhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1308 this.indirectDhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
1309 this.indirectDhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1310 this.indirectDhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1311 this.indirectRelayAgentIpFromCfg = serverInfo.getRelayAgentIp6().orElse(null);
Kalhee Kim45fede42017-09-05 19:05:06 +00001312 }
Yi Tseng483ac6f2017-08-02 15:03:31 -07001313 }
Kalhee Kim45b24182017-10-18 18:30:23 +00001314
1315 /**
1316 * Returns the first interface ip from interface.
1317 *
1318 * @param iface interface of one connect point
1319 * @return the first interface IP; null if not exists an IP address in
1320 * these interfaces
1321 */
1322 private Ip6Address getFirstIpFromInterface(Interface iface) {
1323 checkNotNull(iface, "Interface can't be null");
1324 return iface.ipAddressesList().stream()
1325 .map(InterfaceIpAddress::ipAddress)
1326 .filter(IpAddress::isIp6)
1327 .map(IpAddress::getIp6Address)
1328 .findFirst()
1329 .orElse(null);
1330 }
1331
1332 /**
1333 * Gets Interface facing to the server for default host.
1334 *
1335 * @return the Interface facing to the server; null if not found
1336 */
1337 private Interface getServerInterface() {
1338 if (dhcpServerConnectPoint == null || dhcpConnectVlan == null) {
1339 return null;
1340 }
1341 return interfaceService.getInterfacesByPort(dhcpServerConnectPoint)
1342 .stream()
1343 .filter(iface -> interfaceContainsVlan(iface, dhcpConnectVlan))
1344 .findFirst()
1345 .orElse(null);
1346 }
1347
1348 /**
1349 * Gets Interface facing to the server for indirect hosts.
1350 * Use default server Interface if indirect server not configured.
1351 *
1352 * @return the Interface facing to the server; null if not found
1353 */
1354 private Interface getIndirectServerInterface() {
1355 if (indirectDhcpServerConnectPoint == null || indirectDhcpConnectVlan == null) {
1356 return getServerInterface();
1357 }
1358 return interfaceService.getInterfacesByPort(indirectDhcpServerConnectPoint)
1359 .stream()
1360 .filter(iface -> interfaceContainsVlan(iface, indirectDhcpConnectVlan))
1361 .findFirst()
1362 .orElse(null);
1363 }
1364
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +00001365 /**
1366 * Determind if an Interface contains a vlan id.
1367 *
1368 * @param iface the Interface
1369 * @param vlanId the vlan id
1370 * @return true if the Interface contains the vlan id
1371 */
1372 private boolean interfaceContainsVlan(Interface iface, VlanId vlanId) {
1373 if (vlanId.equals(VlanId.NONE)) {
1374 // untagged packet, check if vlan untagged or vlan native is not NONE
1375 return !iface.vlanUntagged().equals(VlanId.NONE) ||
1376 !iface.vlanNative().equals(VlanId.NONE);
1377 }
1378 // tagged packet, check if the interface contains the vlan
1379 return iface.vlanTagged().contains(vlanId);
1380 }
1381
Yi Tseng51301292017-07-28 13:02:59 -07001382}