blob: 702df7e3a381ee1638a74f2184e7229d99b2fdf9 [file] [log] [blame]
Yi Tseng51301292017-07-28 13:02:59 -07001/*
2 * Copyright 2017-present Open Networking Foundation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 */
17
18package org.onosproject.dhcprelay;
19
Yi Tseng525ff402017-10-23 19:39:39 -070020import com.google.common.collect.HashMultimap;
21import com.google.common.collect.ImmutableSet;
Charles Chane5e0c9a2018-03-30 12:11:34 -070022import com.google.common.collect.Lists;
Yi Tseng525ff402017-10-23 19:39:39 -070023import com.google.common.collect.Multimap;
Charles Chan70fdd492018-03-07 17:36:06 -080024import com.google.common.collect.Multimaps;
Yi Tseng51301292017-07-28 13:02:59 -070025import com.google.common.collect.Sets;
Yi Tseng51301292017-07-28 13:02:59 -070026import org.onlab.packet.BasePacket;
27import org.onlab.packet.DHCP;
28import org.onlab.packet.Ethernet;
29import org.onlab.packet.IPv4;
30import org.onlab.packet.Ip4Address;
31import org.onlab.packet.IpAddress;
32import org.onlab.packet.MacAddress;
Yi Tseng525ff402017-10-23 19:39:39 -070033import org.onlab.packet.TpPort;
Yi Tseng51301292017-07-28 13:02:59 -070034import org.onlab.packet.UDP;
35import org.onlab.packet.VlanId;
36import org.onlab.packet.dhcp.CircuitId;
37import org.onlab.packet.dhcp.DhcpOption;
38import org.onlab.packet.dhcp.DhcpRelayAgentOption;
Taras Lemkin96a0d342018-03-26 14:52:58 +000039import org.onlab.util.Tools;
40import org.onosproject.cfg.ComponentConfigService;
Yi Tseng525ff402017-10-23 19:39:39 -070041import org.onosproject.core.ApplicationId;
42import org.onosproject.core.CoreService;
Yi Tseng51301292017-07-28 13:02:59 -070043import org.onosproject.dhcprelay.api.DhcpHandler;
Yi Tseng919b2df2017-09-07 16:22:51 -070044import org.onosproject.dhcprelay.api.DhcpServerInfo;
Yi Tseng483ac6f2017-08-02 15:03:31 -070045import org.onosproject.dhcprelay.config.DhcpServerConfig;
Yi Tseng525ff402017-10-23 19:39:39 -070046import org.onosproject.dhcprelay.config.IgnoreDhcpConfig;
Yi Tseng51301292017-07-28 13:02:59 -070047import org.onosproject.dhcprelay.store.DhcpRecord;
48import org.onosproject.dhcprelay.store.DhcpRelayStore;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070049import org.onosproject.net.ConnectPoint;
Yi Tseng525ff402017-10-23 19:39:39 -070050import org.onosproject.net.Device;
51import org.onosproject.net.DeviceId;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070052import org.onosproject.net.Host;
53import org.onosproject.net.HostId;
54import org.onosproject.net.HostLocation;
Yi Tseng525ff402017-10-23 19:39:39 -070055import org.onosproject.net.behaviour.Pipeliner;
56import org.onosproject.net.device.DeviceService;
57import org.onosproject.net.flow.DefaultTrafficSelector;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070058import org.onosproject.net.flow.DefaultTrafficTreatment;
Yi Tseng525ff402017-10-23 19:39:39 -070059import org.onosproject.net.flow.TrafficSelector;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070060import org.onosproject.net.flow.TrafficTreatment;
Yi Tseng525ff402017-10-23 19:39:39 -070061import org.onosproject.net.flowobjective.DefaultForwardingObjective;
62import org.onosproject.net.flowobjective.FlowObjectiveService;
63import org.onosproject.net.flowobjective.ForwardingObjective;
64import org.onosproject.net.flowobjective.Objective;
65import org.onosproject.net.flowobjective.ObjectiveContext;
66import org.onosproject.net.flowobjective.ObjectiveError;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070067import org.onosproject.net.host.DefaultHostDescription;
68import org.onosproject.net.host.HostDescription;
Yi Tseng483ac6f2017-08-02 15:03:31 -070069import org.onosproject.net.host.HostEvent;
70import org.onosproject.net.host.HostListener;
Yi Tsengaa417a62017-09-08 17:22:51 -070071import org.onosproject.net.host.HostProvider;
72import org.onosproject.net.host.HostProviderRegistry;
73import org.onosproject.net.host.HostProviderService;
Yi Tseng51301292017-07-28 13:02:59 -070074import org.onosproject.net.host.HostService;
Yi Tseng51301292017-07-28 13:02:59 -070075import org.onosproject.net.host.InterfaceIpAddress;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070076import org.onosproject.net.intf.Interface;
77import org.onosproject.net.intf.InterfaceService;
Yi Tseng51301292017-07-28 13:02:59 -070078import org.onosproject.net.packet.DefaultOutboundPacket;
79import org.onosproject.net.packet.OutboundPacket;
80import org.onosproject.net.packet.PacketContext;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070081import org.onosproject.net.packet.PacketPriority;
Yi Tseng51301292017-07-28 13:02:59 -070082import org.onosproject.net.packet.PacketService;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070083import org.onosproject.net.provider.ProviderId;
84import org.onosproject.routeservice.Route;
85import org.onosproject.routeservice.RouteStore;
Taras Lemkin96a0d342018-03-26 14:52:58 +000086import org.osgi.service.component.ComponentContext;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070087import org.osgi.service.component.annotations.Activate;
88import org.osgi.service.component.annotations.Component;
89import org.osgi.service.component.annotations.Deactivate;
90import org.osgi.service.component.annotations.Modified;
91import org.osgi.service.component.annotations.Reference;
92import org.osgi.service.component.annotations.ReferenceCardinality;
Yi Tseng51301292017-07-28 13:02:59 -070093import org.slf4j.Logger;
94import org.slf4j.LoggerFactory;
95
96import java.nio.ByteBuffer;
Taras Lemkin96a0d342018-03-26 14:52:58 +000097import java.util.ArrayList;
Yi Tsengdcef2c22017-08-05 20:34:06 -070098import java.util.Collection;
Yi Tseng51301292017-07-28 13:02:59 -070099import java.util.Collections;
Taras Lemkin96a0d342018-03-26 14:52:58 +0000100import java.util.Dictionary;
Yi Tseng51301292017-07-28 13:02:59 -0700101import java.util.List;
102import java.util.Optional;
103import java.util.Set;
Charles Chan909cff82018-03-05 13:14:02 -0800104import java.util.concurrent.CopyOnWriteArrayList;
Jordan Halterman6328db72018-04-10 13:34:50 -0400105import java.util.concurrent.Executor;
Yi Tseng525ff402017-10-23 19:39:39 -0700106import java.util.concurrent.atomic.AtomicInteger;
Yi Tseng51301292017-07-28 13:02:59 -0700107import java.util.stream.Collectors;
108
109import static com.google.common.base.Preconditions.checkNotNull;
110import static com.google.common.base.Preconditions.checkState;
Jordan Halterman6328db72018-04-10 13:34:50 -0400111import static java.util.concurrent.Executors.newSingleThreadExecutor;
Yi Tseng51301292017-07-28 13:02:59 -0700112import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_CircuitID;
113import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_END;
114import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_MessageType;
115import static org.onlab.packet.MacAddress.valueOf;
116import static org.onlab.packet.dhcp.DhcpRelayAgentOption.RelayAgentInfoOptions.CIRCUIT_ID;
Jordan Halterman6328db72018-04-10 13:34:50 -0400117import static org.onlab.util.Tools.groupedThreads;
Yi Tseng525ff402017-10-23 19:39:39 -0700118import static org.onosproject.net.flowobjective.Objective.Operation.ADD;
119import static org.onosproject.net.flowobjective.Objective.Operation.REMOVE;
Yi Tseng51301292017-07-28 13:02:59 -0700120
rsahot036620655b2018-02-26 15:01:37 -0500121
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700122@Component(service = { DhcpHandler.class, HostProvider.class })
123//@Property(name = "version", value = "4")
Yi Tsengaa417a62017-09-08 17:22:51 -0700124public class Dhcp4HandlerImpl implements DhcpHandler, HostProvider {
Charles Chand988c282017-09-12 17:09:32 -0700125 public static final String DHCP_V4_RELAY_APP = "org.onosproject.Dhcp4HandlerImpl";
126 public static final ProviderId PROVIDER_ID = new ProviderId("dhcp4", DHCP_V4_RELAY_APP);
Yi Tseng525ff402017-10-23 19:39:39 -0700127 private static final String BROADCAST_IP = "255.255.255.255";
128 private static final int IGNORE_CONTROL_PRIORITY = PacketPriority.CONTROL.priorityValue() + 1000;
129
Taras Lemkin96a0d342018-03-26 14:52:58 +0000130 private static final String LQ_ROUTE_PROPERTY_NAME = "learnRouteFromLeasequery";
131
Yi Tseng525ff402017-10-23 19:39:39 -0700132 private static final TrafficSelector CLIENT_SERVER_SELECTOR = DefaultTrafficSelector.builder()
133 .matchEthType(Ethernet.TYPE_IPV4)
134 .matchIPProtocol(IPv4.PROTOCOL_UDP)
135 .matchIPSrc(Ip4Address.ZERO.toIpPrefix())
136 .matchIPDst(Ip4Address.valueOf(BROADCAST_IP).toIpPrefix())
137 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_CLIENT_PORT))
138 .matchUdpDst(TpPort.tpPort(UDP.DHCP_SERVER_PORT))
139 .build();
140 private static final TrafficSelector SERVER_RELAY_SELECTOR = DefaultTrafficSelector.builder()
141 .matchEthType(Ethernet.TYPE_IPV4)
142 .matchIPProtocol(IPv4.PROTOCOL_UDP)
143 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_SERVER_PORT))
144 .matchUdpDst(TpPort.tpPort(UDP.DHCP_SERVER_PORT))
145 .build();
146 static final Set<TrafficSelector> DHCP_SELECTORS = ImmutableSet.of(
147 CLIENT_SERVER_SELECTOR,
148 SERVER_RELAY_SELECTOR
149 );
Yi Tseng51301292017-07-28 13:02:59 -0700150 private static Logger log = LoggerFactory.getLogger(Dhcp4HandlerImpl.class);
151
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700152 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Yi Tseng51301292017-07-28 13:02:59 -0700153 protected DhcpRelayStore dhcpRelayStore;
154
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700155 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Yi Tseng51301292017-07-28 13:02:59 -0700156 protected PacketService packetService;
157
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700158 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Yi Tseng51301292017-07-28 13:02:59 -0700159 protected RouteStore routeStore;
160
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700161 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Yi Tseng51301292017-07-28 13:02:59 -0700162 protected InterfaceService interfaceService;
163
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700164 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Yi Tseng51301292017-07-28 13:02:59 -0700165 protected HostService hostService;
166
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700167 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Yi Tsengaa417a62017-09-08 17:22:51 -0700168 protected HostProviderRegistry providerRegistry;
169
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700170 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Yi Tseng525ff402017-10-23 19:39:39 -0700171 protected CoreService coreService;
172
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700173 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Yi Tseng525ff402017-10-23 19:39:39 -0700174 protected DeviceService deviceService;
175
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700176 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Yi Tseng525ff402017-10-23 19:39:39 -0700177 protected FlowObjectiveService flowObjectiveService;
178
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700179 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Taras Lemkin96a0d342018-03-26 14:52:58 +0000180 protected ComponentConfigService cfgService;
181
Yi Tsengaa417a62017-09-08 17:22:51 -0700182 protected HostProviderService providerService;
Yi Tseng525ff402017-10-23 19:39:39 -0700183 protected ApplicationId appId;
Charles Chan70fdd492018-03-07 17:36:06 -0800184 protected Multimap<DeviceId, VlanId> ignoredVlans = Multimaps.synchronizedMultimap(HashMultimap.create());
Yi Tseng483ac6f2017-08-02 15:03:31 -0700185 private InternalHostListener hostListener = new InternalHostListener();
186
Charles Chan909cff82018-03-05 13:14:02 -0800187 private List<DhcpServerInfo> defaultServerInfoList = new CopyOnWriteArrayList<>();
188 private List<DhcpServerInfo> indirectServerInfoList = new CopyOnWriteArrayList<>();
Taras Lemkin96a0d342018-03-26 14:52:58 +0000189
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700190 //@Property(name = Dhcp4HandlerImpl.LQ_ROUTE_PROPERTY_NAME, boolValue = false,
191 // label = "Enable learning routing information from LQ")
Taras Lemkin96a0d342018-03-26 14:52:58 +0000192 private Boolean learnRouteFromLeasequery = Boolean.TRUE;
Yi Tseng4f2a0462017-08-31 11:21:00 -0700193
Jordan Halterman6328db72018-04-10 13:34:50 -0400194 private Executor hostEventExecutor = newSingleThreadExecutor(
195 groupedThreads("dhcp4-event-host", "%d", log));
196
Yi Tseng483ac6f2017-08-02 15:03:31 -0700197 @Activate
Taras Lemkin96a0d342018-03-26 14:52:58 +0000198 protected void activate(ComponentContext context) {
199 cfgService.registerProperties(getClass());
200 modified(context);
Yi Tseng525ff402017-10-23 19:39:39 -0700201 appId = coreService.registerApplication(DHCP_V4_RELAY_APP);
Yi Tseng483ac6f2017-08-02 15:03:31 -0700202 hostService.addListener(hostListener);
Yi Tsengaa417a62017-09-08 17:22:51 -0700203 providerService = providerRegistry.register(this);
Yi Tseng483ac6f2017-08-02 15:03:31 -0700204 }
205
206 @Deactivate
207 protected void deactivate() {
Taras Lemkin96a0d342018-03-26 14:52:58 +0000208 cfgService.unregisterProperties(getClass(), false);
Yi Tsengaa417a62017-09-08 17:22:51 -0700209 providerRegistry.unregister(this);
210 hostService.removeListener(hostListener);
Yi Tseng919b2df2017-09-07 16:22:51 -0700211 defaultServerInfoList.forEach(this::stopMonitoringIps);
Charles Chanfc1c22e2018-07-19 09:52:01 -0700212 defaultServerInfoList.forEach(info -> info.getDhcpServerIp4().ifPresent(this::cancelDhcpPacket));
Yi Tseng919b2df2017-09-07 16:22:51 -0700213 defaultServerInfoList.clear();
214 indirectServerInfoList.forEach(this::stopMonitoringIps);
Charles Chanfc1c22e2018-07-19 09:52:01 -0700215 indirectServerInfoList.forEach(info -> info.getDhcpServerIp4().ifPresent(this::cancelDhcpPacket));
Yi Tseng919b2df2017-09-07 16:22:51 -0700216 indirectServerInfoList.clear();
Yi Tseng483ac6f2017-08-02 15:03:31 -0700217 }
218
Taras Lemkin96a0d342018-03-26 14:52:58 +0000219 @Modified
220 protected void modified(ComponentContext context) {
221 Dictionary<?, ?> properties = context.getProperties();
222 Boolean flag;
223 flag = Tools.isPropertyEnabled(properties, Dhcp4HandlerImpl.LQ_ROUTE_PROPERTY_NAME);
224 if (flag != null) {
225 learnRouteFromLeasequery = flag;
226 log.info("Learning routes from DHCP leasequery is {}",
227 learnRouteFromLeasequery ? "enabled" : "disabled");
228 }
229 }
230
Yi Tseng919b2df2017-09-07 16:22:51 -0700231 private void stopMonitoringIps(DhcpServerInfo serverInfo) {
232 serverInfo.getDhcpGatewayIp4().ifPresent(gatewayIp -> {
233 hostService.stopMonitoringIp(gatewayIp);
234 });
235 serverInfo.getDhcpServerIp4().ifPresent(serverIp -> {
236 hostService.stopMonitoringIp(serverIp);
237 });
Yi Tseng51301292017-07-28 13:02:59 -0700238 }
239
240 @Override
Yi Tseng483ac6f2017-08-02 15:03:31 -0700241 public void setDefaultDhcpServerConfigs(Collection<DhcpServerConfig> configs) {
Yi Tseng919b2df2017-09-07 16:22:51 -0700242 setDhcpServerConfigs(configs, defaultServerInfoList);
243 }
244
245 @Override
246 public void setIndirectDhcpServerConfigs(Collection<DhcpServerConfig> configs) {
247 setDhcpServerConfigs(configs, indirectServerInfoList);
248 }
249
250 @Override
251 public List<DhcpServerInfo> getDefaultDhcpServerInfoList() {
252 return defaultServerInfoList;
253 }
254
255 @Override
256 public List<DhcpServerInfo> getIndirectDhcpServerInfoList() {
257 return indirectServerInfoList;
258 }
259
Yi Tseng525ff402017-10-23 19:39:39 -0700260 @Override
261 public void updateIgnoreVlanConfig(IgnoreDhcpConfig config) {
262 if (config == null) {
263 ignoredVlans.forEach(((deviceId, vlanId) -> {
264 processIgnoreVlanRule(deviceId, vlanId, REMOVE);
265 }));
266 return;
267 }
268 config.ignoredVlans().forEach((deviceId, vlanId) -> {
269 if (ignoredVlans.get(deviceId).contains(vlanId)) {
270 // don't need to process if it already ignored
271 return;
272 }
273 processIgnoreVlanRule(deviceId, vlanId, ADD);
274 });
275
276 ignoredVlans.forEach((deviceId, vlanId) -> {
277 if (!config.ignoredVlans().get(deviceId).contains(vlanId)) {
278 // not contains in new config, remove it
279 processIgnoreVlanRule(deviceId, vlanId, REMOVE);
280 }
281 });
282 }
283
Saurav Dasb805f1a2017-12-13 16:19:35 -0800284 @Override
285 public void removeIgnoreVlanState(IgnoreDhcpConfig config) {
286 if (config == null) {
287 ignoredVlans.clear();
288 return;
289 }
290 config.ignoredVlans().forEach((deviceId, vlanId) -> {
291 ignoredVlans.remove(deviceId, vlanId);
292 });
293 }
294
Yi Tseng919b2df2017-09-07 16:22:51 -0700295 public void setDhcpServerConfigs(Collection<DhcpServerConfig> configs, List<DhcpServerInfo> serverInfoList) {
Yi Tseng483ac6f2017-08-02 15:03:31 -0700296 if (configs.size() == 0) {
297 // no config to update
298 return;
299 }
300
rsahot036620655b2018-02-26 15:01:37 -0500301 Boolean isConfigValid = false;
302 for (DhcpServerConfig serverConfig : configs) {
303 if (serverConfig.getDhcpServerIp4().isPresent()) {
304 isConfigValid = true;
305 break;
306 }
Yi Tseng483ac6f2017-08-02 15:03:31 -0700307 }
rsahot036620655b2018-02-26 15:01:37 -0500308 if (!isConfigValid) {
309 log.warn("No IP V4 server address found.");
310 return; // No IP V6 address found
311 }
312 // if (!serverInfoList.isEmpty()) {
313 for (DhcpServerInfo oldServerInfo : serverInfoList) {
314 log.info("In for (DhcpServerInfo oldServerInfo : serverInfoList) {");
Yi Tseng919b2df2017-09-07 16:22:51 -0700315 // remove old server info
rsahot036620655b2018-02-26 15:01:37 -0500316 //DhcpServerInfo oldServerInfo = serverInfoList.remove(0);
Yi Tseng483ac6f2017-08-02 15:03:31 -0700317
Yi Tseng919b2df2017-09-07 16:22:51 -0700318 // stop monitoring gateway or server
319 oldServerInfo.getDhcpGatewayIp4().ifPresent(gatewayIp -> {
320 hostService.stopMonitoringIp(gatewayIp);
321 });
322 oldServerInfo.getDhcpServerIp4().ifPresent(serverIp -> {
323 hostService.stopMonitoringIp(serverIp);
Yi Tseng525ff402017-10-23 19:39:39 -0700324 cancelDhcpPacket(serverIp);
Yi Tseng919b2df2017-09-07 16:22:51 -0700325 });
Yi Tseng483ac6f2017-08-02 15:03:31 -0700326 }
Yi Tseng3df7f9d2017-08-17 13:08:31 -0700327
Yi Tseng919b2df2017-09-07 16:22:51 -0700328 // Create new server info according to the config
rsahot036620655b2018-02-26 15:01:37 -0500329 serverInfoList.clear();
330 for (DhcpServerConfig serverConfig : configs) {
Taras Lemkin96a0d342018-03-26 14:52:58 +0000331 log.debug("Create new server info according to the config");
rsahot036620655b2018-02-26 15:01:37 -0500332 DhcpServerInfo newServerInfo = new DhcpServerInfo(serverConfig,
333 DhcpServerInfo.Version.DHCP_V4);
334 checkState(newServerInfo.getDhcpServerConnectPoint().isPresent(),
335 "Connect point not exists");
336 checkState(newServerInfo.getDhcpServerIp4().isPresent(),
337 "IP of DHCP server not exists");
Yi Tseng4f2a0462017-08-31 11:21:00 -0700338
rsahot036620655b2018-02-26 15:01:37 -0500339 log.debug("DHCP server connect point: {}", newServerInfo.getDhcpServerConnectPoint().orElse(null));
340 log.debug("DHCP server IP: {}", newServerInfo.getDhcpServerIp4().orElse(null));
Yi Tseng919b2df2017-09-07 16:22:51 -0700341
rsahot036620655b2018-02-26 15:01:37 -0500342 Ip4Address serverIp = newServerInfo.getDhcpServerIp4().get();
343 Ip4Address ipToProbe;
344 if (newServerInfo.getDhcpGatewayIp4().isPresent()) {
345 ipToProbe = newServerInfo.getDhcpGatewayIp4().get();
346 } else {
347 ipToProbe = newServerInfo.getDhcpServerIp4().orElse(null);
348 }
349 log.info("Probe_IP {}", ipToProbe);
350 String hostToProbe = newServerInfo.getDhcpGatewayIp4()
351 .map(ip -> "gateway").orElse("server");
352
353 log.debug("Probing to resolve {} IP {}", hostToProbe, ipToProbe);
354 hostService.startMonitoringIp(ipToProbe);
355
356 Set<Host> hosts = hostService.getHostsByIp(ipToProbe);
357 if (!hosts.isEmpty()) {
358 Host host = hosts.iterator().next();
359 newServerInfo.setDhcpConnectVlan(host.vlan());
360 newServerInfo.setDhcpConnectMac(host.mac());
361 }
362
363 // Add new server info
364 synchronized (this) {
365 //serverInfoList.clear();
366 serverInfoList.add(newServerInfo);
367 }
368
369 requestDhcpPacket(serverIp);
Yi Tseng4f2a0462017-08-31 11:21:00 -0700370 }
Yi Tseng483ac6f2017-08-02 15:03:31 -0700371 }
372
Yi Tseng3df7f9d2017-08-17 13:08:31 -0700373 @Override
Yi Tseng51301292017-07-28 13:02:59 -0700374 public void processDhcpPacket(PacketContext context, BasePacket payload) {
375 checkNotNull(payload, "DHCP payload can't be null");
376 checkState(payload instanceof DHCP, "Payload is not a DHCP");
377 DHCP dhcpPayload = (DHCP) payload;
378 if (!configured()) {
Yi Tseng919b2df2017-09-07 16:22:51 -0700379 log.warn("Missing default DHCP relay server config. Abort packet processing");
Yi Tseng51301292017-07-28 13:02:59 -0700380 return;
381 }
382
383 ConnectPoint inPort = context.inPacket().receivedFrom();
Yi Tseng51301292017-07-28 13:02:59 -0700384 checkNotNull(dhcpPayload, "Can't find DHCP payload");
385 Ethernet packet = context.inPacket().parsed();
386 DHCP.MsgType incomingPacketType = dhcpPayload.getOptions().stream()
387 .filter(dhcpOption -> dhcpOption.getCode() == OptionCode_MessageType.getValue())
388 .map(DhcpOption::getData)
389 .map(data -> DHCP.MsgType.getType(data[0]))
390 .findFirst()
391 .orElse(null);
392 checkNotNull(incomingPacketType, "Can't get message type from DHCP payload {}", dhcpPayload);
rsahot036620655b2018-02-26 15:01:37 -0500393 Set<Interface> receivingInterfaces = interfaceService.getInterfacesByPort(inPort);
394 //ignore the packets if dhcp client interface is not configured on onos.
395 if (receivingInterfaces.isEmpty()) {
396 log.warn("Virtual interface is not configured on {}", inPort);
397 return;
398 }
Yi Tseng51301292017-07-28 13:02:59 -0700399 switch (incomingPacketType) {
400 case DHCPDISCOVER:
Yi Tsengdcef2c22017-08-05 20:34:06 -0700401 // Add the gateway IP as virtual interface IP for server to understand
Yi Tseng51301292017-07-28 13:02:59 -0700402 // the lease to be assigned and forward the packet to dhcp server.
rsahot036620655b2018-02-26 15:01:37 -0500403 List<InternalPacket> ethernetClientPacket =
404 processDhcpPacketFromClient(context, packet, receivingInterfaces);
405 for (InternalPacket internalPacket : ethernetClientPacket) {
406 log.debug("DHCPDISCOVER from {} Forward to server", inPort);
Yi Tseng51301292017-07-28 13:02:59 -0700407 writeRequestDhcpRecord(inPort, packet, dhcpPayload);
rsahot036620655b2018-02-26 15:01:37 -0500408 forwardPacket(internalPacket);
Yi Tseng51301292017-07-28 13:02:59 -0700409 }
410 break;
411 case DHCPOFFER:
412 //reply to dhcp client.
Taras Lemkin96a0d342018-03-26 14:52:58 +0000413 InternalPacket ethernetPacketOffer = processDhcpPacketFromServer(context, packet);
Yi Tseng51301292017-07-28 13:02:59 -0700414 if (ethernetPacketOffer != null) {
Taras Lemkin96a0d342018-03-26 14:52:58 +0000415 writeResponseDhcpRecord(ethernetPacketOffer.getPacket(), dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -0700416 sendResponseToClient(ethernetPacketOffer, dhcpPayload);
Yi Tseng51301292017-07-28 13:02:59 -0700417 }
418 break;
419 case DHCPREQUEST:
420 // add the gateway ip as virtual interface ip for server to understand
421 // the lease to be assigned and forward the packet to dhcp server.
rsahot036620655b2018-02-26 15:01:37 -0500422 List<InternalPacket> ethernetPacketRequest =
423 processDhcpPacketFromClient(context, packet, receivingInterfaces);
424 for (InternalPacket internalPacket : ethernetPacketRequest) {
425 log.debug("DHCPDISCOVER from {} Forward to server", inPort);
Yi Tseng51301292017-07-28 13:02:59 -0700426 writeRequestDhcpRecord(inPort, packet, dhcpPayload);
rsahot036620655b2018-02-26 15:01:37 -0500427 forwardPacket(internalPacket);
Yi Tseng51301292017-07-28 13:02:59 -0700428 }
429 break;
Charles Chand0dd7002017-10-08 23:53:36 -0400430 case DHCPDECLINE:
431 break;
Yi Tseng51301292017-07-28 13:02:59 -0700432 case DHCPACK:
433 // reply to dhcp client.
Taras Lemkin96a0d342018-03-26 14:52:58 +0000434 InternalPacket ethernetPacketAck = processDhcpPacketFromServer(context, packet);
Yi Tseng51301292017-07-28 13:02:59 -0700435 if (ethernetPacketAck != null) {
Taras Lemkin96a0d342018-03-26 14:52:58 +0000436 writeResponseDhcpRecord(ethernetPacketAck.getPacket(), dhcpPayload);
437 handleDhcpAck(ethernetPacketAck.getPacket(), dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -0700438 sendResponseToClient(ethernetPacketAck, dhcpPayload);
Yi Tseng51301292017-07-28 13:02:59 -0700439 }
440 break;
Charles Chand0dd7002017-10-08 23:53:36 -0400441 case DHCPNAK:
442 break;
Yi Tseng51301292017-07-28 13:02:59 -0700443 case DHCPRELEASE:
444 // TODO: release the ip address from client
445 break;
Charles Chand0dd7002017-10-08 23:53:36 -0400446 case DHCPINFORM:
447 break;
448 case DHCPFORCERENEW:
449 break;
450 case DHCPLEASEQUERY:
451 handleLeaseQueryMsg(context, packet, dhcpPayload);
452 break;
453 case DHCPLEASEACTIVE:
454 handleLeaseQueryActivateMsg(packet, dhcpPayload);
455 break;
456 case DHCPLEASEUNASSIGNED:
457 case DHCPLEASEUNKNOWN:
458 handleLeaseQueryUnknown(packet, dhcpPayload);
459 break;
Yi Tseng51301292017-07-28 13:02:59 -0700460 default:
461 break;
462 }
463 }
464
465 /**
466 * Checks if this app has been configured.
467 *
468 * @return true if all information we need have been initialized
469 */
Yi Tseng4f2a0462017-08-31 11:21:00 -0700470 private boolean configured() {
Yi Tseng919b2df2017-09-07 16:22:51 -0700471 return !defaultServerInfoList.isEmpty();
Yi Tseng51301292017-07-28 13:02:59 -0700472 }
473
474 /**
Yi Tsengdcef2c22017-08-05 20:34:06 -0700475 * Returns the first interface ip from interface.
Yi Tseng51301292017-07-28 13:02:59 -0700476 *
Yi Tsengdcef2c22017-08-05 20:34:06 -0700477 * @param iface interface of one connect point
Yi Tseng51301292017-07-28 13:02:59 -0700478 * @return the first interface IP; null if not exists an IP address in
479 * these interfaces
480 */
Yi Tseng3df7f9d2017-08-17 13:08:31 -0700481 private Ip4Address getFirstIpFromInterface(Interface iface) {
Yi Tsengdcef2c22017-08-05 20:34:06 -0700482 checkNotNull(iface, "Interface can't be null");
483 return iface.ipAddressesList().stream()
Yi Tseng51301292017-07-28 13:02:59 -0700484 .map(InterfaceIpAddress::ipAddress)
485 .filter(IpAddress::isIp4)
486 .map(IpAddress::getIp4Address)
487 .findFirst()
488 .orElse(null);
489 }
490
491 /**
Yi Tseng4f2a0462017-08-31 11:21:00 -0700492 * Gets Interface facing to the server for default host.
Yi Tsengdcef2c22017-08-05 20:34:06 -0700493 *
494 * @return the Interface facing to the server; null if not found
495 */
Yi Tseng919b2df2017-09-07 16:22:51 -0700496 private Interface getDefaultServerInterface() {
497 return getServerInterface(defaultServerInfoList);
Yi Tsengdcef2c22017-08-05 20:34:06 -0700498 }
499
500 /**
Yi Tseng4f2a0462017-08-31 11:21:00 -0700501 * Gets Interface facing to the server for indirect hosts.
502 * Use default server Interface if indirect server not configured.
503 *
504 * @return the Interface facing to the server; null if not found
505 */
506 private Interface getIndirectServerInterface() {
Yi Tseng919b2df2017-09-07 16:22:51 -0700507 return getServerInterface(indirectServerInfoList);
508 }
509
510 private Interface getServerInterface(List<DhcpServerInfo> serverInfos) {
Yi Tseng3bd57ac2017-11-29 14:39:18 -0800511 return serverInfos.stream()
Yi Tseng4f2a0462017-08-31 11:21:00 -0700512 .findFirst()
Yi Tseng3bd57ac2017-11-29 14:39:18 -0800513 .map(serverInfo -> {
514 ConnectPoint dhcpServerConnectPoint =
515 serverInfo.getDhcpServerConnectPoint().orElse(null);
516 VlanId dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
517 if (dhcpServerConnectPoint == null || dhcpConnectVlan == null) {
518 return null;
519 }
520 return interfaceService.getInterfacesByPort(dhcpServerConnectPoint)
521 .stream()
522 .filter(iface -> interfaceContainsVlan(iface, dhcpConnectVlan))
523 .findFirst()
524 .orElse(null);
525 })
Yi Tseng4f2a0462017-08-31 11:21:00 -0700526 .orElse(null);
527 }
528
529 /**
530 * Determind if an Interface contains a vlan id.
531 *
532 * @param iface the Interface
533 * @param vlanId the vlan id
534 * @return true if the Interface contains the vlan id
535 */
536 private boolean interfaceContainsVlan(Interface iface, VlanId vlanId) {
Yi Tseng4025a102017-09-30 11:35:42 +0800537 if (vlanId.equals(VlanId.NONE)) {
538 // untagged packet, check if vlan untagged or vlan native is not NONE
539 return !iface.vlanUntagged().equals(VlanId.NONE) ||
540 !iface.vlanNative().equals(VlanId.NONE);
541 }
542 // tagged packet, check if the interface contains the vlan
543 return iface.vlanTagged().contains(vlanId);
Yi Tseng4f2a0462017-08-31 11:21:00 -0700544 }
545
Charles Chand0dd7002017-10-08 23:53:36 -0400546 private void handleLeaseQueryActivateMsg(Ethernet packet, DHCP dhcpPayload) {
547 log.debug("LQ: Got DHCPLEASEACTIVE packet!");
548
Taras Lemkin96a0d342018-03-26 14:52:58 +0000549 if (learnRouteFromLeasequery) {
550 // TODO: release the ip address from client
551 MacAddress clientMacAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
552 VlanId vlanId = VlanId.vlanId(packet.getVlanID());
553 HostId hostId = HostId.hostId(clientMacAddress, vlanId);
554 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
Charles Chand0dd7002017-10-08 23:53:36 -0400555
Taras Lemkin96a0d342018-03-26 14:52:58 +0000556 if (record == null) {
557 log.warn("Can't find record for host {} when processing DHCPLEASEACTIVE", hostId);
558 return;
559 }
560
561 // need to update routes
562 log.debug("Lease Query for Client results in DHCPLEASEACTIVE - route needs to be modified");
563 // get current route
564 // find the ip of that client with the DhcpRelay store
565
566 Ip4Address clientIP = record.ip4Address().orElse(null);
567 log.debug("LQ: IP of host is " + clientIP.getIp4Address());
568
569 MacAddress nextHopMac = record.nextHop().orElse(null);
570 log.debug("LQ: MAC of resulting *OLD* NH for that host is " + nextHopMac.toString());
571
572 // find the new NH by looking at the src MAC of the dhcp request
573 // from the LQ store
574 MacAddress newNextHopMac = record.nextHopTemp().orElse(null);
575 log.debug("LQ: MAC of resulting *NEW* NH for that host is " + newNextHopMac.toString());
576
577 log.debug("LQ: updating dhcp relay record with new NH");
578 record.nextHop(newNextHopMac);
579
580 // find the next hop IP from its mac
581 HostId gwHostId = HostId.hostId(newNextHopMac, vlanId);
582 Host gwHost = hostService.getHost(gwHostId);
583
584 if (gwHost == null) {
585 log.warn("Can't find gateway for new NH host " + gwHostId);
586 return;
587 }
588
589 Ip4Address nextHopIp = gwHost.ipAddresses()
590 .stream()
591 .filter(IpAddress::isIp4)
592 .map(IpAddress::getIp4Address)
593 .findFirst()
594 .orElse(null);
595
596 if (nextHopIp == null) {
597 log.warn("Can't find IP address of gateway " + gwHost);
598 return;
599 }
600
601 log.debug("LQ: *NEW* NH IP for host is " + nextHopIp.getIp4Address());
602 Route route = new Route(Route.Source.DHCP, clientIP.toIpPrefix(), nextHopIp);
603 routeStore.updateRoute(route);
Charles Chand0dd7002017-10-08 23:53:36 -0400604 }
605
Charles Chand0dd7002017-10-08 23:53:36 -0400606 // and forward to client
Taras Lemkin96a0d342018-03-26 14:52:58 +0000607 InternalPacket ethernetPacket = processLeaseQueryFromServer(packet);
Charles Chand0dd7002017-10-08 23:53:36 -0400608 if (ethernetPacket != null) {
609 sendResponseToClient(ethernetPacket, dhcpPayload);
610 }
611 }
612
Charles Chand0dd7002017-10-08 23:53:36 -0400613 private void handleLeaseQueryMsg(PacketContext context, Ethernet packet, DHCP dhcpPayload) {
Taras Lemkin96a0d342018-03-26 14:52:58 +0000614 // If this flag is enabled we expect that DHCPLEASEQUERY-ies are sent from an access concentrator
615 // where queried client is connected to. Otherwise, DHCPLEASEQUERY source may be a separate connected agent
616 if (learnRouteFromLeasequery) {
617 log.debug("LQ: Got DHCPLEASEQUERY packet!");
618 MacAddress clientMacAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
619 log.debug("LQ: got DHCPLEASEQUERY with MAC " + clientMacAddress.toString());
620 // add the client mac (hostid) of this request to a store (the entry will be removed with
621 // the reply sent to the originator)
622 VlanId vlanId = VlanId.vlanId(packet.getVlanID());
623 HostId hId = HostId.hostId(clientMacAddress, vlanId);
624 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hId).orElse(null);
625 if (record != null) {
626 //new NH is to be taken from src mac of LQ packet
627 MacAddress newNextHop = packet.getSourceMAC();
628 record.nextHopTemp(newNextHop);
629 record.ip4Status(dhcpPayload.getPacketType());
630 record.updateLastSeen();
631
632 // do a basic routing of the packet (this is unicast routing
633 // not a relay operation like for other broadcast dhcp packets
634 List<InternalPacket> ethernetPacketRequest = processLeaseQueryFromAgent(context, packet);
635 // and forward to server
636 for (InternalPacket internalPacket : ethernetPacketRequest) {
637 log.debug("LeaseQueryMsg forward to server");
638 forwardPacket(internalPacket);
639 }
640 } else {
641 log.warn("LQ: Error! - DHCP relay record for that client not found - ignoring LQ!");
642 }
643 } else {
644 log.debug("LQ: Got DHCPLEASEQUERY packet!");
645
646 int giaddr = dhcpPayload.getGatewayIPAddress();
647
648 log.debug("DHCPLEASEQUERY giaddr: {} ({}). Originators connectPoint: {}", giaddr,
649 Ip4Address.valueOf(giaddr), context.inPacket().receivedFrom());
Charles Chand0dd7002017-10-08 23:53:36 -0400650
651 // do a basic routing of the packet (this is unicast routing
652 // not a relay operation like for other broadcast dhcp packets
rsahot036620655b2018-02-26 15:01:37 -0500653 List<InternalPacket> ethernetPacketRequest = processLeaseQueryFromAgent(context, packet);
Charles Chand0dd7002017-10-08 23:53:36 -0400654 // and forward to server
rsahot036620655b2018-02-26 15:01:37 -0500655 for (InternalPacket internalPacket : ethernetPacketRequest) {
Taras Lemkin96a0d342018-03-26 14:52:58 +0000656 log.trace("LeaseQueryMsg forward to server connected to {}", internalPacket.getDestLocation());
rsahot036620655b2018-02-26 15:01:37 -0500657 forwardPacket(internalPacket);
658 }
Charles Chand0dd7002017-10-08 23:53:36 -0400659 }
660 }
661
662 private void handleLeaseQueryUnknown(Ethernet packet, DHCP dhcpPayload) {
663 log.debug("Lease Query for Client results in DHCPLEASEUNASSIGNED or " +
664 "DHCPLEASEUNKNOWN - removing route & forwarding reply to originator");
Taras Lemkin96a0d342018-03-26 14:52:58 +0000665 if (learnRouteFromLeasequery) {
666 MacAddress clientMacAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
667 VlanId vlanId = VlanId.vlanId(packet.getVlanID());
668 HostId hostId = HostId.hostId(clientMacAddress, vlanId);
669 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
Charles Chand0dd7002017-10-08 23:53:36 -0400670
Taras Lemkin96a0d342018-03-26 14:52:58 +0000671 if (record == null) {
672 log.warn("Can't find record for host {} when handling LQ UNKNOWN/UNASSIGNED message", hostId);
673 return;
674 }
675
676 Ip4Address clientIP = record.ip4Address().orElse(null);
677 log.debug("LQ: IP of host is " + clientIP.getIp4Address());
678
679 // find the new NH by looking at the src MAC of the dhcp request
680 // from the LQ store
681 MacAddress nextHopMac = record.nextHop().orElse(null);
682 log.debug("LQ: MAC of resulting *Existing* NH for that route is " + nextHopMac.toString());
683
684 // find the next hop IP from its mac
685 HostId gwHostId = HostId.hostId(nextHopMac, vlanId);
686 Host gwHost = hostService.getHost(gwHostId);
687
688 if (gwHost == null) {
689 log.warn("Can't find gateway for new NH host " + gwHostId);
690 return;
691 }
692
693 Ip4Address nextHopIp = gwHost.ipAddresses()
694 .stream()
695 .filter(IpAddress::isIp4)
696 .map(IpAddress::getIp4Address)
697 .findFirst()
698 .orElse(null);
699
700 if (nextHopIp == null) {
701 log.warn("Can't find IP address of gateway {}", gwHost);
702 return;
703 }
704
705 log.debug("LQ: *Existing* NH IP for host is " + nextHopIp.getIp4Address() + " removing route for it");
706 Route route = new Route(Route.Source.DHCP, clientIP.toIpPrefix(), nextHopIp);
707 routeStore.removeRoute(route);
708
709 // remove from temp store
710 dhcpRelayStore.removeDhcpRecord(hostId);
Charles Chand0dd7002017-10-08 23:53:36 -0400711 }
Charles Chand0dd7002017-10-08 23:53:36 -0400712 // and forward to client
Taras Lemkin96a0d342018-03-26 14:52:58 +0000713 InternalPacket ethernetPacket = processLeaseQueryFromServer(packet);
Charles Chand0dd7002017-10-08 23:53:36 -0400714 if (ethernetPacket != null) {
715 sendResponseToClient(ethernetPacket, dhcpPayload);
716 }
717 }
718
Yi Tseng4f2a0462017-08-31 11:21:00 -0700719 /**
Yi Tseng51301292017-07-28 13:02:59 -0700720 * Build the DHCP discover/request packet with gateway IP(unicast packet).
721 *
722 * @param context the packet context
723 * @param ethernetPacket the ethernet payload to process
Yi Tseng51301292017-07-28 13:02:59 -0700724 * @return processed packet
725 */
rsahot036620655b2018-02-26 15:01:37 -0500726 private List<InternalPacket> processDhcpPacketFromClient(PacketContext context,
727 Ethernet ethernetPacket,
728 Set<Interface> clientInterfaces) {
Yi Tseng25bfe372017-11-03 16:27:32 -0700729 ConnectPoint receivedFrom = context.inPacket().receivedFrom();
730 DeviceId receivedFromDevice = receivedFrom.deviceId();
rsahot036620655b2018-02-26 15:01:37 -0500731 Ip4Address relayAgentIp = null;
Taras Lemkin96a0d342018-03-26 14:52:58 +0000732 relayAgentIp = Dhcp4HandlerUtil.getRelayAgentIPv4Address(clientInterfaces);
rsahot036620655b2018-02-26 15:01:37 -0500733 MacAddress relayAgentMac = clientInterfaces.iterator().next().mac();
734 if (relayAgentIp == null || relayAgentMac == null) {
735 log.warn("Missing DHCP relay agent interface Ipv4 addr config for "
736 + "packet from client on port: {}. Aborting packet processing",
737 clientInterfaces.iterator().next().connectPoint());
Charles Chane5e0c9a2018-03-30 12:11:34 -0700738 return Lists.newArrayList();
rsahot036620655b2018-02-26 15:01:37 -0500739 }
740 log.debug("Multi DHCP V4 processDhcpPacketFromClient on port {}",
741 clientInterfaces.iterator().next().connectPoint());
Yi Tseng25bfe372017-11-03 16:27:32 -0700742
Yi Tseng4f2a0462017-08-31 11:21:00 -0700743 // get dhcp header.
rsahot036620655b2018-02-26 15:01:37 -0500744 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
Yi Tseng4f2a0462017-08-31 11:21:00 -0700745 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
746 UDP udpPacket = (UDP) ipv4Packet.getPayload();
747 DHCP dhcpPacket = (DHCP) udpPacket.getPayload();
748
Yi Tseng919b2df2017-09-07 16:22:51 -0700749
Yi Tsengdcef2c22017-08-05 20:34:06 -0700750 Ip4Address clientInterfaceIp =
751 interfaceService.getInterfacesByPort(context.inPacket().receivedFrom())
752 .stream()
753 .map(Interface::ipAddressesList)
754 .flatMap(Collection::stream)
755 .map(InterfaceIpAddress::ipAddress)
756 .filter(IpAddress::isIp4)
757 .map(IpAddress::getIp4Address)
758 .findFirst()
759 .orElse(null);
760 if (clientInterfaceIp == null) {
761 log.warn("Can't find interface IP for client interface for port {}",
rsahot036620655b2018-02-26 15:01:37 -0500762 context.inPacket().receivedFrom());
Charles Chane5e0c9a2018-03-30 12:11:34 -0700763 return Lists.newArrayList();
Yi Tsengdcef2c22017-08-05 20:34:06 -0700764 }
rsahot036620655b2018-02-26 15:01:37 -0500765
Yi Tseng4f2a0462017-08-31 11:21:00 -0700766 boolean isDirectlyConnected = directlyConnected(dhcpPacket);
rsahot036620655b2018-02-26 15:01:37 -0500767 boolean directConnFlag = directlyConnected(dhcpPacket);
768
769 // Multi DHCP Start
770 ConnectPoint clientConnectionPoint = context.inPacket().receivedFrom();
771 VlanId vlanIdInUse = VlanId.vlanId(ethernetPacket.getVlanID());
772 Interface clientInterface = interfaceService.getInterfacesByPort(clientConnectionPoint)
Taras Lemkin96a0d342018-03-26 14:52:58 +0000773 .stream().filter(iface -> Dhcp4HandlerUtil.interfaceContainsVlan(iface, vlanIdInUse))
rsahot036620655b2018-02-26 15:01:37 -0500774 .findFirst()
775 .orElse(null);
776
777 List<InternalPacket> internalPackets = new ArrayList<>();
778 List<DhcpServerInfo> serverInfoList = findValidServerInfo(directConnFlag);
779 List<DhcpServerInfo> copyServerInfoList = new ArrayList<DhcpServerInfo>(serverInfoList);
780
781
782 for (DhcpServerInfo serverInfo : copyServerInfoList) {
783 etherReply = (Ethernet) ethernetPacket.clone();
Taras Lemkin96a0d342018-03-26 14:52:58 +0000784 ipv4Packet = (IPv4) etherReply.getPayload();
785 udpPacket = (UDP) ipv4Packet.getPayload();
786 dhcpPacket = (DHCP) udpPacket.getPayload();
rsahot036620655b2018-02-26 15:01:37 -0500787 if (!checkDhcpServerConnPt(directConnFlag, serverInfo)) {
788 log.warn("Can't get server connect point, ignore");
789 continue;
790 }
791 DhcpServerInfo newServerInfo = getHostInfoForServerInfo(serverInfo, serverInfoList);
792 if (newServerInfo == null) {
793 log.warn("Can't get server interface with host info resolved, ignore");
794 continue;
795 }
796
797 Interface serverInterface = getServerInterface(newServerInfo);
Yi Tseng3bd57ac2017-11-29 14:39:18 -0800798 if (serverInterface == null) {
rsahot036620655b2018-02-26 15:01:37 -0500799 log.warn("Can't get server interface, ignore");
800 continue;
Yi Tseng3bd57ac2017-11-29 14:39:18 -0800801 }
Yi Tseng4f2a0462017-08-31 11:21:00 -0700802
rsahot036620655b2018-02-26 15:01:37 -0500803 Ip4Address ipFacingServer = getFirstIpFromInterface(serverInterface);
804 MacAddress macFacingServer = serverInterface.mac();
805 log.debug("Interfacing server {} Mac : {} ", ipFacingServer, macFacingServer);
806 if (ipFacingServer == null || macFacingServer == null) {
807 log.warn("No IP address for server Interface {}", serverInterface);
rsahot036620655b2018-02-26 15:01:37 -0500808 continue;
809 }
Yi Tseng51301292017-07-28 13:02:59 -0700810
Charles Chand0d1e332017-10-10 16:53:32 -0400811
rsahot036620655b2018-02-26 15:01:37 -0500812 etherReply.setSourceMACAddress(macFacingServer);
813 // set default info and replace with indirect if available later on.
814 if (newServerInfo.getDhcpConnectMac().isPresent()) {
815 etherReply.setDestinationMACAddress(newServerInfo.getDhcpConnectMac().get());
816 }
817 if (newServerInfo.getDhcpConnectVlan().isPresent()) {
818 etherReply.setVlanID(newServerInfo.getDhcpConnectVlan().get().toShort());
819 }
820 ipv4Packet.setSourceAddress(ipFacingServer.toInt());
821 ipv4Packet.setDestinationAddress(newServerInfo.getDhcpServerIp4().get().toInt());
Charles Chan2de55302018-03-02 18:27:59 -0800822 log.debug("Directly connected {}", isDirectlyConnected);
823 log.debug("DHCP server IP: {}", newServerInfo.getDhcpServerIp4().get());
rsahot036620655b2018-02-26 15:01:37 -0500824 if (isDirectlyConnected) {
Yi Tseng51301292017-07-28 13:02:59 -0700825
Charles Chan2de55302018-03-02 18:27:59 -0800826 log.debug("Default DHCP server IP: {}", newServerInfo.getDhcpServerIp4().get());
rsahot036620655b2018-02-26 15:01:37 -0500827 if (newServerInfo.getDhcpConnectMac().isPresent()) {
828 etherReply.setDestinationMACAddress(newServerInfo.getDhcpConnectMac().get());
Charles Chand0d1e332017-10-10 16:53:32 -0400829 }
rsahot036620655b2018-02-26 15:01:37 -0500830 if (newServerInfo.getDhcpConnectVlan().isPresent()) {
831 etherReply.setVlanID(newServerInfo.getDhcpConnectVlan().get().toShort());
832 }
833
834 ipv4Packet.setDestinationAddress(newServerInfo.getDhcpServerIp4().get().toInt());
835
836
837 ConnectPoint inPort = context.inPacket().receivedFrom();
838 VlanId vlanId = VlanId.vlanId(ethernetPacket.getVlanID());
839 // add connected in port and vlan
840 CircuitId cid = new CircuitId(inPort.toString(), vlanId);
841 byte[] circuitId = cid.serialize();
842 DhcpOption circuitIdSubOpt = new DhcpOption();
843 circuitIdSubOpt
844 .setCode(CIRCUIT_ID.getValue())
845 .setLength((byte) circuitId.length)
846 .setData(circuitId);
847
848 DhcpRelayAgentOption newRelayAgentOpt = new DhcpRelayAgentOption();
849 newRelayAgentOpt.setCode(OptionCode_CircuitID.getValue());
850 newRelayAgentOpt.addSubOption(circuitIdSubOpt);
851
852 // Removes END option first
853 List<DhcpOption> options = dhcpPacket.getOptions().stream()
854 .filter(opt -> opt.getCode() != OptionCode_END.getValue())
855 .collect(Collectors.toList());
856
857 // push relay agent option
858 options.add(newRelayAgentOpt);
859
860 // make sure option 255(End) is the last option
861 DhcpOption endOption = new DhcpOption();
862 endOption.setCode(OptionCode_END.getValue());
863 options.add(endOption);
864
865 dhcpPacket.setOptions(options);
866
867 relayAgentIp = serverInfo.getRelayAgentIp4(receivedFromDevice).orElse(null);
868
869 // Sets relay agent IP
870 int effectiveRelayAgentIp = relayAgentIp != null ?
871 relayAgentIp.toInt() : clientInterfaceIp.toInt();
872 dhcpPacket.setGatewayIPAddress(effectiveRelayAgentIp);
Charles Chan2de55302018-03-02 18:27:59 -0800873 log.debug("In Default, Relay Agent IP {}", effectiveRelayAgentIp);
Charles Chand0d1e332017-10-10 16:53:32 -0400874 } else {
rsahot036620655b2018-02-26 15:01:37 -0500875 if (!newServerInfo.getDhcpServerIp4().isPresent()) {
876 // do nothing
877 } else if (!newServerInfo.getDhcpConnectMac().isPresent()) {
878 continue;
879 } else {
880 relayAgentIp = newServerInfo.getRelayAgentIp4(receivedFromDevice).orElse(null);
881 // Sets relay agent IP
882 int effectiveRelayAgentIp = relayAgentIp != null ?
883 relayAgentIp.toInt() : clientInterfaceIp.toInt();
884 dhcpPacket.setGatewayIPAddress(effectiveRelayAgentIp);
Charles Chand0d1e332017-10-10 16:53:32 -0400885 }
Yi Tseng4f2a0462017-08-31 11:21:00 -0700886 }
Yi Tseng3df7f9d2017-08-17 13:08:31 -0700887
rsahot036620655b2018-02-26 15:01:37 -0500888 // Remove broadcast flag
889 dhcpPacket.setFlags((short) 0);
890
891 udpPacket.setPayload(dhcpPacket);
892 // As a DHCP relay, the source port should be server port( instead
893 // of client port.
894 udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
895 udpPacket.setDestinationPort(UDP.DHCP_SERVER_PORT);
896 ipv4Packet.setPayload(udpPacket);
897 ipv4Packet.setTtl((byte) 64);
898 etherReply.setPayload(ipv4Packet);
Taras Lemkin96a0d342018-03-26 14:52:58 +0000899 InternalPacket internalPacket = InternalPacket.internalPacket(etherReply,
rsahot036620655b2018-02-26 15:01:37 -0500900 serverInfo.getDhcpServerConnectPoint().get());
Taras Lemkin96a0d342018-03-26 14:52:58 +0000901
rsahot036620655b2018-02-26 15:01:37 -0500902 internalPackets.add(internalPacket);
903 }
904 return internalPackets;
Yi Tseng51301292017-07-28 13:02:59 -0700905 }
906
Charles Chand0dd7002017-10-08 23:53:36 -0400907
908 /**
909 * Do a basic routing for a packet from client (used for LQ processing).
910 *
911 * @param context the packet context
912 * @param ethernetPacket the ethernet payload to process
913 * @return processed packet
914 */
rsahot036620655b2018-02-26 15:01:37 -0500915 private List<InternalPacket> processLeaseQueryFromAgent(PacketContext context,
916 Ethernet ethernetPacket) {
917 ConnectPoint receivedFrom = context.inPacket().receivedFrom();
918 DeviceId receivedFromDevice = receivedFrom.deviceId();
919
Charles Chand0dd7002017-10-08 23:53:36 -0400920 // get dhcp header.
921 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
922 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
923 UDP udpPacket = (UDP) ipv4Packet.getPayload();
924 DHCP dhcpPacket = (DHCP) udpPacket.getPayload();
925
Charles Chan2de55302018-03-02 18:27:59 -0800926 Ip4Address relayAgentIp;
Charles Chand0dd7002017-10-08 23:53:36 -0400927
Charles Chand0dd7002017-10-08 23:53:36 -0400928 Ip4Address clientInterfaceIp =
929 interfaceService.getInterfacesByPort(context.inPacket().receivedFrom())
930 .stream()
931 .map(Interface::ipAddressesList)
932 .flatMap(Collection::stream)
933 .map(InterfaceIpAddress::ipAddress)
934 .filter(IpAddress::isIp4)
935 .map(IpAddress::getIp4Address)
936 .findFirst()
937 .orElse(null);
938 if (clientInterfaceIp == null) {
939 log.warn("Can't find interface IP for client interface for port {}",
rsahot036620655b2018-02-26 15:01:37 -0500940 context.inPacket().receivedFrom());
Charles Chand0dd7002017-10-08 23:53:36 -0400941 return null;
942 }
rsahot036620655b2018-02-26 15:01:37 -0500943
Charles Chand0dd7002017-10-08 23:53:36 -0400944 boolean isDirectlyConnected = directlyConnected(dhcpPacket);
rsahot036620655b2018-02-26 15:01:37 -0500945 boolean directConnFlag = directlyConnected(dhcpPacket);
946
947 // Multi DHCP Start
rsahot036620655b2018-02-26 15:01:37 -0500948 List<InternalPacket> internalPackets = new ArrayList<>();
949 List<DhcpServerInfo> serverInfoList = findValidServerInfo(directConnFlag);
Charles Chan2de55302018-03-02 18:27:59 -0800950 List<DhcpServerInfo> copyServerInfoList = new ArrayList<>(serverInfoList);
rsahot036620655b2018-02-26 15:01:37 -0500951
952 for (DhcpServerInfo serverInfo : copyServerInfoList) {
953 // get dhcp header.
954 etherReply = (Ethernet) ethernetPacket.clone();
955 ipv4Packet = (IPv4) etherReply.getPayload();
956 udpPacket = (UDP) ipv4Packet.getPayload();
957 dhcpPacket = (DHCP) udpPacket.getPayload();
958
959 if (!checkDhcpServerConnPt(directConnFlag, serverInfo)) {
960 log.warn("Can't get server connect point, ignore");
961 continue;
Yi Tseng3bd57ac2017-11-29 14:39:18 -0800962 }
rsahot036620655b2018-02-26 15:01:37 -0500963 DhcpServerInfo newServerInfo = getHostInfoForServerInfo(serverInfo, serverInfoList);
964 if (newServerInfo == null) {
965 log.warn("Can't get server interface with host info resolved, ignore");
966 continue;
967 }
Charles Chand0dd7002017-10-08 23:53:36 -0400968
rsahot036620655b2018-02-26 15:01:37 -0500969 Interface serverInterface = getServerInterface(newServerInfo);
970 if (serverInterface == null) {
971 log.warn("Can't get server interface, ignore");
972 continue;
973 }
974 Ip4Address ipFacingServer = getFirstIpFromInterface(serverInterface);
975 MacAddress macFacingServer = serverInterface.mac();
976 if (ipFacingServer == null || macFacingServer == null) {
977 log.warn("No IP address for server Interface {}", serverInterface);
978 continue;
979 }
Charles Chand0dd7002017-10-08 23:53:36 -0400980
rsahot036620655b2018-02-26 15:01:37 -0500981 etherReply.setSourceMACAddress(macFacingServer);
Charles Chan2de55302018-03-02 18:27:59 -0800982 etherReply.setDestinationMACAddress(newServerInfo.getDhcpConnectMac().get());
983 etherReply.setVlanID(newServerInfo.getDhcpConnectVlan().get().toShort());
rsahot036620655b2018-02-26 15:01:37 -0500984 ipv4Packet.setSourceAddress(ipFacingServer.toInt());
Charles Chan2de55302018-03-02 18:27:59 -0800985 ipv4Packet.setDestinationAddress(newServerInfo.getDhcpServerIp4().get().toInt());
rsahot036620655b2018-02-26 15:01:37 -0500986 if (isDirectlyConnected) {
987 // set default info and replace with indirect if available later on.
988 if (newServerInfo.getDhcpConnectMac().isPresent()) {
989 etherReply.setDestinationMACAddress(newServerInfo.getDhcpConnectMac().get());
990 }
991 if (newServerInfo.getDhcpConnectVlan().isPresent()) {
992 etherReply.setVlanID(serverInfo.getDhcpConnectVlan().get().toShort());
993 }
Taras Lemkin96a0d342018-03-26 14:52:58 +0000994 if (learnRouteFromLeasequery) {
rsahot036620655b2018-02-26 15:01:37 -0500995 relayAgentIp = newServerInfo.getRelayAgentIp4(receivedFromDevice).orElse(null);
996 // Sets relay agent IP
997 int effectiveRelayAgentIp = relayAgentIp != null ?
998 relayAgentIp.toInt() : clientInterfaceIp.toInt();
999 dhcpPacket.setGatewayIPAddress(effectiveRelayAgentIp);
Taras Lemkin96a0d342018-03-26 14:52:58 +00001000 }
1001 } else {
1002 if (!newServerInfo.getDhcpServerIp4().isPresent()) {
1003 //do nothing
1004 } else if (!newServerInfo.getDhcpConnectMac().isPresent()) {
1005 continue;
1006 } else if (learnRouteFromLeasequery) {
1007 relayAgentIp = newServerInfo.getRelayAgentIp4(receivedFromDevice).orElse(null);
1008 // Sets relay agent IP
1009 int effectiveRelayAgentIp = relayAgentIp != null ?
1010 relayAgentIp.toInt() : clientInterfaceIp.toInt();
rsahot036620655b2018-02-26 15:01:37 -05001011 dhcpPacket.setGatewayIPAddress(effectiveRelayAgentIp);
Taras Lemkin96a0d342018-03-26 14:52:58 +00001012 log.debug("Relay Agent IP {}", relayAgentIp);
rsahot036620655b2018-02-26 15:01:37 -05001013 }
1014
Taras Lemkin96a0d342018-03-26 14:52:58 +00001015 log.trace("Indirect");
rsahot036620655b2018-02-26 15:01:37 -05001016 }
1017
1018 // Remove broadcast flag
1019 dhcpPacket.setFlags((short) 0);
1020
1021 udpPacket.setPayload(dhcpPacket);
1022 // As a DHCP relay, the source port should be server port( instead
1023 // of client port.
1024 udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
1025 udpPacket.setDestinationPort(UDP.DHCP_SERVER_PORT);
1026 ipv4Packet.setPayload(udpPacket);
1027 ipv4Packet.setTtl((byte) 64);
1028 etherReply.setPayload(ipv4Packet);
Taras Lemkin96a0d342018-03-26 14:52:58 +00001029 udpPacket.resetChecksum();
rsahot036620655b2018-02-26 15:01:37 -05001030 ////return etherReply;
Taras Lemkin96a0d342018-03-26 14:52:58 +00001031 InternalPacket internalPacket = InternalPacket.internalPacket(etherReply,
rsahot036620655b2018-02-26 15:01:37 -05001032 newServerInfo.getDhcpServerConnectPoint().get());
Taras Lemkin96a0d342018-03-26 14:52:58 +00001033
rsahot036620655b2018-02-26 15:01:37 -05001034 internalPackets.add(internalPacket);
Charles Chand0dd7002017-10-08 23:53:36 -04001035 }
Taras Lemkin96a0d342018-03-26 14:52:58 +00001036 log.debug("num of processLeaseQueryFromAgent packets to send is: {}", internalPackets.size());
Charles Chand0dd7002017-10-08 23:53:36 -04001037
rsahot036620655b2018-02-26 15:01:37 -05001038 return internalPackets;
Charles Chand0dd7002017-10-08 23:53:36 -04001039 }
1040
1041
Yi Tseng51301292017-07-28 13:02:59 -07001042 /**
1043 * Writes DHCP record to the store according to the request DHCP packet (Discover, Request).
1044 *
1045 * @param location the location which DHCP packet comes from
1046 * @param ethernet the DHCP packet
1047 * @param dhcpPayload the DHCP payload
1048 */
1049 private void writeRequestDhcpRecord(ConnectPoint location,
1050 Ethernet ethernet,
1051 DHCP dhcpPayload) {
1052 VlanId vlanId = VlanId.vlanId(ethernet.getVlanID());
1053 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
1054 HostId hostId = HostId.hostId(macAddress, vlanId);
1055 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1056 if (record == null) {
1057 record = new DhcpRecord(HostId.hostId(macAddress, vlanId));
1058 } else {
1059 record = record.clone();
1060 }
1061 record.addLocation(new HostLocation(location, System.currentTimeMillis()));
1062 record.ip4Status(dhcpPayload.getPacketType());
1063 record.setDirectlyConnected(directlyConnected(dhcpPayload));
1064 if (!directlyConnected(dhcpPayload)) {
1065 // Update gateway mac address if the host is not directly connected
1066 record.nextHop(ethernet.getSourceMAC());
1067 }
1068 record.updateLastSeen();
1069 dhcpRelayStore.updateDhcpRecord(HostId.hostId(macAddress, vlanId), record);
1070 }
1071
1072 /**
1073 * Writes DHCP record to the store according to the response DHCP packet (Offer, Ack).
1074 *
1075 * @param ethernet the DHCP packet
1076 * @param dhcpPayload the DHCP payload
1077 */
1078 private void writeResponseDhcpRecord(Ethernet ethernet,
1079 DHCP dhcpPayload) {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001080 Optional<Interface> outInterface = getClientInterface(ethernet, dhcpPayload);
Yi Tseng51301292017-07-28 13:02:59 -07001081 if (!outInterface.isPresent()) {
1082 log.warn("Failed to determine where to send {}", dhcpPayload.getPacketType());
1083 return;
1084 }
1085
1086 Interface outIface = outInterface.get();
1087 ConnectPoint location = outIface.connectPoint();
Yi Tseng4f2a0462017-08-31 11:21:00 -07001088 VlanId vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -07001089 if (vlanId == null) {
1090 vlanId = outIface.vlan();
1091 }
Yi Tseng51301292017-07-28 13:02:59 -07001092 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
1093 HostId hostId = HostId.hostId(macAddress, vlanId);
1094 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1095 if (record == null) {
1096 record = new DhcpRecord(HostId.hostId(macAddress, vlanId));
1097 } else {
1098 record = record.clone();
1099 }
1100 record.addLocation(new HostLocation(location, System.currentTimeMillis()));
1101 if (dhcpPayload.getPacketType() == DHCP.MsgType.DHCPACK) {
1102 record.ip4Address(Ip4Address.valueOf(dhcpPayload.getYourIPAddress()));
1103 }
1104 record.ip4Status(dhcpPayload.getPacketType());
1105 record.setDirectlyConnected(directlyConnected(dhcpPayload));
1106 record.updateLastSeen();
1107 dhcpRelayStore.updateDhcpRecord(HostId.hostId(macAddress, vlanId), record);
1108 }
1109
1110 /**
1111 * Build the DHCP offer/ack with proper client port.
1112 *
1113 * @param ethernetPacket the original packet comes from server
1114 * @return new packet which will send to the client
1115 */
Taras Lemkin96a0d342018-03-26 14:52:58 +00001116 private InternalPacket processDhcpPacketFromServer(PacketContext context, Ethernet ethernetPacket) {
Yi Tseng51301292017-07-28 13:02:59 -07001117 // get dhcp header.
rsahot036620655b2018-02-26 15:01:37 -05001118 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
Yi Tseng51301292017-07-28 13:02:59 -07001119 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
1120 UDP udpPacket = (UDP) ipv4Packet.getPayload();
1121 DHCP dhcpPayload = (DHCP) udpPacket.getPayload();
1122
1123 // determine the vlanId of the client host - note that this vlan id
1124 // could be different from the vlan in the packet from the server
Yi Tsengdcef2c22017-08-05 20:34:06 -07001125 Interface clientInterface = getClientInterface(ethernetPacket, dhcpPayload).orElse(null);
Yi Tseng51301292017-07-28 13:02:59 -07001126
Yi Tsengdcef2c22017-08-05 20:34:06 -07001127 if (clientInterface == null) {
Yi Tseng51301292017-07-28 13:02:59 -07001128 log.warn("Cannot find the interface for the DHCP {}", dhcpPayload);
1129 return null;
1130 }
Yi Tsengdcef2c22017-08-05 20:34:06 -07001131 VlanId vlanId;
rsahot036620655b2018-02-26 15:01:37 -05001132 ConnectPoint inPort = context.inPacket().receivedFrom();
1133 boolean directConnFlag = directlyConnected(dhcpPayload);
1134 DhcpServerInfo foundServerInfo = findServerInfoFromServer(directConnFlag, inPort);
1135
1136 if (foundServerInfo == null) {
1137 log.warn("Cannot find server info");
1138 return null;
1139 } else {
Taras Lemkin96a0d342018-03-26 14:52:58 +00001140 if (Dhcp4HandlerUtil.isServerIpEmpty(foundServerInfo)) {
rsahot036620655b2018-02-26 15:01:37 -05001141 log.warn("Cannot find server info's ipaddress");
1142 return null;
1143 }
1144 }
Yi Tsengdcef2c22017-08-05 20:34:06 -07001145 if (clientInterface.vlanTagged().isEmpty()) {
1146 vlanId = clientInterface.vlan();
1147 } else {
1148 // might be multiple vlan in same interface
Yi Tseng4f2a0462017-08-31 11:21:00 -07001149 vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -07001150 }
1151 if (vlanId == null) {
1152 vlanId = VlanId.NONE;
1153 }
1154 etherReply.setVlanID(vlanId.toShort());
1155 etherReply.setSourceMACAddress(clientInterface.mac());
Yi Tseng51301292017-07-28 13:02:59 -07001156
Yi Tsengdcef2c22017-08-05 20:34:06 -07001157 if (!directlyConnected(dhcpPayload)) {
1158 // if client is indirectly connected, try use next hop mac address
1159 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
1160 HostId hostId = HostId.hostId(macAddress, vlanId);
Daniel Ginsburgb1dec912018-01-29 11:40:22 -08001161 if (((int) dhcpPayload.getFlags() & 0x8000) == 0x0000) {
1162 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1163 if (record != null) {
1164 // if next hop can be found, use mac address of next hop
1165 record.nextHop().ifPresent(etherReply::setDestinationMACAddress);
1166 } else {
1167 // otherwise, discard the packet
1168 log.warn("Can't find record for host id {}, discard packet", hostId);
1169 return null;
1170 }
Yi Tsengdcef2c22017-08-05 20:34:06 -07001171 } else {
Daniel Ginsburgb1dec912018-01-29 11:40:22 -08001172 etherReply.setDestinationMACAddress(MacAddress.BROADCAST);
Yi Tsengdcef2c22017-08-05 20:34:06 -07001173 }
Yi Tseng1696f562017-08-17 17:43:38 -07001174 } else {
1175 etherReply.setDestinationMACAddress(dhcpPayload.getClientHardwareAddress());
Yi Tsengdcef2c22017-08-05 20:34:06 -07001176 }
1177
Yi Tseng51301292017-07-28 13:02:59 -07001178 // we leave the srcMac from the original packet
Yi Tseng51301292017-07-28 13:02:59 -07001179 // figure out the relay agent IP corresponding to the original request
Yi Tseng3df7f9d2017-08-17 13:08:31 -07001180 Ip4Address ipFacingClient = getFirstIpFromInterface(clientInterface);
1181 if (ipFacingClient == null) {
Yi Tseng51301292017-07-28 13:02:59 -07001182 log.warn("Cannot determine relay agent interface Ipv4 addr for host {}/{}. "
1183 + "Aborting relay for dhcp packet from server {}",
Yi Tsengdcef2c22017-08-05 20:34:06 -07001184 etherReply.getDestinationMAC(), clientInterface.vlan(),
Yi Tseng51301292017-07-28 13:02:59 -07001185 ethernetPacket);
1186 return null;
1187 }
1188 // SRC_IP: relay agent IP
1189 // DST_IP: offered IP
Yi Tseng3df7f9d2017-08-17 13:08:31 -07001190 ipv4Packet.setSourceAddress(ipFacingClient.toInt());
Daniel Ginsburgb1dec912018-01-29 11:40:22 -08001191 if (((int) dhcpPayload.getFlags() & 0x8000) == 0x0000) {
1192 ipv4Packet.setDestinationAddress(dhcpPayload.getYourIPAddress());
1193 } else {
1194 ipv4Packet.setDestinationAddress(BROADCAST_IP);
1195 }
Yi Tseng51301292017-07-28 13:02:59 -07001196 udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
1197 if (directlyConnected(dhcpPayload)) {
1198 udpPacket.setDestinationPort(UDP.DHCP_CLIENT_PORT);
1199 } else {
1200 // forward to another dhcp relay
Yi Tseng93ba53c2017-09-14 13:24:21 -07001201 // FIXME: Currently we assume the DHCP comes from a L2 relay with
1202 // Option 82, this might not work if DHCP message comes from
1203 // L3 relay.
1204 udpPacket.setDestinationPort(UDP.DHCP_CLIENT_PORT);
Yi Tseng51301292017-07-28 13:02:59 -07001205 }
1206
1207 udpPacket.setPayload(dhcpPayload);
1208 ipv4Packet.setPayload(udpPacket);
1209 etherReply.setPayload(ipv4Packet);
Taras Lemkin96a0d342018-03-26 14:52:58 +00001210 return InternalPacket.internalPacket(etherReply, clientInterface.connectPoint());
Yi Tseng51301292017-07-28 13:02:59 -07001211 }
1212
Yi Tsengdcef2c22017-08-05 20:34:06 -07001213 /**
Charles Chand0dd7002017-10-08 23:53:36 -04001214 * Build the DHCP offer/ack with proper client port.
1215 *
1216 * @param ethernetPacket the original packet comes from server
1217 * @return new packet which will send to the client
1218 */
Taras Lemkin96a0d342018-03-26 14:52:58 +00001219 private InternalPacket processLeaseQueryFromServer(Ethernet ethernetPacket) {
Charles Chand0dd7002017-10-08 23:53:36 -04001220 // get dhcp header.
1221 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
1222 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
1223 UDP udpPacket = (UDP) ipv4Packet.getPayload();
1224 DHCP dhcpPayload = (DHCP) udpPacket.getPayload();
1225
1226 // determine the vlanId of the client host - note that this vlan id
1227 // could be different from the vlan in the packet from the server
Taras Lemkin96a0d342018-03-26 14:52:58 +00001228 Interface clientInterface = null;
1229 MacAddress destinationMac = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
1230
1231 if (!learnRouteFromLeasequery) {
1232 int giaddr = ipv4Packet.getDestinationAddress();
1233 IpAddress destinationAddress = Ip4Address.valueOf(giaddr);
1234 log.debug("DHCPLEASEQUERYRESP giaddr: {}({})", giaddr, destinationAddress);
1235
1236 Host destinationHost = hostService.getHostsByIp(destinationAddress).stream().findFirst().orElse(null);
1237 if (destinationHost != null) {
1238 destinationMac = destinationHost.mac();
1239 log.trace("DHCPLEASEQUERYRESP destination mac is: {}", destinationMac);
1240 ConnectPoint destinationLocation = destinationHost.location();
1241 log.trace("Lookup for client interface by destination location {}", destinationLocation);
1242 clientInterface = interfaceService.getInterfacesByPort(destinationLocation)
1243 .stream()
1244 .filter(iface -> interfaceContainsVlan(iface, VlanId.vlanId(etherReply.getVlanID())))
1245 .findFirst()
1246 .orElse(null);
1247 log.trace("Found Host {} by ip {}", destinationHost, destinationAddress);
1248 log.debug("DHCPLEASEQUERYRESP Client interface: {}",
1249 (clientInterface != null ? clientInterface : "not resolved"));
1250
1251 }
1252 } else {
1253 clientInterface = getClientInterface(ethernetPacket, dhcpPayload).orElse(null);
1254 }
Charles Chand0dd7002017-10-08 23:53:36 -04001255
1256 if (clientInterface == null) {
1257 log.warn("Cannot find the interface for the DHCP {}", dhcpPayload);
1258 return null;
1259 }
1260 VlanId vlanId;
1261 if (clientInterface.vlanTagged().isEmpty()) {
1262 vlanId = clientInterface.vlan();
1263 } else {
1264 // might be multiple vlan in same interface
1265 vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
1266 }
1267 if (vlanId == null) {
1268 vlanId = VlanId.NONE;
1269 }
1270 etherReply.setVlanID(vlanId.toShort());
1271 etherReply.setSourceMACAddress(clientInterface.mac());
1272
Taras Lemkin96a0d342018-03-26 14:52:58 +00001273 if (!directlyConnected(dhcpPayload) && learnRouteFromLeasequery) {
Charles Chand0dd7002017-10-08 23:53:36 -04001274 // if client is indirectly connected, try use next hop mac address
1275 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
1276 HostId hostId = HostId.hostId(macAddress, vlanId);
1277 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1278 if (record != null) {
1279 // if next hop can be found, use mac address of next hop
Taras Lemkin96a0d342018-03-26 14:52:58 +00001280 Optional<MacAddress> nextHop = record.nextHopTemp();
1281 if (!nextHop.isPresent()) {
1282 nextHop = record.nextHop();
1283 }
1284 nextHop.ifPresent(etherReply::setDestinationMACAddress);
Charles Chand0dd7002017-10-08 23:53:36 -04001285 } else {
1286 // otherwise, discard the packet
1287 log.warn("Can't find record for host id {}, discard packet", hostId);
1288 return null;
1289 }
1290 } else {
Taras Lemkin96a0d342018-03-26 14:52:58 +00001291 etherReply.setDestinationMACAddress(destinationMac);
Charles Chand0dd7002017-10-08 23:53:36 -04001292 }
1293
Charles Chand0dd7002017-10-08 23:53:36 -04001294 udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
Taras Lemkin96a0d342018-03-26 14:52:58 +00001295 if (directlyConnected(dhcpPayload)) {
1296 udpPacket.setDestinationPort(UDP.DHCP_CLIENT_PORT);
1297 } else {
1298 udpPacket.setDestinationPort(UDP.DHCP_SERVER_PORT);
1299 }
Charles Chand0dd7002017-10-08 23:53:36 -04001300
1301 udpPacket.setPayload(dhcpPayload);
1302 ipv4Packet.setPayload(udpPacket);
1303 etherReply.setPayload(ipv4Packet);
Taras Lemkin96a0d342018-03-26 14:52:58 +00001304 udpPacket.resetChecksum();
1305
1306 return InternalPacket.internalPacket(etherReply, clientInterface.connectPoint());
Charles Chand0dd7002017-10-08 23:53:36 -04001307 }
1308 /**
Yi Tsengdcef2c22017-08-05 20:34:06 -07001309 * Extracts VLAN ID from relay agent option.
1310 *
1311 * @param dhcpPayload the DHCP payload
1312 * @return VLAN ID from DHCP payload; null if not exists
1313 */
Yi Tseng4f2a0462017-08-31 11:21:00 -07001314 private VlanId getVlanIdFromRelayAgentOption(DHCP dhcpPayload) {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001315 DhcpRelayAgentOption option = (DhcpRelayAgentOption) dhcpPayload.getOption(OptionCode_CircuitID);
1316 if (option == null) {
1317 return null;
1318 }
1319 DhcpOption circuitIdSubOption = option.getSubOption(CIRCUIT_ID.getValue());
1320 if (circuitIdSubOption == null) {
1321 return null;
1322 }
1323 try {
1324 CircuitId circuitId = CircuitId.deserialize(circuitIdSubOption.getData());
1325 return circuitId.vlanId();
1326 } catch (IllegalArgumentException e) {
1327 // can't deserialize the circuit ID
1328 return null;
1329 }
1330 }
1331
1332 /**
1333 * Removes DHCP relay agent information option (option 82) from DHCP payload.
1334 * Also reset giaddr to 0
1335 *
1336 * @param ethPacket the Ethernet packet to be processed
1337 * @return Ethernet packet processed
1338 */
1339 private Ethernet removeRelayAgentOption(Ethernet ethPacket) {
rsahot036620655b2018-02-26 15:01:37 -05001340 Ethernet ethernet = (Ethernet) ethPacket.duplicate();
Yi Tsengdcef2c22017-08-05 20:34:06 -07001341 IPv4 ipv4 = (IPv4) ethernet.getPayload();
1342 UDP udp = (UDP) ipv4.getPayload();
1343 DHCP dhcpPayload = (DHCP) udp.getPayload();
1344
1345 // removes relay agent information option
1346 List<DhcpOption> options = dhcpPayload.getOptions();
1347 options = options.stream()
1348 .filter(option -> option.getCode() != OptionCode_CircuitID.getValue())
1349 .collect(Collectors.toList());
1350 dhcpPayload.setOptions(options);
1351 dhcpPayload.setGatewayIPAddress(0);
1352
1353 udp.setPayload(dhcpPayload);
1354 ipv4.setPayload(udp);
1355 ethernet.setPayload(ipv4);
1356 return ethernet;
1357 }
1358
Taras Lemkin96a0d342018-03-26 14:52:58 +00001359 private boolean isDhcpPacketLeasequery(DHCP dhcpPacket) {
1360 switch (dhcpPacket.getPacketType()) {
1361 case DHCPLEASEACTIVE:
1362 case DHCPLEASEQUERY:
1363 case DHCPLEASEUNASSIGNED:
1364 case DHCPLEASEUNKNOWN:
1365 return true;
1366 default:
1367 return false;
1368 }
1369 }
Yi Tseng51301292017-07-28 13:02:59 -07001370
1371 /**
1372 * Check if the host is directly connected to the network or not.
1373 *
1374 * @param dhcpPayload the dhcp payload
1375 * @return true if the host is directly connected to the network; false otherwise
1376 */
1377 private boolean directlyConnected(DHCP dhcpPayload) {
Taras Lemkin96a0d342018-03-26 14:52:58 +00001378 // leasequery is always indirect
1379 if (isDhcpPacketLeasequery(dhcpPayload)) {
1380 return false;
1381 }
1382
Yi Tseng440e2b72017-08-24 14:47:34 -07001383 DhcpRelayAgentOption relayAgentOption =
1384 (DhcpRelayAgentOption) dhcpPayload.getOption(OptionCode_CircuitID);
Yi Tseng51301292017-07-28 13:02:59 -07001385
1386 // Doesn't contains relay option
1387 if (relayAgentOption == null) {
1388 return true;
1389 }
1390
Yi Tseng440e2b72017-08-24 14:47:34 -07001391 // check circuit id, if circuit id is invalid, we say it is an indirect host
1392 DhcpOption circuitIdOpt = relayAgentOption.getSubOption(CIRCUIT_ID.getValue());
Yi Tseng51301292017-07-28 13:02:59 -07001393
Yi Tseng440e2b72017-08-24 14:47:34 -07001394 try {
1395 CircuitId.deserialize(circuitIdOpt.getData());
Yi Tseng51301292017-07-28 13:02:59 -07001396 return true;
Yi Tseng440e2b72017-08-24 14:47:34 -07001397 } catch (Exception e) {
1398 // invalid circuit id
1399 return false;
Yi Tseng51301292017-07-28 13:02:59 -07001400 }
Yi Tseng51301292017-07-28 13:02:59 -07001401 }
1402
1403
1404 /**
1405 * Send the DHCP ack to the requester host.
1406 * Modify Host or Route store according to the type of DHCP.
1407 *
1408 * @param ethernetPacketAck the packet
1409 * @param dhcpPayload the DHCP data
1410 */
1411 private void handleDhcpAck(Ethernet ethernetPacketAck, DHCP dhcpPayload) {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001412 Optional<Interface> outInterface = getClientInterface(ethernetPacketAck, dhcpPayload);
Yi Tseng51301292017-07-28 13:02:59 -07001413 if (!outInterface.isPresent()) {
1414 log.warn("Can't find output interface for dhcp: {}", dhcpPayload);
1415 return;
1416 }
1417
1418 Interface outIface = outInterface.get();
1419 HostLocation hostLocation = new HostLocation(outIface.connectPoint(), System.currentTimeMillis());
1420 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
Yi Tseng4f2a0462017-08-31 11:21:00 -07001421 VlanId vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -07001422 if (vlanId == null) {
1423 vlanId = outIface.vlan();
1424 }
Yi Tseng51301292017-07-28 13:02:59 -07001425 HostId hostId = HostId.hostId(macAddress, vlanId);
1426 Ip4Address ip = Ip4Address.valueOf(dhcpPayload.getYourIPAddress());
1427
1428 if (directlyConnected(dhcpPayload)) {
1429 // Add to host store if it connect to network directly
1430 Set<IpAddress> ips = Sets.newHashSet(ip);
Yi Tsengaa417a62017-09-08 17:22:51 -07001431 Host host = hostService.getHost(hostId);
Yi Tseng51301292017-07-28 13:02:59 -07001432
Yi Tsengaa417a62017-09-08 17:22:51 -07001433 Set<HostLocation> hostLocations = Sets.newHashSet(hostLocation);
1434 if (host != null) {
1435 // Dual homing support:
1436 // if host exists, use old locations and new location
1437 hostLocations.addAll(host.locations());
1438 }
1439 HostDescription desc = new DefaultHostDescription(macAddress, vlanId,
1440 hostLocations, ips, false);
1441 // Add IP address when dhcp server give the host new ip address
1442 providerService.hostDetected(hostId, desc, false);
Yi Tseng51301292017-07-28 13:02:59 -07001443 } else {
1444 // Add to route store if it does not connect to network directly
1445 // Get gateway host IP according to host mac address
Yi Tsengdcef2c22017-08-05 20:34:06 -07001446 // TODO: remove relay store here
Yi Tseng51301292017-07-28 13:02:59 -07001447 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1448
1449 if (record == null) {
1450 log.warn("Can't find DHCP record of host {}", hostId);
1451 return;
1452 }
1453
1454 MacAddress gwMac = record.nextHop().orElse(null);
1455 if (gwMac == null) {
1456 log.warn("Can't find gateway mac address from record {}", record);
1457 return;
1458 }
1459
1460 HostId gwHostId = HostId.hostId(gwMac, record.vlanId());
1461 Host gwHost = hostService.getHost(gwHostId);
1462
1463 if (gwHost == null) {
1464 log.warn("Can't find gateway host {}", gwHostId);
1465 return;
1466 }
1467
1468 Ip4Address nextHopIp = gwHost.ipAddresses()
1469 .stream()
1470 .filter(IpAddress::isIp4)
1471 .map(IpAddress::getIp4Address)
1472 .findFirst()
1473 .orElse(null);
1474
1475 if (nextHopIp == null) {
1476 log.warn("Can't find IP address of gateway {}", gwHost);
1477 return;
1478 }
1479
Charles Chan6305b692018-04-04 11:43:54 -07001480 Route route = new Route(Route.Source.DHCP, ip.toIpPrefix(), nextHopIp);
Daniel Ginsburg83b76452018-06-09 01:43:59 +03001481 routeStore.replaceRoute(route);
Yi Tseng51301292017-07-28 13:02:59 -07001482 }
Yi Tseng51301292017-07-28 13:02:59 -07001483 }
1484
1485 /**
Yi Tseng51301292017-07-28 13:02:59 -07001486 * Gets output interface of a dhcp packet.
1487 * If option 82 exists in the dhcp packet and the option was sent by
Yi Tseng4f2a0462017-08-31 11:21:00 -07001488 * ONOS (circuit format is correct), use the connect
Yi Tseng51301292017-07-28 13:02:59 -07001489 * point and vlan id from circuit id; otherwise, find host by destination
1490 * address and use vlan id from sender (dhcp server).
1491 *
1492 * @param ethPacket the ethernet packet
1493 * @param dhcpPayload the dhcp packet
1494 * @return an interface represent the output port and vlan; empty value
1495 * if the host or circuit id not found
1496 */
Yi Tsengdcef2c22017-08-05 20:34:06 -07001497 private Optional<Interface> getClientInterface(Ethernet ethPacket, DHCP dhcpPayload) {
Yi Tseng51301292017-07-28 13:02:59 -07001498 VlanId originalPacketVlanId = VlanId.vlanId(ethPacket.getVlanID());
Yi Tseng51301292017-07-28 13:02:59 -07001499 DhcpRelayAgentOption option = (DhcpRelayAgentOption) dhcpPayload.getOption(OptionCode_CircuitID);
1500
Yi Tseng4f2a0462017-08-31 11:21:00 -07001501 DhcpOption circuitIdSubOption = option.getSubOption(CIRCUIT_ID.getValue());
1502 try {
1503 CircuitId circuitId = CircuitId.deserialize(circuitIdSubOption.getData());
1504 ConnectPoint connectPoint = ConnectPoint.deviceConnectPoint(circuitId.connectPoint());
1505 VlanId vlanId = circuitId.vlanId();
1506 return interfaceService.getInterfacesByPort(connectPoint)
1507 .stream()
1508 .filter(iface -> interfaceContainsVlan(iface, vlanId))
1509 .findFirst();
1510 } catch (IllegalArgumentException ex) {
1511 // invalid circuit format, didn't sent by ONOS
1512 log.debug("Invalid circuit {}, use information from dhcp payload",
1513 circuitIdSubOption.getData());
Yi Tseng51301292017-07-28 13:02:59 -07001514 }
1515
1516 // Use Vlan Id from DHCP server if DHCP relay circuit id was not
1517 // sent by ONOS or circuit Id can't be parsed
Yi Tsengdcef2c22017-08-05 20:34:06 -07001518 // TODO: remove relay store from this method
Yi Tseng51301292017-07-28 13:02:59 -07001519 MacAddress dstMac = valueOf(dhcpPayload.getClientHardwareAddress());
1520 Optional<DhcpRecord> dhcpRecord = dhcpRelayStore.getDhcpRecord(HostId.hostId(dstMac, originalPacketVlanId));
Yi Tsengdcef2c22017-08-05 20:34:06 -07001521 ConnectPoint clientConnectPoint = dhcpRecord
Yi Tseng51301292017-07-28 13:02:59 -07001522 .map(DhcpRecord::locations)
1523 .orElse(Collections.emptySet())
1524 .stream()
1525 .reduce((hl1, hl2) -> {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001526 // find latest host connect point
Yi Tseng51301292017-07-28 13:02:59 -07001527 if (hl1 == null || hl2 == null) {
1528 return hl1 == null ? hl2 : hl1;
1529 }
1530 return hl1.time() > hl2.time() ? hl1 : hl2;
1531 })
Yi Tsengdcef2c22017-08-05 20:34:06 -07001532 .orElse(null);
Yi Tseng51301292017-07-28 13:02:59 -07001533
Yi Tsengdcef2c22017-08-05 20:34:06 -07001534 if (clientConnectPoint != null) {
1535 return interfaceService.getInterfacesByPort(clientConnectPoint)
1536 .stream()
Yi Tseng4f2a0462017-08-31 11:21:00 -07001537 .filter(iface -> interfaceContainsVlan(iface, originalPacketVlanId))
Yi Tsengdcef2c22017-08-05 20:34:06 -07001538 .findFirst();
1539 }
1540 return Optional.empty();
Yi Tseng51301292017-07-28 13:02:59 -07001541 }
1542
1543 /**
1544 * Send the response DHCP to the requester host.
1545 *
Taras Lemkin96a0d342018-03-26 14:52:58 +00001546 * @param thePacket the packet
Yi Tseng51301292017-07-28 13:02:59 -07001547 * @param dhcpPayload the DHCP data
1548 */
Taras Lemkin96a0d342018-03-26 14:52:58 +00001549 private void sendResponseToClient(InternalPacket thePacket, DHCP dhcpPayload) {
1550 checkNotNull(thePacket, "Nothing to send");
1551 checkNotNull(thePacket.getPacket(), "Packet to send must not be empty");
1552 checkNotNull(thePacket.getDestLocation(), "Packet destination not be empty");
1553
1554 Ethernet ethPacket = thePacket.getPacket();
Yi Tsengdcef2c22017-08-05 20:34:06 -07001555 if (directlyConnected(dhcpPayload)) {
1556 ethPacket = removeRelayAgentOption(ethPacket);
1557 }
Taras Lemkin96a0d342018-03-26 14:52:58 +00001558
Yi Tsengdcef2c22017-08-05 20:34:06 -07001559 TrafficTreatment treatment = DefaultTrafficTreatment.builder()
Taras Lemkin96a0d342018-03-26 14:52:58 +00001560 .setOutput(thePacket.getDestLocation().port())
Yi Tsengdcef2c22017-08-05 20:34:06 -07001561 .build();
1562 OutboundPacket o = new DefaultOutboundPacket(
Taras Lemkin96a0d342018-03-26 14:52:58 +00001563 thePacket.getDestLocation().deviceId(),
Yi Tsengdcef2c22017-08-05 20:34:06 -07001564 treatment,
1565 ByteBuffer.wrap(ethPacket.serialize()));
1566 if (log.isTraceEnabled()) {
Taras Lemkin96a0d342018-03-26 14:52:58 +00001567 log.trace("Relaying packet to DHCP client {} via {}",
Yi Tsengdcef2c22017-08-05 20:34:06 -07001568 ethPacket,
Taras Lemkin96a0d342018-03-26 14:52:58 +00001569 thePacket.getDestLocation());
Yi Tsengdcef2c22017-08-05 20:34:06 -07001570 }
1571 packetService.emit(o);
Yi Tseng51301292017-07-28 13:02:59 -07001572 }
Yi Tseng483ac6f2017-08-02 15:03:31 -07001573
Yi Tsengaa417a62017-09-08 17:22:51 -07001574 @Override
1575 public void triggerProbe(Host host) {
1576 // Do nothing here
1577 }
1578
1579 @Override
1580 public ProviderId id() {
Charles Chand988c282017-09-12 17:09:32 -07001581 return PROVIDER_ID;
Yi Tsengaa417a62017-09-08 17:22:51 -07001582 }
1583
Yi Tseng483ac6f2017-08-02 15:03:31 -07001584 class InternalHostListener implements HostListener {
1585 @Override
1586 public void event(HostEvent event) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001587 if (!configured()) {
1588 return;
1589 }
Yi Tseng483ac6f2017-08-02 15:03:31 -07001590 switch (event.type()) {
1591 case HOST_ADDED:
1592 case HOST_UPDATED:
Charles Chan24a96ff2018-08-13 10:32:03 -07001593 case HOST_MOVED:
Jordan Halterman6328db72018-04-10 13:34:50 -04001594 log.trace("Scheduled host event {}", event);
1595 hostEventExecutor.execute(() -> hostUpdated(event.subject()));
Yi Tseng483ac6f2017-08-02 15:03:31 -07001596 break;
1597 case HOST_REMOVED:
Jordan Halterman6328db72018-04-10 13:34:50 -04001598 log.trace("Scheduled host event {}", event);
1599 hostEventExecutor.execute(() -> hostRemoved(event.subject()));
Yi Tseng483ac6f2017-08-02 15:03:31 -07001600 break;
Yi Tseng483ac6f2017-08-02 15:03:31 -07001601 default:
1602 break;
1603 }
1604 }
1605 }
1606
1607 /**
Yi Tseng483ac6f2017-08-02 15:03:31 -07001608 * Handle host updated.
1609 * If the host is DHCP server or gateway, update connect mac and vlan.
1610 *
1611 * @param host the host
1612 */
1613 private void hostUpdated(Host host) {
Yi Tseng525ff402017-10-23 19:39:39 -07001614 hostUpdated(host, defaultServerInfoList);
1615 hostUpdated(host, indirectServerInfoList);
Yi Tseng483ac6f2017-08-02 15:03:31 -07001616 }
1617
Yi Tseng525ff402017-10-23 19:39:39 -07001618 private void hostUpdated(Host host, List<DhcpServerInfo> srverInfoList) {
jjosep004c05f55ab2018-08-21 09:01:10 -04001619 srverInfoList.stream().forEach(serverInfo -> {
1620 Ip4Address targetIp = serverInfo.getDhcpGatewayIp4().orElse(null);
Yi Tseng525ff402017-10-23 19:39:39 -07001621 Ip4Address serverIp = serverInfo.getDhcpServerIp4().orElse(null);
Yi Tseng525ff402017-10-23 19:39:39 -07001622 if (targetIp == null) {
1623 targetIp = serverIp;
1624 }
Yi Tseng525ff402017-10-23 19:39:39 -07001625 if (targetIp != null) {
1626 if (host.ipAddresses().contains(targetIp)) {
1627 serverInfo.setDhcpConnectMac(host.mac());
1628 serverInfo.setDhcpConnectVlan(host.vlan());
1629 requestDhcpPacket(serverIp);
1630 }
1631 }
jjosep004c05f55ab2018-08-21 09:01:10 -04001632 });
Yi Tseng525ff402017-10-23 19:39:39 -07001633 }
1634
1635
Yi Tseng483ac6f2017-08-02 15:03:31 -07001636 /**
1637 * Handle host removed.
1638 * If the host is DHCP server or gateway, unset connect mac and vlan.
1639 *
1640 * @param host the host
1641 */
1642 private void hostRemoved(Host host) {
Yi Tseng525ff402017-10-23 19:39:39 -07001643 hostRemoved(host, defaultServerInfoList);
1644 hostRemoved(host, indirectServerInfoList);
1645 }
1646
1647 private void hostRemoved(Host host, List<DhcpServerInfo> serverInfoList) {
jjosep004c05f55ab2018-08-21 09:01:10 -04001648 serverInfoList.stream().forEach(serverInfo -> {
1649 Ip4Address targetIp = serverInfo.getDhcpGatewayIp4().orElse(null);
Yi Tseng525ff402017-10-23 19:39:39 -07001650 Ip4Address serverIp = serverInfo.getDhcpServerIp4().orElse(null);
Yi Tseng525ff402017-10-23 19:39:39 -07001651 if (targetIp == null) {
1652 targetIp = serverIp;
Yi Tseng919b2df2017-09-07 16:22:51 -07001653 }
Yi Tseng525ff402017-10-23 19:39:39 -07001654
1655 if (targetIp != null) {
1656 if (host.ipAddresses().contains(targetIp)) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001657 serverInfo.setDhcpConnectVlan(null);
1658 serverInfo.setDhcpConnectMac(null);
Yi Tseng525ff402017-10-23 19:39:39 -07001659 cancelDhcpPacket(serverIp);
Yi Tseng919b2df2017-09-07 16:22:51 -07001660 }
Yi Tseng483ac6f2017-08-02 15:03:31 -07001661 }
jjosep004c05f55ab2018-08-21 09:01:10 -04001662 });
Yi Tseng525ff402017-10-23 19:39:39 -07001663 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001664
Yi Tseng525ff402017-10-23 19:39:39 -07001665 private void requestDhcpPacket(Ip4Address serverIp) {
1666 requestServerDhcpPacket(serverIp);
1667 requestClientDhcpPacket(serverIp);
1668 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001669
Yi Tseng525ff402017-10-23 19:39:39 -07001670 private void cancelDhcpPacket(Ip4Address serverIp) {
1671 cancelServerDhcpPacket(serverIp);
1672 cancelClientDhcpPacket(serverIp);
1673 }
1674
1675 private void cancelServerDhcpPacket(Ip4Address serverIp) {
1676 TrafficSelector serverSelector =
1677 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1678 .matchIPSrc(serverIp.toIpPrefix())
1679 .build();
1680 packetService.cancelPackets(serverSelector,
1681 PacketPriority.CONTROL,
1682 appId);
1683 }
1684
1685 private void requestServerDhcpPacket(Ip4Address serverIp) {
1686 TrafficSelector serverSelector =
1687 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1688 .matchIPSrc(serverIp.toIpPrefix())
1689 .build();
1690 packetService.requestPackets(serverSelector,
1691 PacketPriority.CONTROL,
1692 appId);
1693 }
1694
1695 private void cancelClientDhcpPacket(Ip4Address serverIp) {
1696 // Packet comes from relay
1697 TrafficSelector indirectClientSelector =
1698 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1699 .matchIPDst(serverIp.toIpPrefix())
1700 .build();
1701 packetService.cancelPackets(indirectClientSelector,
1702 PacketPriority.CONTROL,
1703 appId);
1704
1705 // Packet comes from client
1706 packetService.cancelPackets(CLIENT_SERVER_SELECTOR,
1707 PacketPriority.CONTROL,
1708 appId);
1709 }
1710
1711 private void requestClientDhcpPacket(Ip4Address serverIp) {
1712 // Packet comes from relay
1713 TrafficSelector indirectClientSelector =
1714 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1715 .matchIPDst(serverIp.toIpPrefix())
1716 .build();
1717 packetService.requestPackets(indirectClientSelector,
1718 PacketPriority.CONTROL,
1719 appId);
1720
1721 // Packet comes from client
1722 packetService.requestPackets(CLIENT_SERVER_SELECTOR,
1723 PacketPriority.CONTROL,
1724 appId);
1725 }
1726
1727 /**
1728 * Process the ignore rules.
1729 *
1730 * @param deviceId the device id
1731 * @param vlanId the vlan to be ignored
1732 * @param op the operation, ADD to install; REMOVE to uninstall rules
1733 */
1734 private void processIgnoreVlanRule(DeviceId deviceId, VlanId vlanId, Objective.Operation op) {
Yi Tseng525ff402017-10-23 19:39:39 -07001735 AtomicInteger installedCount = new AtomicInteger(DHCP_SELECTORS.size());
1736 DHCP_SELECTORS.forEach(trafficSelector -> {
1737 TrafficSelector selector = DefaultTrafficSelector.builder(trafficSelector)
1738 .matchVlanId(vlanId)
1739 .build();
1740
1741 ForwardingObjective.Builder builder = DefaultForwardingObjective.builder()
1742 .withFlag(ForwardingObjective.Flag.VERSATILE)
1743 .withSelector(selector)
1744 .withPriority(IGNORE_CONTROL_PRIORITY)
Yi Tsengdbabeed2017-11-29 10:49:20 -08001745 .withTreatment(DefaultTrafficTreatment.emptyTreatment())
Yi Tseng525ff402017-10-23 19:39:39 -07001746 .fromApp(appId);
1747
1748
1749 ObjectiveContext objectiveContext = new ObjectiveContext() {
1750 @Override
1751 public void onSuccess(Objective objective) {
1752 log.info("Ignore rule {} (Vlan id {}, device {}, selector {})",
1753 op, vlanId, deviceId, selector);
1754 int countDown = installedCount.decrementAndGet();
1755 if (countDown != 0) {
1756 return;
1757 }
1758 switch (op) {
1759 case ADD:
1760 ignoredVlans.put(deviceId, vlanId);
1761 break;
1762 case REMOVE:
1763 ignoredVlans.remove(deviceId, vlanId);
1764 break;
1765 default:
1766 log.warn("Unsupported objective operation {}", op);
1767 break;
1768 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001769 }
Yi Tseng525ff402017-10-23 19:39:39 -07001770
1771 @Override
1772 public void onError(Objective objective, ObjectiveError error) {
1773 log.warn("Can't {} ignore rule (vlan id {}, selector {}, device {}) due to {}",
1774 op, vlanId, selector, deviceId, error);
Yi Tseng919b2df2017-09-07 16:22:51 -07001775 }
Yi Tseng525ff402017-10-23 19:39:39 -07001776 };
1777
1778 ForwardingObjective fwd;
1779 switch (op) {
1780 case ADD:
1781 fwd = builder.add(objectiveContext);
1782 break;
1783 case REMOVE:
1784 fwd = builder.remove(objectiveContext);
1785 break;
1786 default:
1787 log.warn("Unsupported objective operation {}", op);
1788 return;
Yi Tseng4f2a0462017-08-31 11:21:00 -07001789 }
Yi Tseng525ff402017-10-23 19:39:39 -07001790
1791 Device device = deviceService.getDevice(deviceId);
1792 if (device == null || !device.is(Pipeliner.class)) {
1793 log.warn("Device {} is not available now, wait until device is available", deviceId);
1794 return;
1795 }
1796 flowObjectiveService.apply(deviceId, fwd);
1797 });
Yi Tseng483ac6f2017-08-02 15:03:31 -07001798 }
Kalhee Kimba366062017-11-07 16:32:09 +00001799
1800 @Override
1801 public void setDhcpFpmEnabled(Boolean enabled) {
1802 // v4 does not use fpm. Do nothing.
1803 }
rsahot036620655b2018-02-26 15:01:37 -05001804 private List<DhcpServerInfo> findValidServerInfo(boolean directConnFlag) {
1805 List<DhcpServerInfo> validServerInfo;
1806
1807 if (directConnFlag || indirectServerInfoList.isEmpty()) {
1808 validServerInfo = new ArrayList<DhcpServerInfo>(defaultServerInfoList);
1809 } else {
1810 validServerInfo = new ArrayList<DhcpServerInfo>(indirectServerInfoList);
1811 }
1812 return validServerInfo;
1813 }
1814
1815
1816 private boolean checkDhcpServerConnPt(boolean directConnFlag,
1817 DhcpServerInfo serverInfo) {
1818 if (serverInfo.getDhcpServerConnectPoint() == null) {
1819 log.warn("DHCP4 server connect point for {} connPt {}",
1820 directConnFlag ? "direct" : "indirect", serverInfo.getDhcpServerConnectPoint());
1821 return false;
1822 }
1823 return true;
1824 }
1825
1826 /**
1827 * Checks if serverInfo's host info (mac and vlan) is filled in; if not, fills in.
1828 *
1829 * @param serverInfo server information
1830 * @return newServerInfo if host info can be either found or filled in.
1831 */
1832 private DhcpServerInfo getHostInfoForServerInfo(DhcpServerInfo serverInfo, List<DhcpServerInfo> sererInfoList) {
1833 DhcpServerInfo newServerInfo = null;
1834 MacAddress dhcpServerConnectMac = serverInfo.getDhcpConnectMac().orElse(null);
1835 VlanId dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1836 ConnectPoint dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1837
1838 if (dhcpServerConnectMac != null && dhcpConnectVlan != null) {
1839 newServerInfo = serverInfo;
Charles Chan2de55302018-03-02 18:27:59 -08001840 log.debug("DHCP server {} host info found. ConnectPt{} Mac {} vlan {}", serverInfo.getDhcpServerIp4(),
rsahot036620655b2018-02-26 15:01:37 -05001841 dhcpServerConnectPoint, dhcpServerConnectMac, dhcpConnectVlan);
1842 } else {
1843 log.warn("DHCP server {} not resolve yet connectPt {} mac {} vlan {}", serverInfo.getDhcpServerIp4(),
1844 dhcpServerConnectPoint, dhcpServerConnectMac, dhcpConnectVlan);
1845
1846 Ip4Address ipToProbe;
1847 if (serverInfo.getDhcpGatewayIp4().isPresent()) {
1848 ipToProbe = serverInfo.getDhcpGatewayIp4().get();
1849 } else {
1850 ipToProbe = serverInfo.getDhcpServerIp4().orElse(null);
1851 }
1852 String hostToProbe = serverInfo.getDhcpGatewayIp6()
1853 .map(ip -> "gateway").orElse("server");
1854
1855 log.warn("Dynamically probing to resolve {} IP {}", hostToProbe, ipToProbe);
1856 hostService.startMonitoringIp(ipToProbe);
1857
1858 Set<Host> hosts = hostService.getHostsByIp(ipToProbe);
1859 if (!hosts.isEmpty()) {
1860 int serverInfoIndex = sererInfoList.indexOf(serverInfo);
1861 Host host = hosts.iterator().next();
1862 serverInfo.setDhcpConnectVlan(host.vlan());
1863 serverInfo.setDhcpConnectMac(host.mac());
1864 // replace the serverInfo in the list
1865 sererInfoList.set(serverInfoIndex, serverInfo);
1866 newServerInfo = serverInfo;
1867 log.warn("Dynamically host found host {}", host);
1868 } else {
1869 log.warn("No host found host ip {} dynamically", ipToProbe);
1870 }
1871 }
1872 return newServerInfo;
1873 }
1874
1875 /**
1876 * Gets Interface facing to the server for default host.
1877 *
1878 * @param serverInfo server information
1879 * @return the Interface facing to the server; null if not found
1880 */
1881 private Interface getServerInterface(DhcpServerInfo serverInfo) {
1882 Interface serverInterface = null;
1883
1884 ConnectPoint dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1885 VlanId dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1886
1887 if (dhcpServerConnectPoint != null && dhcpConnectVlan != null) {
1888 serverInterface = interfaceService.getInterfacesByPort(dhcpServerConnectPoint)
1889 .stream()
Taras Lemkin96a0d342018-03-26 14:52:58 +00001890 .filter(iface -> Dhcp4HandlerUtil.interfaceContainsVlan(iface, dhcpConnectVlan))
rsahot036620655b2018-02-26 15:01:37 -05001891 .findFirst()
1892 .orElse(null);
1893 } else {
1894 log.warn("DHCP server {} not resolve yet connectPoint {} vlan {}", serverInfo.getDhcpServerIp6(),
1895 dhcpServerConnectPoint, dhcpConnectVlan);
1896 }
1897
1898 return serverInterface;
1899 }
1900
1901 //forward the packet to ConnectPoint where the DHCP server is attached.
1902 private void forwardPacket(InternalPacket packet) {
1903 //send Packetout to dhcp server connectpoint.
Taras Lemkin96a0d342018-03-26 14:52:58 +00001904 if (packet.getDestLocation() != null) {
rsahot036620655b2018-02-26 15:01:37 -05001905 TrafficTreatment t = DefaultTrafficTreatment.builder()
Taras Lemkin96a0d342018-03-26 14:52:58 +00001906 .setOutput(packet.getDestLocation().port()).build();
rsahot036620655b2018-02-26 15:01:37 -05001907 OutboundPacket o = new DefaultOutboundPacket(
Taras Lemkin96a0d342018-03-26 14:52:58 +00001908 packet.getDestLocation().deviceId(), t, ByteBuffer.wrap(packet.getPacket().serialize()));
rsahot036620655b2018-02-26 15:01:37 -05001909 if (log.isTraceEnabled()) {
Taras Lemkin96a0d342018-03-26 14:52:58 +00001910 log.trace("Relaying packet to destination {}", packet.getDestLocation());
rsahot036620655b2018-02-26 15:01:37 -05001911 }
Taras Lemkin96a0d342018-03-26 14:52:58 +00001912 log.debug("packetService.emit(o) to port {}", packet.getDestLocation());
rsahot036620655b2018-02-26 15:01:37 -05001913 packetService.emit(o);
1914 }
1915 }
1916
1917
1918 private DhcpServerInfo findServerInfoFromServer(boolean directConnFlag, ConnectPoint inPort) {
1919 List<DhcpServerInfo> validServerInfoList = findValidServerInfo(directConnFlag);
1920 DhcpServerInfo foundServerInfo = null;
1921 for (DhcpServerInfo serverInfo : validServerInfoList) {
1922 if (inPort.equals(serverInfo.getDhcpServerConnectPoint().get())) {
1923 foundServerInfo = serverInfo;
Charles Chan2de55302018-03-02 18:27:59 -08001924 log.debug("ServerInfo found for Rcv port {} Server Connect Point {} for {}",
rsahot036620655b2018-02-26 15:01:37 -05001925 inPort, serverInfo.getDhcpServerConnectPoint(), directConnFlag ? "direct" : "indirect");
1926 break;
1927 } else {
1928 log.warn("Rcv port {} not the same as Server Connect Point {} for {}",
1929 inPort, serverInfo.getDhcpServerConnectPoint(), directConnFlag ? "direct" : "indirect");
1930 }
1931 }
1932 return foundServerInfo;
1933 }
Yi Tseng51301292017-07-28 13:02:59 -07001934}