blob: 9dabfd9fa44c40dd02ffe2cd961ce34a92277ae3 [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) {
691 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 }
699
700 // get dhcp6 header.
701
702 IPv6 clientIpv6 = (IPv6) clientPacket.getPayload();
703 UDP clientUdp = (UDP) clientIpv6.getPayload();
704 DHCP6 clientDhcp6 = (DHCP6) clientUdp.getPayload();
705
706 boolean directConnFlag = directlyConnected(clientDhcp6);
707
Ray Milkeyf0c47612017-09-28 11:29:38 -0700708 Ethernet etherReply = clientPacket.duplicate();
Kalhee Kim45fede42017-09-05 19:05:06 +0000709 etherReply.setSourceMACAddress(relayAgentMac);
710
Kalhee Kimd21029f2017-09-26 20:21:53 +0000711 if ((directConnFlag && this.dhcpConnectMac == null) ||
712 !directConnFlag && this.indirectDhcpConnectMac == null && this.dhcpConnectMac == null) {
713 log.warn("Packet received from {} connected client.", directConnFlag ? "directly" : "indirectly");
Kalhee Kim45fede42017-09-05 19:05:06 +0000714 log.warn("DHCP6 {} not yet resolved .. Aborting DHCP "
715 + "packet processing from client on port: {}",
716 (this.dhcpGatewayIp == null) ? "server IP " + this.dhcpServerIp
717 : "gateway IP " + this.dhcpGatewayIp,
718 clientInterfaces.iterator().next().connectPoint());
719
720 return null;
721 }
722
Kalhee Kim45fede42017-09-05 19:05:06 +0000723 if (this.dhcpServerConnectPoint == null) {
Kalhee Kimd21029f2017-09-26 20:21:53 +0000724 log.warn("DHCP6 server connection point direct {} directConn {} indirectConn {} is not set up yet",
725 directConnFlag, this.dhcpServerConnectPoint, this.indirectDhcpServerConnectPoint);
Kalhee Kim45fede42017-09-05 19:05:06 +0000726 return null;
727 }
728
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000729 etherReply.setDestinationMACAddress(this.dhcpConnectMac);
730 etherReply.setVlanID(this.dhcpConnectVlan.toShort());
Kalhee Kim45fede42017-09-05 19:05:06 +0000731
732 IPv6 ipv6Packet = (IPv6) etherReply.getPayload();
733 byte[] peerAddress = clientIpv6.getSourceAddress();
734 ipv6Packet.setSourceAddress(relayAgentIp.toOctets());
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000735 ipv6Packet.setDestinationAddress(this.dhcpServerIp.toOctets());
Kalhee Kim45fede42017-09-05 19:05:06 +0000736
737 UDP udpPacket = (UDP) ipv6Packet.getPayload();
738 udpPacket.setSourcePort(UDP.DHCP_V6_SERVER_PORT);
739 DHCP6 dhcp6Packet = (DHCP6) udpPacket.getPayload();
740 byte[] dhcp6PacketByte = dhcp6Packet.serialize();
741
742 // notify onos and quagga to release PD
743 //releasePD(dhcp6Packet);
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000744 ConnectPoint clientConnectionPoint = context.inPacket().receivedFrom();
745 VlanId vlanIdInUse = VlanId.vlanId(clientPacket.getVlanID());
746 Interface clientInterface = interfaceService.getInterfacesByPort(clientConnectionPoint)
747 .stream()
748 .filter(iface -> interfaceContainsVlan(iface, vlanIdInUse))
749 .findFirst()
750 .orElse(null);
Kalhee Kim45fede42017-09-05 19:05:06 +0000751
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000752 removeHostOrRoute(directConnFlag, dhcp6Packet, clientPacket, clientIpv6, clientInterface);
Kalhee Kim45fede42017-09-05 19:05:06 +0000753
754 DHCP6 dhcp6Relay = new DHCP6();
755 dhcp6Relay.setMsgType(DHCP6.MsgType.RELAY_FORW.value());
756 // link address: server uses the address to identify the link on which the client
757 // is located.
758 if (directConnFlag) {
759 dhcp6Relay.setLinkAddress(relayAgentIp.toOctets());
760 log.debug("direct connection: relayAgentIp obtained dynamically {}",
761 HexString.toHexString(relayAgentIp.toOctets(), ":"));
762
763 } else {
Kalhee Kimd21029f2017-09-26 20:21:53 +0000764 if (this.indirectDhcpServerIp == null) {
765 log.warn("indirect DhcpServerIp not available, use default DhcpServerIp {}",
766 HexString.toHexString(this.dhcpServerIp.toOctets()));
767 } else {
768 // Indirect case, replace destination to indirect dhcp server if exist
769 // Check if mac is obtained for valid server ip
770 if (this.indirectDhcpConnectMac == null) {
771 log.warn("DHCP6 {} not yet resolved .. Aborting DHCP "
772 + "packet processing from client on port: {}",
773 (this.indirectDhcpGatewayIp == null) ? "server IP " + this.indirectDhcpServerIp
774 : "gateway IP " + this.indirectDhcpGatewayIp,
775 clientInterfaces.iterator().next().connectPoint());
776 return null;
777 }
778 etherReply.setDestinationMACAddress(this.indirectDhcpConnectMac);
779 etherReply.setVlanID(this.indirectDhcpConnectVlan.toShort());
780 ipv6Packet.setDestinationAddress(this.indirectDhcpServerIp.toOctets());
781
782 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000783 if (this.indirectRelayAgentIpFromCfg == null) {
784 dhcp6Relay.setLinkAddress(relayAgentIp.toOctets());
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000785 log.warn("indirect connection: relayAgentIp NOT availale from config file! Use dynamic. {}",
Kalhee Kim45fede42017-09-05 19:05:06 +0000786 HexString.toHexString(relayAgentIp.toOctets(), ":"));
787
788 } else {
789 dhcp6Relay.setLinkAddress(this.indirectRelayAgentIpFromCfg.toOctets());
790 log.debug("indirect connection: relayAgentIp from config file is available! {}",
791 HexString.toHexString(this.indirectRelayAgentIpFromCfg.toOctets(), ":"));
792 }
793 }
794
795 // peer address: address of the client or relay agent from which
796 // the message to be relayed was received.
797 dhcp6Relay.setPeerAddress(peerAddress);
798 List<Dhcp6Option> options = new ArrayList<Dhcp6Option>();
799
800 // directly connected case, hop count is zero
801 // otherwise, hop count + 1
802 if (directConnFlag) {
803 dhcp6Relay.setHopCount((byte) 0);
804 } else {
805 dhcp6Relay.setHopCount((byte) (dhcp6Packet.getHopCount() + 1));
806 }
807
808 // create relay message option
809 Dhcp6Option relayMessage = new Dhcp6Option();
810 relayMessage.setCode(DHCP6.OptionCode.RELAY_MSG.value());
811 relayMessage.setLength((short) dhcp6PacketByte.length);
812 relayMessage.setData(dhcp6PacketByte);
813 options.add(relayMessage);
814
815 // create interfaceId option
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000816 String inPortString = "-" + context.inPacket().receivedFrom().toString() + ":";
Kalhee Kim45fede42017-09-05 19:05:06 +0000817 Dhcp6Option interfaceId = new Dhcp6Option();
818 interfaceId.setCode(DHCP6.OptionCode.INTERFACE_ID.value());
819 byte[] clientSoureMacBytes = clientPacket.getSourceMACAddress();
820 byte[] inPortStringBytes = inPortString.getBytes();
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000821 byte[] vlanIdBytes = new byte[2];
822 vlanIdBytes[0] = (byte) (clientPacket.getVlanID() & 0xff);
823 vlanIdBytes[1] = (byte) ((clientPacket.getVlanID() >> 8) & 0xff);
824 byte[] interfaceIdBytes = new byte[clientSoureMacBytes.length +
825 inPortStringBytes.length + vlanIdBytes.length];
826 log.debug("Length: interfaceIdBytes {} clientSoureMacBytes {} inPortStringBytes {} vlan {}",
827 interfaceIdBytes.length, clientSoureMacBytes.length, inPortStringBytes.length,
828 vlanIdBytes.length);
Kalhee Kim45fede42017-09-05 19:05:06 +0000829
830 System.arraycopy(clientSoureMacBytes, 0, interfaceIdBytes, 0, clientSoureMacBytes.length);
831 System.arraycopy(inPortStringBytes, 0, interfaceIdBytes, clientSoureMacBytes.length, inPortStringBytes.length);
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000832 System.arraycopy(vlanIdBytes, 0, interfaceIdBytes, clientSoureMacBytes.length + inPortStringBytes.length,
833 vlanIdBytes.length);
Kalhee Kim45fede42017-09-05 19:05:06 +0000834
835 interfaceId.setData(interfaceIdBytes);
836 interfaceId.setLength((short) interfaceIdBytes.length);
837
838 options.add(interfaceId);
839
840 log.debug("interfaceId write srcMac {} portString {}",
841 HexString.toHexString(clientSoureMacBytes, ":"), inPortString);
842 dhcp6Relay.setOptions(options);
Kalhee Kim45fede42017-09-05 19:05:06 +0000843 udpPacket.setPayload(dhcp6Relay);
844 udpPacket.resetChecksum();
845 ipv6Packet.setPayload(udpPacket);
Charles Chanae0f5dc2017-10-09 11:07:25 -0400846 ipv6Packet.setHopLimit((byte) 64);
Kalhee Kim45fede42017-09-05 19:05:06 +0000847 etherReply.setPayload(ipv6Packet);
848
Kalhee Kimd21029f2017-09-26 20:21:53 +0000849 if (directConnFlag) {
850 return new InternalPacket(etherReply, this.dhcpServerConnectPoint);
851 } else {
852 if (this.indirectDhcpServerIp == null) {
853 return new InternalPacket(etherReply, this.dhcpServerConnectPoint);
854 } else {
855 return new InternalPacket(etherReply, this.indirectDhcpServerConnectPoint);
856 }
857 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000858 }
859
860 /**
861 *
862 * process the DHCP6 relay-reply packet from dhcp server.
863 *
864 * @param context packet context
865 * @param receivedPacket server ethernet packet
866 * @param recevingInterfaces set of server side interfaces
867 */
868 private InternalPacket processDhcp6PacketFromServer(PacketContext context,
869 Ethernet receivedPacket, Set<Interface> recevingInterfaces) {
Kalhee Kim45fede42017-09-05 19:05:06 +0000870 // get dhcp6 header.
Ray Milkeyf0c47612017-09-28 11:29:38 -0700871 Ethernet etherReply = receivedPacket.duplicate();
Kalhee Kim45fede42017-09-05 19:05:06 +0000872 IPv6 ipv6Packet = (IPv6) etherReply.getPayload();
873 UDP udpPacket = (UDP) ipv6Packet.getPayload();
874 DHCP6 dhcp6Relay = (DHCP6) udpPacket.getPayload();
875
876 Boolean directConnFlag = directlyConnected(dhcp6Relay);
Kalhee Kimd21029f2017-09-26 20:21:53 +0000877 ConnectPoint inPort = context.inPacket().receivedFrom();
878 if ((directConnFlag || (!directConnFlag && this.indirectDhcpServerIp == null))
879 && !inPort.equals(this.dhcpServerConnectPoint)) {
880 log.warn("Receiving port {} is not the same as server connect point {} for direct or indirect-null",
881 inPort, this.dhcpServerConnectPoint);
882 return null;
883 }
884
885 if (!directConnFlag && this.indirectDhcpServerIp != null &&
886 !inPort.equals(this.indirectDhcpServerConnectPoint)) {
887 log.warn("Receiving port {} is not the same as server connect point {} for indirect",
888 inPort, this.indirectDhcpServerConnectPoint);
889 return null;
890 }
891
Kalhee Kim45fede42017-09-05 19:05:06 +0000892
893 Dhcp6InterfaceIdOption interfaceIdOption = dhcp6Relay.getOptions().stream()
894 .filter(opt -> opt instanceof Dhcp6InterfaceIdOption)
895 .map(opt -> (Dhcp6InterfaceIdOption) opt)
896 .findFirst()
897 .orElse(null);
898
899 if (interfaceIdOption == null) {
900 log.warn("Interface Id option is not present, abort packet...");
901 return null;
902 }
903
904 MacAddress peerMac = interfaceIdOption.getMacAddress();
905 String clientConnectionPointStr = new String(interfaceIdOption.getInPort());
906
907 ConnectPoint clientConnectionPoint = ConnectPoint.deviceConnectPoint(clientConnectionPointStr);
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000908 VlanId vlanIdInUse = VlanId.vlanId(interfaceIdOption.getVlanId());
909 Interface clientInterface = interfaceService.getInterfacesByPort(clientConnectionPoint)
910 .stream()
911 .filter(iface -> interfaceContainsVlan(iface, vlanIdInUse))
912 .findFirst()
913 .orElse(null);
914 if (clientInterface == null) {
915 log.warn("Cannot get client interface for from packet, abort... vlan {}", vlanIdInUse.toString());
Kalhee Kim45fede42017-09-05 19:05:06 +0000916 return null;
917 }
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000918 MacAddress relayAgentMac = clientInterface.mac();
Kalhee Kim45fede42017-09-05 19:05:06 +0000919 if (relayAgentMac == null) {
920 log.warn("Can not get interface mac, abort packet..");
921 return null;
922 }
923 etherReply.setSourceMACAddress(relayAgentMac);
924
925 // find destMac
926 MacAddress clientMac = null;
Yi Tsengaa417a62017-09-08 17:22:51 -0700927 Ip6Address peerAddress = Ip6Address.valueOf(dhcp6Relay.getPeerAddress());
928 Set<Host> clients = hostService.getHostsByIp(peerAddress);
Kalhee Kim45fede42017-09-05 19:05:06 +0000929 if (clients.isEmpty()) {
930 log.warn("There's no host found for this address {}",
931 HexString.toHexString(dhcp6Relay.getPeerAddress(), ":"));
932 log.warn("Let's look up interfaceId {}", HexString.toHexString(peerMac.toBytes(), ":"));
933 clientMac = peerMac;
934 } else {
935 clientMac = clients.iterator().next().mac();
936 if (clientMac == null) {
937 log.warn("No client mac address found, abort packet...");
938 return null;
939 }
940 log.warn("Client mac address found from getHostByIp");
941
942 }
943 etherReply.setDestinationMACAddress(clientMac);
944
945 // ip header
946 ipv6Packet.setSourceAddress(dhcp6Relay.getLinkAddress());
947 ipv6Packet.setDestinationAddress(dhcp6Relay.getPeerAddress());
948 // udp header
949 udpPacket.setSourcePort(UDP.DHCP_V6_SERVER_PORT);
950 if (directConnFlag) {
951 udpPacket.setDestinationPort(UDP.DHCP_V6_CLIENT_PORT);
952 } else {
953 udpPacket.setDestinationPort(UDP.DHCP_V6_SERVER_PORT);
954 }
955
956 DHCP6 embeddedDhcp6 = dhcp6Relay.getOptions().stream()
957 .filter(opt -> opt instanceof Dhcp6RelayOption)
958 .map(BasePacket::getPayload)
959 .map(pld -> (DHCP6) pld)
960 .findFirst()
961 .orElse(null);
962
963
964 // add host or route
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000965 addHostOrRoute(directConnFlag, dhcp6Relay, embeddedDhcp6, clientMac, clientInterface);
Kalhee Kim45fede42017-09-05 19:05:06 +0000966
967 udpPacket.setPayload(embeddedDhcp6);
968 udpPacket.resetChecksum();
969 ipv6Packet.setPayload(udpPacket);
970 etherReply.setPayload(ipv6Packet);
971
972 return new InternalPacket(etherReply, clientConnectionPoint);
973 }
974
Yi Tseng919b2df2017-09-07 16:22:51 -0700975 // Returns the first v6 interface ip out of a set of interfaces or null.
Kalhee Kim45fede42017-09-05 19:05:06 +0000976 // Checks all interfaces, and ignores v6 interface ips
977 private Ip6Address getRelayAgentIPv6Address(Set<Interface> intfs) {
978 for (Interface intf : intfs) {
979 for (InterfaceIpAddress ip : intf.ipAddressesList()) {
980 Ip6Address relayAgentIp = ip.ipAddress().getIp6Address();
981 if (relayAgentIp != null) {
982 return relayAgentIp;
983 }
984 }
985 }
986 return null;
Yi Tseng51301292017-07-28 13:02:59 -0700987 }
Yi Tseng483ac6f2017-08-02 15:03:31 -0700988
989 @Override
990 public void setDefaultDhcpServerConfigs(Collection<DhcpServerConfig> configs) {
Yi Tseng919b2df2017-09-07 16:22:51 -0700991 setDhcpServerConfigs(configs, defaultServerInfoList);
992 reloadServerSettings();
993 }
994
995 @Override
996 public void setIndirectDhcpServerConfigs(Collection<DhcpServerConfig> configs) {
997 setDhcpServerConfigs(configs, indirectServerInfoList);
998 reloadServerSettings();
999 }
1000
1001 public void setDhcpServerConfigs(Collection<DhcpServerConfig> configs, List<DhcpServerInfo> serverInfoList) {
Kalhee Kim45fede42017-09-05 19:05:06 +00001002 if (configs.size() == 0) {
1003 // no config to update
1004 return;
1005 }
1006
1007 // TODO: currently we pick up first DHCP server config.
1008 // Will use other server configs in the future for HA.
1009 DhcpServerConfig serverConfig = configs.iterator().next();
Yi Tseng919b2df2017-09-07 16:22:51 -07001010
Kalhee Kim45fede42017-09-05 19:05:06 +00001011 if (!serverConfig.getDhcpServerIp6().isPresent()) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001012 // not a DHCPv6 config
Kalhee Kim45fede42017-09-05 19:05:06 +00001013 return;
1014 }
1015
Yi Tseng919b2df2017-09-07 16:22:51 -07001016 if (!serverInfoList.isEmpty()) {
1017 // remove old server info
1018 DhcpServerInfo oldServerInfo = serverInfoList.remove(0);
1019
1020 // stop monitoring gateway or server
1021 oldServerInfo.getDhcpGatewayIp6().ifPresent(gatewayIp -> {
1022 hostService.stopMonitoringIp(gatewayIp);
1023 });
1024 oldServerInfo.getDhcpServerIp6().ifPresent(serverIp -> {
1025 hostService.stopMonitoringIp(serverIp);
1026 });
1027 }
1028
1029 // Create new server info according to the config
1030 DhcpServerInfo newServerInfo = new DhcpServerInfo(serverConfig,
1031 DhcpServerInfo.Version.DHCP_V6);
1032 checkState(newServerInfo.getDhcpServerConnectPoint().isPresent(),
1033 "Connect point not exists");
1034 checkState(newServerInfo.getDhcpServerIp6().isPresent(),
1035 "IP of DHCP server not exists");
1036
1037 log.debug("DHCP server connect point: {}", newServerInfo.getDhcpServerConnectPoint().orElse(null));
1038 log.debug("DHCP server IP: {}", newServerInfo.getDhcpServerIp6().orElse(null));
1039
1040 IpAddress ipToProbe;
1041 if (newServerInfo.getDhcpGatewayIp6().isPresent()) {
1042 ipToProbe = newServerInfo.getDhcpGatewayIp6().get();
1043 } else {
1044 ipToProbe = newServerInfo.getDhcpServerIp6().orElse(null);
1045 }
1046 String hostToProbe = newServerInfo.getDhcpGatewayIp6()
1047 .map(ip -> "gateway").orElse("server");
1048
1049 log.debug("Probing to resolve {} IP {}", hostToProbe, ipToProbe);
Kalhee Kim45fede42017-09-05 19:05:06 +00001050 hostService.startMonitoringIp(ipToProbe);
1051
1052 Set<Host> hosts = hostService.getHostsByIp(ipToProbe);
1053 if (!hosts.isEmpty()) {
1054 Host host = hosts.iterator().next();
Yi Tseng919b2df2017-09-07 16:22:51 -07001055 newServerInfo.setDhcpConnectVlan(host.vlan());
1056 newServerInfo.setDhcpConnectMac(host.mac());
Kalhee Kim45fede42017-09-05 19:05:06 +00001057 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001058 // Add new server info
1059 serverInfoList.add(0, newServerInfo);
Yi Tseng483ac6f2017-08-02 15:03:31 -07001060
Yi Tseng919b2df2017-09-07 16:22:51 -07001061 // Remove duplicated server info
1062 Set<DhcpServerInfo> nonDupServerInfoList = Sets.newLinkedHashSet();
1063 nonDupServerInfoList.addAll(serverInfoList);
1064 serverInfoList.clear();
1065 serverInfoList.addAll(nonDupServerInfoList);
Kalhee Kim45fede42017-09-05 19:05:06 +00001066 }
1067
1068 class InternalHostListener implements HostListener {
1069 @Override
1070 public void event(HostEvent event) {
1071 switch (event.type()) {
1072 case HOST_ADDED:
1073 case HOST_UPDATED:
1074 hostUpdated(event.subject());
1075 break;
1076 case HOST_REMOVED:
1077 hostRemoved(event.subject());
1078 break;
1079 case HOST_MOVED:
1080 hostMoved(event.subject());
1081 break;
1082 default:
1083 break;
1084 }
1085 }
1086 }
1087
1088 /**
1089 * Handle host move.
1090 * If the host DHCP server or gateway and it moved to the location different
1091 * to user configured, unsets the connect mac and vlan
1092 *
1093 * @param host the host
1094 */
1095 private void hostMoved(Host host) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001096 Set<ConnectPoint> hostConnectPoints = host.locations().stream()
1097 .map(hl -> new ConnectPoint(hl.elementId(), hl.port()))
1098 .collect(Collectors.toSet());
1099 DhcpServerInfo serverInfo;
1100 ConnectPoint dhcpServerConnectPoint;
1101 Ip6Address dhcpGatewayIp;
1102 Ip6Address dhcpServerIp;
1103
1104 if (!defaultServerInfoList.isEmpty()) {
1105 serverInfo = defaultServerInfoList.get(0);
1106 dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1107 dhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1108 dhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
1109 if (dhcpServerConnectPoint == null) {
1110 return;
1111 }
1112 if (dhcpGatewayIp != null) {
1113 if (host.ipAddresses().contains(dhcpGatewayIp) &&
1114 !hostConnectPoints.contains(dhcpServerConnectPoint)) {
1115 serverInfo.setDhcpConnectVlan(null);
1116 serverInfo.setDhcpConnectMac(null);
1117 }
1118 }
1119 if (dhcpServerIp != null) {
1120 if (host.ipAddresses().contains(dhcpServerIp) &&
1121 !hostConnectPoints.contains(dhcpServerConnectPoint)) {
1122 serverInfo.setDhcpConnectVlan(null);
1123 serverInfo.setDhcpConnectMac(null);
1124 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001125 }
1126 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001127
1128 if (!indirectServerInfoList.isEmpty()) {
1129 serverInfo = indirectServerInfoList.get(0);
1130 dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1131 dhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1132 dhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
1133 if (dhcpServerConnectPoint == null) {
1134 return;
1135 }
1136 if (dhcpGatewayIp != null) {
1137 if (host.ipAddresses().contains(dhcpGatewayIp) &&
1138 !hostConnectPoints.contains(dhcpServerConnectPoint)) {
1139 serverInfo.setDhcpConnectVlan(null);
1140 serverInfo.setDhcpConnectMac(null);
1141 }
1142 }
1143 if (dhcpServerIp != null) {
1144 if (host.ipAddresses().contains(dhcpServerIp) &&
1145 !hostConnectPoints.contains(dhcpServerConnectPoint)) {
1146 serverInfo.setDhcpConnectVlan(null);
1147 serverInfo.setDhcpConnectMac(null);
1148 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001149 }
1150 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001151 reloadServerSettings();
Kalhee Kim45fede42017-09-05 19:05:06 +00001152 }
1153
1154 /**
1155 * Handle host updated.
1156 * If the host is DHCP server or gateway, update connect mac and vlan.
1157 *
1158 * @param host the host
1159 */
1160 private void hostUpdated(Host host) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001161 DhcpServerInfo serverInfo;
1162 Ip6Address dhcpGatewayIp;
1163 Ip6Address dhcpServerIp;
1164 if (!defaultServerInfoList.isEmpty()) {
1165 serverInfo = defaultServerInfoList.get(0);
1166 dhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1167 dhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
1168 if (dhcpGatewayIp != null) {
1169 if (host.ipAddresses().contains(dhcpGatewayIp)) {
1170 serverInfo.setDhcpConnectMac(host.mac());
1171 serverInfo.setDhcpConnectVlan(host.vlan());
1172 }
1173 }
1174 if (dhcpServerIp != null) {
1175 if (host.ipAddresses().contains(dhcpServerIp)) {
1176 serverInfo.setDhcpConnectMac(host.mac());
1177 serverInfo.setDhcpConnectVlan(host.vlan());
1178 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001179 }
1180 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001181
1182 if (!indirectServerInfoList.isEmpty()) {
1183 serverInfo = indirectServerInfoList.get(0);
1184 dhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1185 dhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
1186 if (dhcpGatewayIp != null) {
1187 if (host.ipAddresses().contains(dhcpGatewayIp)) {
1188 serverInfo.setDhcpConnectMac(host.mac());
1189 serverInfo.setDhcpConnectVlan(host.vlan());
1190 }
1191 }
1192 if (dhcpServerIp != null) {
1193 if (host.ipAddresses().contains(dhcpServerIp)) {
1194 serverInfo.setDhcpConnectMac(host.mac());
1195 serverInfo.setDhcpConnectVlan(host.vlan());
1196 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001197 }
1198 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001199 reloadServerSettings();
Kalhee Kim45fede42017-09-05 19:05:06 +00001200 }
1201
1202 /**
1203 * Handle host removed.
1204 * If the host is DHCP server or gateway, unset connect mac and vlan.
1205 *
1206 * @param host the host
1207 */
1208 private void hostRemoved(Host host) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001209 DhcpServerInfo serverInfo;
1210 Ip6Address dhcpGatewayIp;
1211 Ip6Address dhcpServerIp;
1212
1213 if (!defaultServerInfoList.isEmpty()) {
1214 serverInfo = defaultServerInfoList.get(0);
1215 dhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1216 dhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
1217
1218 if (dhcpGatewayIp != null) {
1219 if (host.ipAddresses().contains(dhcpGatewayIp)) {
1220 serverInfo.setDhcpConnectVlan(null);
1221 serverInfo.setDhcpConnectMac(null);
1222 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001223 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001224 if (dhcpServerIp != null) {
1225 if (host.ipAddresses().contains(dhcpServerIp)) {
1226 serverInfo.setDhcpConnectVlan(null);
1227 serverInfo.setDhcpConnectMac(null);
1228 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001229 }
1230 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001231
1232 if (!indirectServerInfoList.isEmpty()) {
1233 serverInfo = indirectServerInfoList.get(0);
1234 dhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1235 dhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
1236
1237 if (dhcpGatewayIp != null) {
1238 if (host.ipAddresses().contains(dhcpGatewayIp)) {
1239 serverInfo.setDhcpConnectVlan(null);
1240 serverInfo.setDhcpConnectMac(null);
1241 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001242 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001243 if (dhcpServerIp != null) {
1244 if (host.ipAddresses().contains(dhcpServerIp)) {
1245 serverInfo.setDhcpConnectVlan(null);
1246 serverInfo.setDhcpConnectMac(null);
1247 }
1248 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001249 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001250 reloadServerSettings();
1251 }
1252
1253 private void reloadServerSettings() {
1254 DhcpServerInfo serverInfo;
1255 if (!defaultServerInfoList.isEmpty()) {
1256 serverInfo = defaultServerInfoList.get(0);
1257 this.dhcpConnectMac = serverInfo.getDhcpConnectMac().orElse(null);
1258 this.dhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1259 this.dhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
1260 this.dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1261 this.dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1262 }
1263
1264 if (!indirectServerInfoList.isEmpty()) {
1265 serverInfo = indirectServerInfoList.get(0);
1266 this.indirectDhcpConnectMac = serverInfo.getDhcpConnectMac().orElse(null);
1267 this.indirectDhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null);
1268 this.indirectDhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null);
1269 this.indirectDhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1270 this.indirectDhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1271 this.indirectRelayAgentIpFromCfg = serverInfo.getRelayAgentIp6().orElse(null);
Kalhee Kim45fede42017-09-05 19:05:06 +00001272 }
Yi Tseng483ac6f2017-08-02 15:03:31 -07001273 }
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +00001274 /**
1275 * Determind if an Interface contains a vlan id.
1276 *
1277 * @param iface the Interface
1278 * @param vlanId the vlan id
1279 * @return true if the Interface contains the vlan id
1280 */
1281 private boolean interfaceContainsVlan(Interface iface, VlanId vlanId) {
1282 if (vlanId.equals(VlanId.NONE)) {
1283 // untagged packet, check if vlan untagged or vlan native is not NONE
1284 return !iface.vlanUntagged().equals(VlanId.NONE) ||
1285 !iface.vlanNative().equals(VlanId.NONE);
1286 }
1287 // tagged packet, check if the interface contains the vlan
1288 return iface.vlanTagged().contains(vlanId);
1289 }
1290
Yi Tseng51301292017-07-28 13:02:59 -07001291}