blob: 14ee7004d462aa74bbb000cfc036b9616afb8894 [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 Tseng483ac6f2017-08-02 15:03:31 -070026import org.apache.felix.scr.annotations.Activate;
Yi Tseng51301292017-07-28 13:02:59 -070027import org.apache.felix.scr.annotations.Component;
Yi Tseng483ac6f2017-08-02 15:03:31 -070028import org.apache.felix.scr.annotations.Deactivate;
Taras Lemkin96a0d342018-03-26 14:52:58 +000029import org.apache.felix.scr.annotations.Modified;
Yi Tseng51301292017-07-28 13:02:59 -070030import org.apache.felix.scr.annotations.Property;
31import org.apache.felix.scr.annotations.Reference;
32import org.apache.felix.scr.annotations.ReferenceCardinality;
33import org.apache.felix.scr.annotations.Service;
34import org.onlab.packet.BasePacket;
35import org.onlab.packet.DHCP;
36import org.onlab.packet.Ethernet;
37import org.onlab.packet.IPv4;
38import org.onlab.packet.Ip4Address;
39import org.onlab.packet.IpAddress;
40import org.onlab.packet.MacAddress;
Yi Tseng525ff402017-10-23 19:39:39 -070041import org.onlab.packet.TpPort;
Yi Tseng51301292017-07-28 13:02:59 -070042import org.onlab.packet.UDP;
43import org.onlab.packet.VlanId;
44import org.onlab.packet.dhcp.CircuitId;
45import org.onlab.packet.dhcp.DhcpOption;
46import org.onlab.packet.dhcp.DhcpRelayAgentOption;
Taras Lemkin96a0d342018-03-26 14:52:58 +000047import org.onlab.util.Tools;
48import org.onosproject.cfg.ComponentConfigService;
Yi Tseng525ff402017-10-23 19:39:39 -070049import org.onosproject.core.ApplicationId;
50import org.onosproject.core.CoreService;
Yi Tseng51301292017-07-28 13:02:59 -070051import org.onosproject.dhcprelay.api.DhcpHandler;
Yi Tseng919b2df2017-09-07 16:22:51 -070052import org.onosproject.dhcprelay.api.DhcpServerInfo;
Yi Tseng483ac6f2017-08-02 15:03:31 -070053import org.onosproject.dhcprelay.config.DhcpServerConfig;
Yi Tseng525ff402017-10-23 19:39:39 -070054import org.onosproject.dhcprelay.config.IgnoreDhcpConfig;
Yi Tseng51301292017-07-28 13:02:59 -070055import org.onosproject.dhcprelay.store.DhcpRecord;
56import org.onosproject.dhcprelay.store.DhcpRelayStore;
Yi Tseng525ff402017-10-23 19:39:39 -070057import org.onosproject.net.Device;
58import org.onosproject.net.DeviceId;
59import org.onosproject.net.behaviour.Pipeliner;
60import org.onosproject.net.device.DeviceService;
61import org.onosproject.net.flow.DefaultTrafficSelector;
62import org.onosproject.net.flow.TrafficSelector;
63import org.onosproject.net.flowobjective.DefaultForwardingObjective;
64import org.onosproject.net.flowobjective.FlowObjectiveService;
65import org.onosproject.net.flowobjective.ForwardingObjective;
66import org.onosproject.net.flowobjective.Objective;
67import org.onosproject.net.flowobjective.ObjectiveContext;
68import org.onosproject.net.flowobjective.ObjectiveError;
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;
Ray Milkeyfacf2862017-08-03 11:58:29 -070074import org.onosproject.net.intf.Interface;
75import org.onosproject.net.intf.InterfaceService;
Yi Tseng525ff402017-10-23 19:39:39 -070076import org.onosproject.net.packet.PacketPriority;
Yi Tsengaa417a62017-09-08 17:22:51 -070077import org.onosproject.net.provider.ProviderId;
Ray Milkey69ec8712017-08-08 13:00:43 -070078import org.onosproject.routeservice.Route;
79import org.onosproject.routeservice.RouteStore;
Yi Tseng51301292017-07-28 13:02:59 -070080import org.onosproject.net.ConnectPoint;
81import org.onosproject.net.Host;
82import org.onosproject.net.HostId;
83import org.onosproject.net.HostLocation;
84import org.onosproject.net.flow.DefaultTrafficTreatment;
85import org.onosproject.net.flow.TrafficTreatment;
86import org.onosproject.net.host.DefaultHostDescription;
87import org.onosproject.net.host.HostDescription;
88import org.onosproject.net.host.HostService;
Yi Tseng51301292017-07-28 13:02:59 -070089import org.onosproject.net.host.InterfaceIpAddress;
90import org.onosproject.net.packet.DefaultOutboundPacket;
91import org.onosproject.net.packet.OutboundPacket;
92import org.onosproject.net.packet.PacketContext;
93import org.onosproject.net.packet.PacketService;
Taras Lemkin96a0d342018-03-26 14:52:58 +000094import org.osgi.service.component.ComponentContext;
Yi Tseng51301292017-07-28 13:02:59 -070095import org.slf4j.Logger;
96import org.slf4j.LoggerFactory;
97
98import java.nio.ByteBuffer;
Taras Lemkin96a0d342018-03-26 14:52:58 +000099import java.util.ArrayList;
Yi Tsengdcef2c22017-08-05 20:34:06 -0700100import java.util.Collection;
Yi Tseng51301292017-07-28 13:02:59 -0700101import java.util.Collections;
Taras Lemkin96a0d342018-03-26 14:52:58 +0000102import java.util.Dictionary;
Yi Tseng51301292017-07-28 13:02:59 -0700103import java.util.List;
104import java.util.Optional;
105import java.util.Set;
Charles Chan909cff82018-03-05 13:14:02 -0800106import java.util.concurrent.CopyOnWriteArrayList;
Jordan Halterman6328db72018-04-10 13:34:50 -0400107import java.util.concurrent.Executor;
Yi Tseng525ff402017-10-23 19:39:39 -0700108import java.util.concurrent.atomic.AtomicInteger;
Yi Tseng51301292017-07-28 13:02:59 -0700109import java.util.stream.Collectors;
110
111import static com.google.common.base.Preconditions.checkNotNull;
112import static com.google.common.base.Preconditions.checkState;
Jordan Halterman6328db72018-04-10 13:34:50 -0400113import static java.util.concurrent.Executors.newSingleThreadExecutor;
Yi Tseng51301292017-07-28 13:02:59 -0700114import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_CircuitID;
115import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_END;
116import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_MessageType;
117import static org.onlab.packet.MacAddress.valueOf;
118import static org.onlab.packet.dhcp.DhcpRelayAgentOption.RelayAgentInfoOptions.CIRCUIT_ID;
Jordan Halterman6328db72018-04-10 13:34:50 -0400119import static org.onlab.util.Tools.groupedThreads;
Yi Tseng525ff402017-10-23 19:39:39 -0700120import static org.onosproject.net.flowobjective.Objective.Operation.ADD;
121import static org.onosproject.net.flowobjective.Objective.Operation.REMOVE;
Yi Tseng51301292017-07-28 13:02:59 -0700122
rsahot036620655b2018-02-26 15:01:37 -0500123
Yi Tseng51301292017-07-28 13:02:59 -0700124@Component
125@Service
126@Property(name = "version", value = "4")
Yi Tsengaa417a62017-09-08 17:22:51 -0700127public class Dhcp4HandlerImpl implements DhcpHandler, HostProvider {
Charles Chand988c282017-09-12 17:09:32 -0700128 public static final String DHCP_V4_RELAY_APP = "org.onosproject.Dhcp4HandlerImpl";
129 public static final ProviderId PROVIDER_ID = new ProviderId("dhcp4", DHCP_V4_RELAY_APP);
Yi Tseng525ff402017-10-23 19:39:39 -0700130 private static final String BROADCAST_IP = "255.255.255.255";
131 private static final int IGNORE_CONTROL_PRIORITY = PacketPriority.CONTROL.priorityValue() + 1000;
132
Taras Lemkin96a0d342018-03-26 14:52:58 +0000133 private static final String LQ_ROUTE_PROPERTY_NAME = "learnRouteFromLeasequery";
134
Yi Tseng525ff402017-10-23 19:39:39 -0700135 private static final TrafficSelector CLIENT_SERVER_SELECTOR = DefaultTrafficSelector.builder()
136 .matchEthType(Ethernet.TYPE_IPV4)
137 .matchIPProtocol(IPv4.PROTOCOL_UDP)
138 .matchIPSrc(Ip4Address.ZERO.toIpPrefix())
139 .matchIPDst(Ip4Address.valueOf(BROADCAST_IP).toIpPrefix())
140 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_CLIENT_PORT))
141 .matchUdpDst(TpPort.tpPort(UDP.DHCP_SERVER_PORT))
142 .build();
143 private static final TrafficSelector SERVER_RELAY_SELECTOR = DefaultTrafficSelector.builder()
144 .matchEthType(Ethernet.TYPE_IPV4)
145 .matchIPProtocol(IPv4.PROTOCOL_UDP)
146 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_SERVER_PORT))
147 .matchUdpDst(TpPort.tpPort(UDP.DHCP_SERVER_PORT))
148 .build();
149 static final Set<TrafficSelector> DHCP_SELECTORS = ImmutableSet.of(
150 CLIENT_SERVER_SELECTOR,
151 SERVER_RELAY_SELECTOR
152 );
Yi Tseng51301292017-07-28 13:02:59 -0700153 private static Logger log = LoggerFactory.getLogger(Dhcp4HandlerImpl.class);
154
155 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
156 protected DhcpRelayStore dhcpRelayStore;
157
158 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
159 protected PacketService packetService;
160
161 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yi Tseng51301292017-07-28 13:02:59 -0700162 protected RouteStore routeStore;
163
164 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
165 protected InterfaceService interfaceService;
166
167 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
168 protected HostService hostService;
169
Yi Tsengaa417a62017-09-08 17:22:51 -0700170 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
171 protected HostProviderRegistry providerRegistry;
172
Yi Tseng525ff402017-10-23 19:39:39 -0700173 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
174 protected CoreService coreService;
175
176 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
177 protected DeviceService deviceService;
178
179 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
180 protected FlowObjectiveService flowObjectiveService;
181
Taras Lemkin96a0d342018-03-26 14:52:58 +0000182 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
183 protected ComponentConfigService cfgService;
184
Yi Tsengaa417a62017-09-08 17:22:51 -0700185 protected HostProviderService providerService;
Yi Tseng525ff402017-10-23 19:39:39 -0700186 protected ApplicationId appId;
Charles Chan70fdd492018-03-07 17:36:06 -0800187 protected Multimap<DeviceId, VlanId> ignoredVlans = Multimaps.synchronizedMultimap(HashMultimap.create());
Yi Tseng483ac6f2017-08-02 15:03:31 -0700188 private InternalHostListener hostListener = new InternalHostListener();
189
Charles Chan909cff82018-03-05 13:14:02 -0800190 private List<DhcpServerInfo> defaultServerInfoList = new CopyOnWriteArrayList<>();
191 private List<DhcpServerInfo> indirectServerInfoList = new CopyOnWriteArrayList<>();
Taras Lemkin96a0d342018-03-26 14:52:58 +0000192
193 @Property(name = Dhcp4HandlerImpl.LQ_ROUTE_PROPERTY_NAME, boolValue = false,
194 label = "Enable learning routing information from LQ")
195 private Boolean learnRouteFromLeasequery = Boolean.TRUE;
Yi Tseng4f2a0462017-08-31 11:21:00 -0700196
Jordan Halterman6328db72018-04-10 13:34:50 -0400197 private Executor hostEventExecutor = newSingleThreadExecutor(
198 groupedThreads("dhcp4-event-host", "%d", log));
199
Yi Tseng483ac6f2017-08-02 15:03:31 -0700200 @Activate
Taras Lemkin96a0d342018-03-26 14:52:58 +0000201 protected void activate(ComponentContext context) {
202 cfgService.registerProperties(getClass());
203 modified(context);
Yi Tseng525ff402017-10-23 19:39:39 -0700204 appId = coreService.registerApplication(DHCP_V4_RELAY_APP);
Yi Tseng483ac6f2017-08-02 15:03:31 -0700205 hostService.addListener(hostListener);
Yi Tsengaa417a62017-09-08 17:22:51 -0700206 providerService = providerRegistry.register(this);
Yi Tseng483ac6f2017-08-02 15:03:31 -0700207 }
208
209 @Deactivate
210 protected void deactivate() {
Taras Lemkin96a0d342018-03-26 14:52:58 +0000211 cfgService.unregisterProperties(getClass(), false);
Yi Tsengaa417a62017-09-08 17:22:51 -0700212 providerRegistry.unregister(this);
213 hostService.removeListener(hostListener);
Yi Tseng919b2df2017-09-07 16:22:51 -0700214 defaultServerInfoList.forEach(this::stopMonitoringIps);
Charles Chanfc1c22e2018-07-19 09:52:01 -0700215 defaultServerInfoList.forEach(info -> info.getDhcpServerIp4().ifPresent(this::cancelDhcpPacket));
Yi Tseng919b2df2017-09-07 16:22:51 -0700216 defaultServerInfoList.clear();
217 indirectServerInfoList.forEach(this::stopMonitoringIps);
Charles Chanfc1c22e2018-07-19 09:52:01 -0700218 indirectServerInfoList.forEach(info -> info.getDhcpServerIp4().ifPresent(this::cancelDhcpPacket));
Yi Tseng919b2df2017-09-07 16:22:51 -0700219 indirectServerInfoList.clear();
Yi Tseng483ac6f2017-08-02 15:03:31 -0700220 }
221
Taras Lemkin96a0d342018-03-26 14:52:58 +0000222 @Modified
223 protected void modified(ComponentContext context) {
224 Dictionary<?, ?> properties = context.getProperties();
225 Boolean flag;
226 flag = Tools.isPropertyEnabled(properties, Dhcp4HandlerImpl.LQ_ROUTE_PROPERTY_NAME);
227 if (flag != null) {
228 learnRouteFromLeasequery = flag;
229 log.info("Learning routes from DHCP leasequery is {}",
230 learnRouteFromLeasequery ? "enabled" : "disabled");
231 }
232 }
233
Yi Tseng919b2df2017-09-07 16:22:51 -0700234 private void stopMonitoringIps(DhcpServerInfo serverInfo) {
235 serverInfo.getDhcpGatewayIp4().ifPresent(gatewayIp -> {
236 hostService.stopMonitoringIp(gatewayIp);
237 });
238 serverInfo.getDhcpServerIp4().ifPresent(serverIp -> {
239 hostService.stopMonitoringIp(serverIp);
240 });
Yi Tseng51301292017-07-28 13:02:59 -0700241 }
242
243 @Override
Yi Tseng483ac6f2017-08-02 15:03:31 -0700244 public void setDefaultDhcpServerConfigs(Collection<DhcpServerConfig> configs) {
Yi Tseng919b2df2017-09-07 16:22:51 -0700245 setDhcpServerConfigs(configs, defaultServerInfoList);
246 }
247
248 @Override
249 public void setIndirectDhcpServerConfigs(Collection<DhcpServerConfig> configs) {
250 setDhcpServerConfigs(configs, indirectServerInfoList);
251 }
252
253 @Override
254 public List<DhcpServerInfo> getDefaultDhcpServerInfoList() {
255 return defaultServerInfoList;
256 }
257
258 @Override
259 public List<DhcpServerInfo> getIndirectDhcpServerInfoList() {
260 return indirectServerInfoList;
261 }
262
Yi Tseng525ff402017-10-23 19:39:39 -0700263 @Override
264 public void updateIgnoreVlanConfig(IgnoreDhcpConfig config) {
265 if (config == null) {
266 ignoredVlans.forEach(((deviceId, vlanId) -> {
267 processIgnoreVlanRule(deviceId, vlanId, REMOVE);
268 }));
269 return;
270 }
271 config.ignoredVlans().forEach((deviceId, vlanId) -> {
272 if (ignoredVlans.get(deviceId).contains(vlanId)) {
273 // don't need to process if it already ignored
274 return;
275 }
276 processIgnoreVlanRule(deviceId, vlanId, ADD);
277 });
278
279 ignoredVlans.forEach((deviceId, vlanId) -> {
280 if (!config.ignoredVlans().get(deviceId).contains(vlanId)) {
281 // not contains in new config, remove it
282 processIgnoreVlanRule(deviceId, vlanId, REMOVE);
283 }
284 });
285 }
286
Saurav Dasb805f1a2017-12-13 16:19:35 -0800287 @Override
288 public void removeIgnoreVlanState(IgnoreDhcpConfig config) {
289 if (config == null) {
290 ignoredVlans.clear();
291 return;
292 }
293 config.ignoredVlans().forEach((deviceId, vlanId) -> {
294 ignoredVlans.remove(deviceId, vlanId);
295 });
296 }
297
Yi Tseng919b2df2017-09-07 16:22:51 -0700298 public void setDhcpServerConfigs(Collection<DhcpServerConfig> configs, List<DhcpServerInfo> serverInfoList) {
Yi Tseng483ac6f2017-08-02 15:03:31 -0700299 if (configs.size() == 0) {
300 // no config to update
301 return;
302 }
303
rsahot036620655b2018-02-26 15:01:37 -0500304 Boolean isConfigValid = false;
305 for (DhcpServerConfig serverConfig : configs) {
306 if (serverConfig.getDhcpServerIp4().isPresent()) {
307 isConfigValid = true;
308 break;
309 }
Yi Tseng483ac6f2017-08-02 15:03:31 -0700310 }
rsahot036620655b2018-02-26 15:01:37 -0500311 if (!isConfigValid) {
312 log.warn("No IP V4 server address found.");
313 return; // No IP V6 address found
314 }
315 // if (!serverInfoList.isEmpty()) {
316 for (DhcpServerInfo oldServerInfo : serverInfoList) {
317 log.info("In for (DhcpServerInfo oldServerInfo : serverInfoList) {");
Yi Tseng919b2df2017-09-07 16:22:51 -0700318 // remove old server info
rsahot036620655b2018-02-26 15:01:37 -0500319 //DhcpServerInfo oldServerInfo = serverInfoList.remove(0);
Yi Tseng483ac6f2017-08-02 15:03:31 -0700320
Yi Tseng919b2df2017-09-07 16:22:51 -0700321 // stop monitoring gateway or server
322 oldServerInfo.getDhcpGatewayIp4().ifPresent(gatewayIp -> {
323 hostService.stopMonitoringIp(gatewayIp);
324 });
325 oldServerInfo.getDhcpServerIp4().ifPresent(serverIp -> {
326 hostService.stopMonitoringIp(serverIp);
Yi Tseng525ff402017-10-23 19:39:39 -0700327 cancelDhcpPacket(serverIp);
Yi Tseng919b2df2017-09-07 16:22:51 -0700328 });
Yi Tseng483ac6f2017-08-02 15:03:31 -0700329 }
Yi Tseng3df7f9d2017-08-17 13:08:31 -0700330
Yi Tseng919b2df2017-09-07 16:22:51 -0700331 // Create new server info according to the config
rsahot036620655b2018-02-26 15:01:37 -0500332 serverInfoList.clear();
333 for (DhcpServerConfig serverConfig : configs) {
Taras Lemkin96a0d342018-03-26 14:52:58 +0000334 log.debug("Create new server info according to the config");
rsahot036620655b2018-02-26 15:01:37 -0500335 DhcpServerInfo newServerInfo = new DhcpServerInfo(serverConfig,
336 DhcpServerInfo.Version.DHCP_V4);
337 checkState(newServerInfo.getDhcpServerConnectPoint().isPresent(),
338 "Connect point not exists");
339 checkState(newServerInfo.getDhcpServerIp4().isPresent(),
340 "IP of DHCP server not exists");
Yi Tseng4f2a0462017-08-31 11:21:00 -0700341
rsahot036620655b2018-02-26 15:01:37 -0500342 log.debug("DHCP server connect point: {}", newServerInfo.getDhcpServerConnectPoint().orElse(null));
343 log.debug("DHCP server IP: {}", newServerInfo.getDhcpServerIp4().orElse(null));
Yi Tseng919b2df2017-09-07 16:22:51 -0700344
rsahot036620655b2018-02-26 15:01:37 -0500345 Ip4Address serverIp = newServerInfo.getDhcpServerIp4().get();
346 Ip4Address ipToProbe;
347 if (newServerInfo.getDhcpGatewayIp4().isPresent()) {
348 ipToProbe = newServerInfo.getDhcpGatewayIp4().get();
349 } else {
350 ipToProbe = newServerInfo.getDhcpServerIp4().orElse(null);
351 }
352 log.info("Probe_IP {}", ipToProbe);
353 String hostToProbe = newServerInfo.getDhcpGatewayIp4()
354 .map(ip -> "gateway").orElse("server");
355
356 log.debug("Probing to resolve {} IP {}", hostToProbe, ipToProbe);
357 hostService.startMonitoringIp(ipToProbe);
358
359 Set<Host> hosts = hostService.getHostsByIp(ipToProbe);
360 if (!hosts.isEmpty()) {
361 Host host = hosts.iterator().next();
362 newServerInfo.setDhcpConnectVlan(host.vlan());
363 newServerInfo.setDhcpConnectMac(host.mac());
364 }
365
366 // Add new server info
367 synchronized (this) {
368 //serverInfoList.clear();
369 serverInfoList.add(newServerInfo);
370 }
371
372 requestDhcpPacket(serverIp);
Yi Tseng4f2a0462017-08-31 11:21:00 -0700373 }
Yi Tseng483ac6f2017-08-02 15:03:31 -0700374 }
375
Yi Tseng3df7f9d2017-08-17 13:08:31 -0700376 @Override
Yi Tseng51301292017-07-28 13:02:59 -0700377 public void processDhcpPacket(PacketContext context, BasePacket payload) {
378 checkNotNull(payload, "DHCP payload can't be null");
379 checkState(payload instanceof DHCP, "Payload is not a DHCP");
380 DHCP dhcpPayload = (DHCP) payload;
381 if (!configured()) {
Yi Tseng919b2df2017-09-07 16:22:51 -0700382 log.warn("Missing default DHCP relay server config. Abort packet processing");
Yi Tseng51301292017-07-28 13:02:59 -0700383 return;
384 }
385
386 ConnectPoint inPort = context.inPacket().receivedFrom();
Yi Tseng51301292017-07-28 13:02:59 -0700387 checkNotNull(dhcpPayload, "Can't find DHCP payload");
388 Ethernet packet = context.inPacket().parsed();
389 DHCP.MsgType incomingPacketType = dhcpPayload.getOptions().stream()
390 .filter(dhcpOption -> dhcpOption.getCode() == OptionCode_MessageType.getValue())
391 .map(DhcpOption::getData)
392 .map(data -> DHCP.MsgType.getType(data[0]))
393 .findFirst()
394 .orElse(null);
395 checkNotNull(incomingPacketType, "Can't get message type from DHCP payload {}", dhcpPayload);
rsahot036620655b2018-02-26 15:01:37 -0500396 Set<Interface> receivingInterfaces = interfaceService.getInterfacesByPort(inPort);
397 //ignore the packets if dhcp client interface is not configured on onos.
398 if (receivingInterfaces.isEmpty()) {
399 log.warn("Virtual interface is not configured on {}", inPort);
400 return;
401 }
Yi Tseng51301292017-07-28 13:02:59 -0700402 switch (incomingPacketType) {
403 case DHCPDISCOVER:
Yi Tsengdcef2c22017-08-05 20:34:06 -0700404 // Add the gateway IP as virtual interface IP for server to understand
Yi Tseng51301292017-07-28 13:02:59 -0700405 // the lease to be assigned and forward the packet to dhcp server.
rsahot036620655b2018-02-26 15:01:37 -0500406 List<InternalPacket> ethernetClientPacket =
407 processDhcpPacketFromClient(context, packet, receivingInterfaces);
408 for (InternalPacket internalPacket : ethernetClientPacket) {
409 log.debug("DHCPDISCOVER from {} Forward to server", inPort);
Yi Tseng51301292017-07-28 13:02:59 -0700410 writeRequestDhcpRecord(inPort, packet, dhcpPayload);
rsahot036620655b2018-02-26 15:01:37 -0500411 forwardPacket(internalPacket);
Yi Tseng51301292017-07-28 13:02:59 -0700412 }
413 break;
414 case DHCPOFFER:
415 //reply to dhcp client.
Taras Lemkin96a0d342018-03-26 14:52:58 +0000416 InternalPacket ethernetPacketOffer = processDhcpPacketFromServer(context, packet);
Yi Tseng51301292017-07-28 13:02:59 -0700417 if (ethernetPacketOffer != null) {
Taras Lemkin96a0d342018-03-26 14:52:58 +0000418 writeResponseDhcpRecord(ethernetPacketOffer.getPacket(), dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -0700419 sendResponseToClient(ethernetPacketOffer, dhcpPayload);
Yi Tseng51301292017-07-28 13:02:59 -0700420 }
421 break;
422 case DHCPREQUEST:
423 // add the gateway ip as virtual interface ip for server to understand
424 // the lease to be assigned and forward the packet to dhcp server.
rsahot036620655b2018-02-26 15:01:37 -0500425 List<InternalPacket> ethernetPacketRequest =
426 processDhcpPacketFromClient(context, packet, receivingInterfaces);
427 for (InternalPacket internalPacket : ethernetPacketRequest) {
428 log.debug("DHCPDISCOVER from {} Forward to server", inPort);
Yi Tseng51301292017-07-28 13:02:59 -0700429 writeRequestDhcpRecord(inPort, packet, dhcpPayload);
rsahot036620655b2018-02-26 15:01:37 -0500430 forwardPacket(internalPacket);
Yi Tseng51301292017-07-28 13:02:59 -0700431 }
432 break;
Charles Chand0dd7002017-10-08 23:53:36 -0400433 case DHCPDECLINE:
434 break;
Yi Tseng51301292017-07-28 13:02:59 -0700435 case DHCPACK:
436 // reply to dhcp client.
Taras Lemkin96a0d342018-03-26 14:52:58 +0000437 InternalPacket ethernetPacketAck = processDhcpPacketFromServer(context, packet);
Yi Tseng51301292017-07-28 13:02:59 -0700438 if (ethernetPacketAck != null) {
Taras Lemkin96a0d342018-03-26 14:52:58 +0000439 writeResponseDhcpRecord(ethernetPacketAck.getPacket(), dhcpPayload);
440 handleDhcpAck(ethernetPacketAck.getPacket(), dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -0700441 sendResponseToClient(ethernetPacketAck, dhcpPayload);
Yi Tseng51301292017-07-28 13:02:59 -0700442 }
443 break;
Charles Chand0dd7002017-10-08 23:53:36 -0400444 case DHCPNAK:
445 break;
Yi Tseng51301292017-07-28 13:02:59 -0700446 case DHCPRELEASE:
447 // TODO: release the ip address from client
448 break;
Charles Chand0dd7002017-10-08 23:53:36 -0400449 case DHCPINFORM:
450 break;
451 case DHCPFORCERENEW:
452 break;
453 case DHCPLEASEQUERY:
454 handleLeaseQueryMsg(context, packet, dhcpPayload);
455 break;
456 case DHCPLEASEACTIVE:
457 handleLeaseQueryActivateMsg(packet, dhcpPayload);
458 break;
459 case DHCPLEASEUNASSIGNED:
460 case DHCPLEASEUNKNOWN:
461 handleLeaseQueryUnknown(packet, dhcpPayload);
462 break;
Yi Tseng51301292017-07-28 13:02:59 -0700463 default:
464 break;
465 }
466 }
467
468 /**
469 * Checks if this app has been configured.
470 *
471 * @return true if all information we need have been initialized
472 */
Yi Tseng4f2a0462017-08-31 11:21:00 -0700473 private boolean configured() {
Yi Tseng919b2df2017-09-07 16:22:51 -0700474 return !defaultServerInfoList.isEmpty();
Yi Tseng51301292017-07-28 13:02:59 -0700475 }
476
477 /**
Yi Tsengdcef2c22017-08-05 20:34:06 -0700478 * Returns the first interface ip from interface.
Yi Tseng51301292017-07-28 13:02:59 -0700479 *
Yi Tsengdcef2c22017-08-05 20:34:06 -0700480 * @param iface interface of one connect point
Yi Tseng51301292017-07-28 13:02:59 -0700481 * @return the first interface IP; null if not exists an IP address in
482 * these interfaces
483 */
Yi Tseng3df7f9d2017-08-17 13:08:31 -0700484 private Ip4Address getFirstIpFromInterface(Interface iface) {
Yi Tsengdcef2c22017-08-05 20:34:06 -0700485 checkNotNull(iface, "Interface can't be null");
486 return iface.ipAddressesList().stream()
Yi Tseng51301292017-07-28 13:02:59 -0700487 .map(InterfaceIpAddress::ipAddress)
488 .filter(IpAddress::isIp4)
489 .map(IpAddress::getIp4Address)
490 .findFirst()
491 .orElse(null);
492 }
493
494 /**
Yi Tseng4f2a0462017-08-31 11:21:00 -0700495 * Gets Interface facing to the server for default host.
Yi Tsengdcef2c22017-08-05 20:34:06 -0700496 *
497 * @return the Interface facing to the server; null if not found
498 */
Yi Tseng919b2df2017-09-07 16:22:51 -0700499 private Interface getDefaultServerInterface() {
500 return getServerInterface(defaultServerInfoList);
Yi Tsengdcef2c22017-08-05 20:34:06 -0700501 }
502
503 /**
Yi Tseng4f2a0462017-08-31 11:21:00 -0700504 * Gets Interface facing to the server for indirect hosts.
505 * Use default server Interface if indirect server not configured.
506 *
507 * @return the Interface facing to the server; null if not found
508 */
509 private Interface getIndirectServerInterface() {
Yi Tseng919b2df2017-09-07 16:22:51 -0700510 return getServerInterface(indirectServerInfoList);
511 }
512
513 private Interface getServerInterface(List<DhcpServerInfo> serverInfos) {
Yi Tseng3bd57ac2017-11-29 14:39:18 -0800514 return serverInfos.stream()
Yi Tseng4f2a0462017-08-31 11:21:00 -0700515 .findFirst()
Yi Tseng3bd57ac2017-11-29 14:39:18 -0800516 .map(serverInfo -> {
517 ConnectPoint dhcpServerConnectPoint =
518 serverInfo.getDhcpServerConnectPoint().orElse(null);
519 VlanId dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
520 if (dhcpServerConnectPoint == null || dhcpConnectVlan == null) {
521 return null;
522 }
523 return interfaceService.getInterfacesByPort(dhcpServerConnectPoint)
524 .stream()
525 .filter(iface -> interfaceContainsVlan(iface, dhcpConnectVlan))
526 .findFirst()
527 .orElse(null);
528 })
Yi Tseng4f2a0462017-08-31 11:21:00 -0700529 .orElse(null);
530 }
531
532 /**
533 * Determind if an Interface contains a vlan id.
534 *
535 * @param iface the Interface
536 * @param vlanId the vlan id
537 * @return true if the Interface contains the vlan id
538 */
539 private boolean interfaceContainsVlan(Interface iface, VlanId vlanId) {
Yi Tseng4025a102017-09-30 11:35:42 +0800540 if (vlanId.equals(VlanId.NONE)) {
541 // untagged packet, check if vlan untagged or vlan native is not NONE
542 return !iface.vlanUntagged().equals(VlanId.NONE) ||
543 !iface.vlanNative().equals(VlanId.NONE);
544 }
545 // tagged packet, check if the interface contains the vlan
546 return iface.vlanTagged().contains(vlanId);
Yi Tseng4f2a0462017-08-31 11:21:00 -0700547 }
548
Charles Chand0dd7002017-10-08 23:53:36 -0400549 private void handleLeaseQueryActivateMsg(Ethernet packet, DHCP dhcpPayload) {
550 log.debug("LQ: Got DHCPLEASEACTIVE packet!");
551
Taras Lemkin96a0d342018-03-26 14:52:58 +0000552 if (learnRouteFromLeasequery) {
553 // TODO: release the ip address from client
554 MacAddress clientMacAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
555 VlanId vlanId = VlanId.vlanId(packet.getVlanID());
556 HostId hostId = HostId.hostId(clientMacAddress, vlanId);
557 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
Charles Chand0dd7002017-10-08 23:53:36 -0400558
Taras Lemkin96a0d342018-03-26 14:52:58 +0000559 if (record == null) {
560 log.warn("Can't find record for host {} when processing DHCPLEASEACTIVE", hostId);
561 return;
562 }
563
564 // need to update routes
565 log.debug("Lease Query for Client results in DHCPLEASEACTIVE - route needs to be modified");
566 // get current route
567 // find the ip of that client with the DhcpRelay store
568
569 Ip4Address clientIP = record.ip4Address().orElse(null);
570 log.debug("LQ: IP of host is " + clientIP.getIp4Address());
571
572 MacAddress nextHopMac = record.nextHop().orElse(null);
573 log.debug("LQ: MAC of resulting *OLD* NH for that host is " + nextHopMac.toString());
574
575 // find the new NH by looking at the src MAC of the dhcp request
576 // from the LQ store
577 MacAddress newNextHopMac = record.nextHopTemp().orElse(null);
578 log.debug("LQ: MAC of resulting *NEW* NH for that host is " + newNextHopMac.toString());
579
580 log.debug("LQ: updating dhcp relay record with new NH");
581 record.nextHop(newNextHopMac);
582
583 // find the next hop IP from its mac
584 HostId gwHostId = HostId.hostId(newNextHopMac, vlanId);
585 Host gwHost = hostService.getHost(gwHostId);
586
587 if (gwHost == null) {
588 log.warn("Can't find gateway for new NH host " + gwHostId);
589 return;
590 }
591
592 Ip4Address nextHopIp = gwHost.ipAddresses()
593 .stream()
594 .filter(IpAddress::isIp4)
595 .map(IpAddress::getIp4Address)
596 .findFirst()
597 .orElse(null);
598
599 if (nextHopIp == null) {
600 log.warn("Can't find IP address of gateway " + gwHost);
601 return;
602 }
603
604 log.debug("LQ: *NEW* NH IP for host is " + nextHopIp.getIp4Address());
605 Route route = new Route(Route.Source.DHCP, clientIP.toIpPrefix(), nextHopIp);
606 routeStore.updateRoute(route);
Charles Chand0dd7002017-10-08 23:53:36 -0400607 }
608
Charles Chand0dd7002017-10-08 23:53:36 -0400609 // and forward to client
Taras Lemkin96a0d342018-03-26 14:52:58 +0000610 InternalPacket ethernetPacket = processLeaseQueryFromServer(packet);
Charles Chand0dd7002017-10-08 23:53:36 -0400611 if (ethernetPacket != null) {
612 sendResponseToClient(ethernetPacket, dhcpPayload);
613 }
614 }
615
Charles Chand0dd7002017-10-08 23:53:36 -0400616 private void handleLeaseQueryMsg(PacketContext context, Ethernet packet, DHCP dhcpPayload) {
Taras Lemkin96a0d342018-03-26 14:52:58 +0000617 // If this flag is enabled we expect that DHCPLEASEQUERY-ies are sent from an access concentrator
618 // where queried client is connected to. Otherwise, DHCPLEASEQUERY source may be a separate connected agent
619 if (learnRouteFromLeasequery) {
620 log.debug("LQ: Got DHCPLEASEQUERY packet!");
621 MacAddress clientMacAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
622 log.debug("LQ: got DHCPLEASEQUERY with MAC " + clientMacAddress.toString());
623 // add the client mac (hostid) of this request to a store (the entry will be removed with
624 // the reply sent to the originator)
625 VlanId vlanId = VlanId.vlanId(packet.getVlanID());
626 HostId hId = HostId.hostId(clientMacAddress, vlanId);
627 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hId).orElse(null);
628 if (record != null) {
629 //new NH is to be taken from src mac of LQ packet
630 MacAddress newNextHop = packet.getSourceMAC();
631 record.nextHopTemp(newNextHop);
632 record.ip4Status(dhcpPayload.getPacketType());
633 record.updateLastSeen();
634
635 // do a basic routing of the packet (this is unicast routing
636 // not a relay operation like for other broadcast dhcp packets
637 List<InternalPacket> ethernetPacketRequest = processLeaseQueryFromAgent(context, packet);
638 // and forward to server
639 for (InternalPacket internalPacket : ethernetPacketRequest) {
640 log.debug("LeaseQueryMsg forward to server");
641 forwardPacket(internalPacket);
642 }
643 } else {
644 log.warn("LQ: Error! - DHCP relay record for that client not found - ignoring LQ!");
645 }
646 } else {
647 log.debug("LQ: Got DHCPLEASEQUERY packet!");
648
649 int giaddr = dhcpPayload.getGatewayIPAddress();
650
651 log.debug("DHCPLEASEQUERY giaddr: {} ({}). Originators connectPoint: {}", giaddr,
652 Ip4Address.valueOf(giaddr), context.inPacket().receivedFrom());
Charles Chand0dd7002017-10-08 23:53:36 -0400653
654 // do a basic routing of the packet (this is unicast routing
655 // not a relay operation like for other broadcast dhcp packets
rsahot036620655b2018-02-26 15:01:37 -0500656 List<InternalPacket> ethernetPacketRequest = processLeaseQueryFromAgent(context, packet);
Charles Chand0dd7002017-10-08 23:53:36 -0400657 // and forward to server
rsahot036620655b2018-02-26 15:01:37 -0500658 for (InternalPacket internalPacket : ethernetPacketRequest) {
Taras Lemkin96a0d342018-03-26 14:52:58 +0000659 log.trace("LeaseQueryMsg forward to server connected to {}", internalPacket.getDestLocation());
rsahot036620655b2018-02-26 15:01:37 -0500660 forwardPacket(internalPacket);
661 }
Charles Chand0dd7002017-10-08 23:53:36 -0400662 }
663 }
664
665 private void handleLeaseQueryUnknown(Ethernet packet, DHCP dhcpPayload) {
666 log.debug("Lease Query for Client results in DHCPLEASEUNASSIGNED or " +
667 "DHCPLEASEUNKNOWN - removing route & forwarding reply to originator");
Taras Lemkin96a0d342018-03-26 14:52:58 +0000668 if (learnRouteFromLeasequery) {
669 MacAddress clientMacAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
670 VlanId vlanId = VlanId.vlanId(packet.getVlanID());
671 HostId hostId = HostId.hostId(clientMacAddress, vlanId);
672 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
Charles Chand0dd7002017-10-08 23:53:36 -0400673
Taras Lemkin96a0d342018-03-26 14:52:58 +0000674 if (record == null) {
675 log.warn("Can't find record for host {} when handling LQ UNKNOWN/UNASSIGNED message", hostId);
676 return;
677 }
678
679 Ip4Address clientIP = record.ip4Address().orElse(null);
680 log.debug("LQ: IP of host is " + clientIP.getIp4Address());
681
682 // find the new NH by looking at the src MAC of the dhcp request
683 // from the LQ store
684 MacAddress nextHopMac = record.nextHop().orElse(null);
685 log.debug("LQ: MAC of resulting *Existing* NH for that route is " + nextHopMac.toString());
686
687 // find the next hop IP from its mac
688 HostId gwHostId = HostId.hostId(nextHopMac, vlanId);
689 Host gwHost = hostService.getHost(gwHostId);
690
691 if (gwHost == null) {
692 log.warn("Can't find gateway for new NH host " + gwHostId);
693 return;
694 }
695
696 Ip4Address nextHopIp = gwHost.ipAddresses()
697 .stream()
698 .filter(IpAddress::isIp4)
699 .map(IpAddress::getIp4Address)
700 .findFirst()
701 .orElse(null);
702
703 if (nextHopIp == null) {
704 log.warn("Can't find IP address of gateway {}", gwHost);
705 return;
706 }
707
708 log.debug("LQ: *Existing* NH IP for host is " + nextHopIp.getIp4Address() + " removing route for it");
709 Route route = new Route(Route.Source.DHCP, clientIP.toIpPrefix(), nextHopIp);
710 routeStore.removeRoute(route);
711
712 // remove from temp store
713 dhcpRelayStore.removeDhcpRecord(hostId);
Charles Chand0dd7002017-10-08 23:53:36 -0400714 }
Charles Chand0dd7002017-10-08 23:53:36 -0400715 // and forward to client
Taras Lemkin96a0d342018-03-26 14:52:58 +0000716 InternalPacket ethernetPacket = processLeaseQueryFromServer(packet);
Charles Chand0dd7002017-10-08 23:53:36 -0400717 if (ethernetPacket != null) {
718 sendResponseToClient(ethernetPacket, dhcpPayload);
719 }
720 }
721
Yi Tseng4f2a0462017-08-31 11:21:00 -0700722 /**
Yi Tseng51301292017-07-28 13:02:59 -0700723 * Build the DHCP discover/request packet with gateway IP(unicast packet).
724 *
725 * @param context the packet context
726 * @param ethernetPacket the ethernet payload to process
Yi Tseng51301292017-07-28 13:02:59 -0700727 * @return processed packet
728 */
rsahot036620655b2018-02-26 15:01:37 -0500729 private List<InternalPacket> processDhcpPacketFromClient(PacketContext context,
730 Ethernet ethernetPacket,
731 Set<Interface> clientInterfaces) {
Yi Tseng25bfe372017-11-03 16:27:32 -0700732 ConnectPoint receivedFrom = context.inPacket().receivedFrom();
733 DeviceId receivedFromDevice = receivedFrom.deviceId();
rsahot036620655b2018-02-26 15:01:37 -0500734 Ip4Address relayAgentIp = null;
Taras Lemkin96a0d342018-03-26 14:52:58 +0000735 relayAgentIp = Dhcp4HandlerUtil.getRelayAgentIPv4Address(clientInterfaces);
rsahot036620655b2018-02-26 15:01:37 -0500736 MacAddress relayAgentMac = clientInterfaces.iterator().next().mac();
737 if (relayAgentIp == null || relayAgentMac == null) {
738 log.warn("Missing DHCP relay agent interface Ipv4 addr config for "
739 + "packet from client on port: {}. Aborting packet processing",
740 clientInterfaces.iterator().next().connectPoint());
Charles Chane5e0c9a2018-03-30 12:11:34 -0700741 return Lists.newArrayList();
rsahot036620655b2018-02-26 15:01:37 -0500742 }
743 log.debug("Multi DHCP V4 processDhcpPacketFromClient on port {}",
744 clientInterfaces.iterator().next().connectPoint());
Yi Tseng25bfe372017-11-03 16:27:32 -0700745
Yi Tseng4f2a0462017-08-31 11:21:00 -0700746 // get dhcp header.
rsahot036620655b2018-02-26 15:01:37 -0500747 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
Yi Tseng4f2a0462017-08-31 11:21:00 -0700748 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
749 UDP udpPacket = (UDP) ipv4Packet.getPayload();
750 DHCP dhcpPacket = (DHCP) udpPacket.getPayload();
751
Yi Tseng919b2df2017-09-07 16:22:51 -0700752
Yi Tsengdcef2c22017-08-05 20:34:06 -0700753 Ip4Address clientInterfaceIp =
754 interfaceService.getInterfacesByPort(context.inPacket().receivedFrom())
755 .stream()
756 .map(Interface::ipAddressesList)
757 .flatMap(Collection::stream)
758 .map(InterfaceIpAddress::ipAddress)
759 .filter(IpAddress::isIp4)
760 .map(IpAddress::getIp4Address)
761 .findFirst()
762 .orElse(null);
763 if (clientInterfaceIp == null) {
764 log.warn("Can't find interface IP for client interface for port {}",
rsahot036620655b2018-02-26 15:01:37 -0500765 context.inPacket().receivedFrom());
Charles Chane5e0c9a2018-03-30 12:11:34 -0700766 return Lists.newArrayList();
Yi Tsengdcef2c22017-08-05 20:34:06 -0700767 }
rsahot036620655b2018-02-26 15:01:37 -0500768
Yi Tseng4f2a0462017-08-31 11:21:00 -0700769 boolean isDirectlyConnected = directlyConnected(dhcpPacket);
rsahot036620655b2018-02-26 15:01:37 -0500770 boolean directConnFlag = directlyConnected(dhcpPacket);
771
772 // Multi DHCP Start
773 ConnectPoint clientConnectionPoint = context.inPacket().receivedFrom();
774 VlanId vlanIdInUse = VlanId.vlanId(ethernetPacket.getVlanID());
775 Interface clientInterface = interfaceService.getInterfacesByPort(clientConnectionPoint)
Taras Lemkin96a0d342018-03-26 14:52:58 +0000776 .stream().filter(iface -> Dhcp4HandlerUtil.interfaceContainsVlan(iface, vlanIdInUse))
rsahot036620655b2018-02-26 15:01:37 -0500777 .findFirst()
778 .orElse(null);
779
780 List<InternalPacket> internalPackets = new ArrayList<>();
781 List<DhcpServerInfo> serverInfoList = findValidServerInfo(directConnFlag);
782 List<DhcpServerInfo> copyServerInfoList = new ArrayList<DhcpServerInfo>(serverInfoList);
783
784
785 for (DhcpServerInfo serverInfo : copyServerInfoList) {
786 etherReply = (Ethernet) ethernetPacket.clone();
Taras Lemkin96a0d342018-03-26 14:52:58 +0000787 ipv4Packet = (IPv4) etherReply.getPayload();
788 udpPacket = (UDP) ipv4Packet.getPayload();
789 dhcpPacket = (DHCP) udpPacket.getPayload();
rsahot036620655b2018-02-26 15:01:37 -0500790 if (!checkDhcpServerConnPt(directConnFlag, serverInfo)) {
791 log.warn("Can't get server connect point, ignore");
792 continue;
793 }
794 DhcpServerInfo newServerInfo = getHostInfoForServerInfo(serverInfo, serverInfoList);
795 if (newServerInfo == null) {
796 log.warn("Can't get server interface with host info resolved, ignore");
797 continue;
798 }
799
800 Interface serverInterface = getServerInterface(newServerInfo);
Yi Tseng3bd57ac2017-11-29 14:39:18 -0800801 if (serverInterface == null) {
rsahot036620655b2018-02-26 15:01:37 -0500802 log.warn("Can't get server interface, ignore");
803 continue;
Yi Tseng3bd57ac2017-11-29 14:39:18 -0800804 }
Yi Tseng4f2a0462017-08-31 11:21:00 -0700805
rsahot036620655b2018-02-26 15:01:37 -0500806 Ip4Address ipFacingServer = getFirstIpFromInterface(serverInterface);
807 MacAddress macFacingServer = serverInterface.mac();
808 log.debug("Interfacing server {} Mac : {} ", ipFacingServer, macFacingServer);
809 if (ipFacingServer == null || macFacingServer == null) {
810 log.warn("No IP address for server Interface {}", serverInterface);
rsahot036620655b2018-02-26 15:01:37 -0500811 continue;
812 }
Yi Tseng51301292017-07-28 13:02:59 -0700813
Charles Chand0d1e332017-10-10 16:53:32 -0400814
rsahot036620655b2018-02-26 15:01:37 -0500815 etherReply.setSourceMACAddress(macFacingServer);
816 // set default info and replace with indirect if available later on.
817 if (newServerInfo.getDhcpConnectMac().isPresent()) {
818 etherReply.setDestinationMACAddress(newServerInfo.getDhcpConnectMac().get());
819 }
820 if (newServerInfo.getDhcpConnectVlan().isPresent()) {
821 etherReply.setVlanID(newServerInfo.getDhcpConnectVlan().get().toShort());
822 }
823 ipv4Packet.setSourceAddress(ipFacingServer.toInt());
824 ipv4Packet.setDestinationAddress(newServerInfo.getDhcpServerIp4().get().toInt());
Charles Chan2de55302018-03-02 18:27:59 -0800825 log.debug("Directly connected {}", isDirectlyConnected);
826 log.debug("DHCP server IP: {}", newServerInfo.getDhcpServerIp4().get());
rsahot036620655b2018-02-26 15:01:37 -0500827 if (isDirectlyConnected) {
Yi Tseng51301292017-07-28 13:02:59 -0700828
Charles Chan2de55302018-03-02 18:27:59 -0800829 log.debug("Default DHCP server IP: {}", newServerInfo.getDhcpServerIp4().get());
rsahot036620655b2018-02-26 15:01:37 -0500830 if (newServerInfo.getDhcpConnectMac().isPresent()) {
831 etherReply.setDestinationMACAddress(newServerInfo.getDhcpConnectMac().get());
Charles Chand0d1e332017-10-10 16:53:32 -0400832 }
rsahot036620655b2018-02-26 15:01:37 -0500833 if (newServerInfo.getDhcpConnectVlan().isPresent()) {
834 etherReply.setVlanID(newServerInfo.getDhcpConnectVlan().get().toShort());
835 }
836
837 ipv4Packet.setDestinationAddress(newServerInfo.getDhcpServerIp4().get().toInt());
838
839
840 ConnectPoint inPort = context.inPacket().receivedFrom();
841 VlanId vlanId = VlanId.vlanId(ethernetPacket.getVlanID());
842 // add connected in port and vlan
843 CircuitId cid = new CircuitId(inPort.toString(), vlanId);
844 byte[] circuitId = cid.serialize();
845 DhcpOption circuitIdSubOpt = new DhcpOption();
846 circuitIdSubOpt
847 .setCode(CIRCUIT_ID.getValue())
848 .setLength((byte) circuitId.length)
849 .setData(circuitId);
850
851 DhcpRelayAgentOption newRelayAgentOpt = new DhcpRelayAgentOption();
852 newRelayAgentOpt.setCode(OptionCode_CircuitID.getValue());
853 newRelayAgentOpt.addSubOption(circuitIdSubOpt);
854
855 // Removes END option first
856 List<DhcpOption> options = dhcpPacket.getOptions().stream()
857 .filter(opt -> opt.getCode() != OptionCode_END.getValue())
858 .collect(Collectors.toList());
859
860 // push relay agent option
861 options.add(newRelayAgentOpt);
862
863 // make sure option 255(End) is the last option
864 DhcpOption endOption = new DhcpOption();
865 endOption.setCode(OptionCode_END.getValue());
866 options.add(endOption);
867
868 dhcpPacket.setOptions(options);
869
870 relayAgentIp = serverInfo.getRelayAgentIp4(receivedFromDevice).orElse(null);
871
872 // Sets relay agent IP
873 int effectiveRelayAgentIp = relayAgentIp != null ?
874 relayAgentIp.toInt() : clientInterfaceIp.toInt();
875 dhcpPacket.setGatewayIPAddress(effectiveRelayAgentIp);
Charles Chan2de55302018-03-02 18:27:59 -0800876 log.debug("In Default, Relay Agent IP {}", effectiveRelayAgentIp);
Charles Chand0d1e332017-10-10 16:53:32 -0400877 } else {
rsahot036620655b2018-02-26 15:01:37 -0500878 if (!newServerInfo.getDhcpServerIp4().isPresent()) {
879 // do nothing
880 } else if (!newServerInfo.getDhcpConnectMac().isPresent()) {
881 continue;
882 } else {
883 relayAgentIp = newServerInfo.getRelayAgentIp4(receivedFromDevice).orElse(null);
884 // Sets relay agent IP
885 int effectiveRelayAgentIp = relayAgentIp != null ?
886 relayAgentIp.toInt() : clientInterfaceIp.toInt();
887 dhcpPacket.setGatewayIPAddress(effectiveRelayAgentIp);
Charles Chand0d1e332017-10-10 16:53:32 -0400888 }
Yi Tseng4f2a0462017-08-31 11:21:00 -0700889 }
Yi Tseng3df7f9d2017-08-17 13:08:31 -0700890
rsahot036620655b2018-02-26 15:01:37 -0500891 // Remove broadcast flag
892 dhcpPacket.setFlags((short) 0);
893
894 udpPacket.setPayload(dhcpPacket);
895 // As a DHCP relay, the source port should be server port( instead
896 // of client port.
897 udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
898 udpPacket.setDestinationPort(UDP.DHCP_SERVER_PORT);
899 ipv4Packet.setPayload(udpPacket);
900 ipv4Packet.setTtl((byte) 64);
901 etherReply.setPayload(ipv4Packet);
Taras Lemkin96a0d342018-03-26 14:52:58 +0000902 InternalPacket internalPacket = InternalPacket.internalPacket(etherReply,
rsahot036620655b2018-02-26 15:01:37 -0500903 serverInfo.getDhcpServerConnectPoint().get());
Taras Lemkin96a0d342018-03-26 14:52:58 +0000904
rsahot036620655b2018-02-26 15:01:37 -0500905 internalPackets.add(internalPacket);
906 }
907 return internalPackets;
Yi Tseng51301292017-07-28 13:02:59 -0700908 }
909
Charles Chand0dd7002017-10-08 23:53:36 -0400910
911 /**
912 * Do a basic routing for a packet from client (used for LQ processing).
913 *
914 * @param context the packet context
915 * @param ethernetPacket the ethernet payload to process
916 * @return processed packet
917 */
rsahot036620655b2018-02-26 15:01:37 -0500918 private List<InternalPacket> processLeaseQueryFromAgent(PacketContext context,
919 Ethernet ethernetPacket) {
920 ConnectPoint receivedFrom = context.inPacket().receivedFrom();
921 DeviceId receivedFromDevice = receivedFrom.deviceId();
922
Charles Chand0dd7002017-10-08 23:53:36 -0400923 // get dhcp header.
924 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
925 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
926 UDP udpPacket = (UDP) ipv4Packet.getPayload();
927 DHCP dhcpPacket = (DHCP) udpPacket.getPayload();
928
Charles Chan2de55302018-03-02 18:27:59 -0800929 Ip4Address relayAgentIp;
Charles Chand0dd7002017-10-08 23:53:36 -0400930
Charles Chand0dd7002017-10-08 23:53:36 -0400931 Ip4Address clientInterfaceIp =
932 interfaceService.getInterfacesByPort(context.inPacket().receivedFrom())
933 .stream()
934 .map(Interface::ipAddressesList)
935 .flatMap(Collection::stream)
936 .map(InterfaceIpAddress::ipAddress)
937 .filter(IpAddress::isIp4)
938 .map(IpAddress::getIp4Address)
939 .findFirst()
940 .orElse(null);
941 if (clientInterfaceIp == null) {
942 log.warn("Can't find interface IP for client interface for port {}",
rsahot036620655b2018-02-26 15:01:37 -0500943 context.inPacket().receivedFrom());
Charles Chand0dd7002017-10-08 23:53:36 -0400944 return null;
945 }
rsahot036620655b2018-02-26 15:01:37 -0500946
Charles Chand0dd7002017-10-08 23:53:36 -0400947 boolean isDirectlyConnected = directlyConnected(dhcpPacket);
rsahot036620655b2018-02-26 15:01:37 -0500948 boolean directConnFlag = directlyConnected(dhcpPacket);
949
950 // Multi DHCP Start
rsahot036620655b2018-02-26 15:01:37 -0500951 List<InternalPacket> internalPackets = new ArrayList<>();
952 List<DhcpServerInfo> serverInfoList = findValidServerInfo(directConnFlag);
Charles Chan2de55302018-03-02 18:27:59 -0800953 List<DhcpServerInfo> copyServerInfoList = new ArrayList<>(serverInfoList);
rsahot036620655b2018-02-26 15:01:37 -0500954
955 for (DhcpServerInfo serverInfo : copyServerInfoList) {
956 // get dhcp header.
957 etherReply = (Ethernet) ethernetPacket.clone();
958 ipv4Packet = (IPv4) etherReply.getPayload();
959 udpPacket = (UDP) ipv4Packet.getPayload();
960 dhcpPacket = (DHCP) udpPacket.getPayload();
961
962 if (!checkDhcpServerConnPt(directConnFlag, serverInfo)) {
963 log.warn("Can't get server connect point, ignore");
964 continue;
Yi Tseng3bd57ac2017-11-29 14:39:18 -0800965 }
rsahot036620655b2018-02-26 15:01:37 -0500966 DhcpServerInfo newServerInfo = getHostInfoForServerInfo(serverInfo, serverInfoList);
967 if (newServerInfo == null) {
968 log.warn("Can't get server interface with host info resolved, ignore");
969 continue;
970 }
Charles Chand0dd7002017-10-08 23:53:36 -0400971
rsahot036620655b2018-02-26 15:01:37 -0500972 Interface serverInterface = getServerInterface(newServerInfo);
973 if (serverInterface == null) {
974 log.warn("Can't get server interface, ignore");
975 continue;
976 }
977 Ip4Address ipFacingServer = getFirstIpFromInterface(serverInterface);
978 MacAddress macFacingServer = serverInterface.mac();
979 if (ipFacingServer == null || macFacingServer == null) {
980 log.warn("No IP address for server Interface {}", serverInterface);
981 continue;
982 }
Charles Chand0dd7002017-10-08 23:53:36 -0400983
rsahot036620655b2018-02-26 15:01:37 -0500984 etherReply.setSourceMACAddress(macFacingServer);
Charles Chan2de55302018-03-02 18:27:59 -0800985 etherReply.setDestinationMACAddress(newServerInfo.getDhcpConnectMac().get());
986 etherReply.setVlanID(newServerInfo.getDhcpConnectVlan().get().toShort());
rsahot036620655b2018-02-26 15:01:37 -0500987 ipv4Packet.setSourceAddress(ipFacingServer.toInt());
Charles Chan2de55302018-03-02 18:27:59 -0800988 ipv4Packet.setDestinationAddress(newServerInfo.getDhcpServerIp4().get().toInt());
rsahot036620655b2018-02-26 15:01:37 -0500989 if (isDirectlyConnected) {
990 // set default info and replace with indirect if available later on.
991 if (newServerInfo.getDhcpConnectMac().isPresent()) {
992 etherReply.setDestinationMACAddress(newServerInfo.getDhcpConnectMac().get());
993 }
994 if (newServerInfo.getDhcpConnectVlan().isPresent()) {
995 etherReply.setVlanID(serverInfo.getDhcpConnectVlan().get().toShort());
996 }
Taras Lemkin96a0d342018-03-26 14:52:58 +0000997 if (learnRouteFromLeasequery) {
rsahot036620655b2018-02-26 15:01:37 -0500998 relayAgentIp = newServerInfo.getRelayAgentIp4(receivedFromDevice).orElse(null);
999 // Sets relay agent IP
1000 int effectiveRelayAgentIp = relayAgentIp != null ?
1001 relayAgentIp.toInt() : clientInterfaceIp.toInt();
1002 dhcpPacket.setGatewayIPAddress(effectiveRelayAgentIp);
Taras Lemkin96a0d342018-03-26 14:52:58 +00001003 }
1004 } else {
1005 if (!newServerInfo.getDhcpServerIp4().isPresent()) {
1006 //do nothing
1007 } else if (!newServerInfo.getDhcpConnectMac().isPresent()) {
1008 continue;
1009 } else if (learnRouteFromLeasequery) {
1010 relayAgentIp = newServerInfo.getRelayAgentIp4(receivedFromDevice).orElse(null);
1011 // Sets relay agent IP
1012 int effectiveRelayAgentIp = relayAgentIp != null ?
1013 relayAgentIp.toInt() : clientInterfaceIp.toInt();
rsahot036620655b2018-02-26 15:01:37 -05001014 dhcpPacket.setGatewayIPAddress(effectiveRelayAgentIp);
Taras Lemkin96a0d342018-03-26 14:52:58 +00001015 log.debug("Relay Agent IP {}", relayAgentIp);
rsahot036620655b2018-02-26 15:01:37 -05001016 }
1017
Taras Lemkin96a0d342018-03-26 14:52:58 +00001018 log.trace("Indirect");
rsahot036620655b2018-02-26 15:01:37 -05001019 }
1020
1021 // Remove broadcast flag
1022 dhcpPacket.setFlags((short) 0);
1023
1024 udpPacket.setPayload(dhcpPacket);
1025 // As a DHCP relay, the source port should be server port( instead
1026 // of client port.
1027 udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
1028 udpPacket.setDestinationPort(UDP.DHCP_SERVER_PORT);
1029 ipv4Packet.setPayload(udpPacket);
1030 ipv4Packet.setTtl((byte) 64);
1031 etherReply.setPayload(ipv4Packet);
Taras Lemkin96a0d342018-03-26 14:52:58 +00001032 udpPacket.resetChecksum();
rsahot036620655b2018-02-26 15:01:37 -05001033 ////return etherReply;
Taras Lemkin96a0d342018-03-26 14:52:58 +00001034 InternalPacket internalPacket = InternalPacket.internalPacket(etherReply,
rsahot036620655b2018-02-26 15:01:37 -05001035 newServerInfo.getDhcpServerConnectPoint().get());
Taras Lemkin96a0d342018-03-26 14:52:58 +00001036
rsahot036620655b2018-02-26 15:01:37 -05001037 internalPackets.add(internalPacket);
Charles Chand0dd7002017-10-08 23:53:36 -04001038 }
Taras Lemkin96a0d342018-03-26 14:52:58 +00001039 log.debug("num of processLeaseQueryFromAgent packets to send is: {}", internalPackets.size());
Charles Chand0dd7002017-10-08 23:53:36 -04001040
rsahot036620655b2018-02-26 15:01:37 -05001041 return internalPackets;
Charles Chand0dd7002017-10-08 23:53:36 -04001042 }
1043
1044
Yi Tseng51301292017-07-28 13:02:59 -07001045 /**
1046 * Writes DHCP record to the store according to the request DHCP packet (Discover, Request).
1047 *
1048 * @param location the location which DHCP packet comes from
1049 * @param ethernet the DHCP packet
1050 * @param dhcpPayload the DHCP payload
1051 */
1052 private void writeRequestDhcpRecord(ConnectPoint location,
1053 Ethernet ethernet,
1054 DHCP dhcpPayload) {
1055 VlanId vlanId = VlanId.vlanId(ethernet.getVlanID());
1056 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
1057 HostId hostId = HostId.hostId(macAddress, vlanId);
1058 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1059 if (record == null) {
1060 record = new DhcpRecord(HostId.hostId(macAddress, vlanId));
1061 } else {
1062 record = record.clone();
1063 }
1064 record.addLocation(new HostLocation(location, System.currentTimeMillis()));
1065 record.ip4Status(dhcpPayload.getPacketType());
1066 record.setDirectlyConnected(directlyConnected(dhcpPayload));
1067 if (!directlyConnected(dhcpPayload)) {
1068 // Update gateway mac address if the host is not directly connected
1069 record.nextHop(ethernet.getSourceMAC());
1070 }
1071 record.updateLastSeen();
1072 dhcpRelayStore.updateDhcpRecord(HostId.hostId(macAddress, vlanId), record);
1073 }
1074
1075 /**
1076 * Writes DHCP record to the store according to the response DHCP packet (Offer, Ack).
1077 *
1078 * @param ethernet the DHCP packet
1079 * @param dhcpPayload the DHCP payload
1080 */
1081 private void writeResponseDhcpRecord(Ethernet ethernet,
1082 DHCP dhcpPayload) {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001083 Optional<Interface> outInterface = getClientInterface(ethernet, dhcpPayload);
Yi Tseng51301292017-07-28 13:02:59 -07001084 if (!outInterface.isPresent()) {
1085 log.warn("Failed to determine where to send {}", dhcpPayload.getPacketType());
1086 return;
1087 }
1088
1089 Interface outIface = outInterface.get();
1090 ConnectPoint location = outIface.connectPoint();
Yi Tseng4f2a0462017-08-31 11:21:00 -07001091 VlanId vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -07001092 if (vlanId == null) {
1093 vlanId = outIface.vlan();
1094 }
Yi Tseng51301292017-07-28 13:02:59 -07001095 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
1096 HostId hostId = HostId.hostId(macAddress, vlanId);
1097 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1098 if (record == null) {
1099 record = new DhcpRecord(HostId.hostId(macAddress, vlanId));
1100 } else {
1101 record = record.clone();
1102 }
1103 record.addLocation(new HostLocation(location, System.currentTimeMillis()));
1104 if (dhcpPayload.getPacketType() == DHCP.MsgType.DHCPACK) {
1105 record.ip4Address(Ip4Address.valueOf(dhcpPayload.getYourIPAddress()));
1106 }
1107 record.ip4Status(dhcpPayload.getPacketType());
1108 record.setDirectlyConnected(directlyConnected(dhcpPayload));
1109 record.updateLastSeen();
1110 dhcpRelayStore.updateDhcpRecord(HostId.hostId(macAddress, vlanId), record);
1111 }
1112
1113 /**
1114 * Build the DHCP offer/ack with proper client port.
1115 *
1116 * @param ethernetPacket the original packet comes from server
1117 * @return new packet which will send to the client
1118 */
Taras Lemkin96a0d342018-03-26 14:52:58 +00001119 private InternalPacket processDhcpPacketFromServer(PacketContext context, Ethernet ethernetPacket) {
Yi Tseng51301292017-07-28 13:02:59 -07001120 // get dhcp header.
rsahot036620655b2018-02-26 15:01:37 -05001121 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
Yi Tseng51301292017-07-28 13:02:59 -07001122 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
1123 UDP udpPacket = (UDP) ipv4Packet.getPayload();
1124 DHCP dhcpPayload = (DHCP) udpPacket.getPayload();
1125
1126 // determine the vlanId of the client host - note that this vlan id
1127 // could be different from the vlan in the packet from the server
Yi Tsengdcef2c22017-08-05 20:34:06 -07001128 Interface clientInterface = getClientInterface(ethernetPacket, dhcpPayload).orElse(null);
Yi Tseng51301292017-07-28 13:02:59 -07001129
Yi Tsengdcef2c22017-08-05 20:34:06 -07001130 if (clientInterface == null) {
Yi Tseng51301292017-07-28 13:02:59 -07001131 log.warn("Cannot find the interface for the DHCP {}", dhcpPayload);
1132 return null;
1133 }
Yi Tsengdcef2c22017-08-05 20:34:06 -07001134 VlanId vlanId;
rsahot036620655b2018-02-26 15:01:37 -05001135 ConnectPoint inPort = context.inPacket().receivedFrom();
1136 boolean directConnFlag = directlyConnected(dhcpPayload);
1137 DhcpServerInfo foundServerInfo = findServerInfoFromServer(directConnFlag, inPort);
1138
1139 if (foundServerInfo == null) {
jayakumarthazhathed5f05d2018-09-25 15:56:51 -04001140 log.warn("Cannot find server info for {} server, inPort {}",
1141 directConnFlag ? "direct" : "indirect", inPort);
rsahot036620655b2018-02-26 15:01:37 -05001142 return null;
1143 } else {
Taras Lemkin96a0d342018-03-26 14:52:58 +00001144 if (Dhcp4HandlerUtil.isServerIpEmpty(foundServerInfo)) {
rsahot036620655b2018-02-26 15:01:37 -05001145 log.warn("Cannot find server info's ipaddress");
1146 return null;
1147 }
1148 }
Yi Tsengdcef2c22017-08-05 20:34:06 -07001149 if (clientInterface.vlanTagged().isEmpty()) {
1150 vlanId = clientInterface.vlan();
1151 } else {
1152 // might be multiple vlan in same interface
Yi Tseng4f2a0462017-08-31 11:21:00 -07001153 vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -07001154 }
1155 if (vlanId == null) {
1156 vlanId = VlanId.NONE;
1157 }
1158 etherReply.setVlanID(vlanId.toShort());
1159 etherReply.setSourceMACAddress(clientInterface.mac());
Yi Tseng51301292017-07-28 13:02:59 -07001160
Yi Tsengdcef2c22017-08-05 20:34:06 -07001161 if (!directlyConnected(dhcpPayload)) {
1162 // if client is indirectly connected, try use next hop mac address
1163 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
1164 HostId hostId = HostId.hostId(macAddress, vlanId);
Daniel Ginsburgb1dec912018-01-29 11:40:22 -08001165 if (((int) dhcpPayload.getFlags() & 0x8000) == 0x0000) {
1166 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1167 if (record != null) {
1168 // if next hop can be found, use mac address of next hop
1169 record.nextHop().ifPresent(etherReply::setDestinationMACAddress);
1170 } else {
1171 // otherwise, discard the packet
1172 log.warn("Can't find record for host id {}, discard packet", hostId);
1173 return null;
1174 }
Yi Tsengdcef2c22017-08-05 20:34:06 -07001175 } else {
Daniel Ginsburgb1dec912018-01-29 11:40:22 -08001176 etherReply.setDestinationMACAddress(MacAddress.BROADCAST);
Yi Tsengdcef2c22017-08-05 20:34:06 -07001177 }
Yi Tseng1696f562017-08-17 17:43:38 -07001178 } else {
1179 etherReply.setDestinationMACAddress(dhcpPayload.getClientHardwareAddress());
Yi Tsengdcef2c22017-08-05 20:34:06 -07001180 }
1181
Yi Tseng51301292017-07-28 13:02:59 -07001182 // we leave the srcMac from the original packet
Yi Tseng51301292017-07-28 13:02:59 -07001183 // figure out the relay agent IP corresponding to the original request
Yi Tseng3df7f9d2017-08-17 13:08:31 -07001184 Ip4Address ipFacingClient = getFirstIpFromInterface(clientInterface);
1185 if (ipFacingClient == null) {
Yi Tseng51301292017-07-28 13:02:59 -07001186 log.warn("Cannot determine relay agent interface Ipv4 addr for host {}/{}. "
1187 + "Aborting relay for dhcp packet from server {}",
Yi Tsengdcef2c22017-08-05 20:34:06 -07001188 etherReply.getDestinationMAC(), clientInterface.vlan(),
Yi Tseng51301292017-07-28 13:02:59 -07001189 ethernetPacket);
1190 return null;
1191 }
1192 // SRC_IP: relay agent IP
1193 // DST_IP: offered IP
Yi Tseng3df7f9d2017-08-17 13:08:31 -07001194 ipv4Packet.setSourceAddress(ipFacingClient.toInt());
Daniel Ginsburgb1dec912018-01-29 11:40:22 -08001195 if (((int) dhcpPayload.getFlags() & 0x8000) == 0x0000) {
1196 ipv4Packet.setDestinationAddress(dhcpPayload.getYourIPAddress());
1197 } else {
1198 ipv4Packet.setDestinationAddress(BROADCAST_IP);
1199 }
Yi Tseng51301292017-07-28 13:02:59 -07001200 udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
1201 if (directlyConnected(dhcpPayload)) {
1202 udpPacket.setDestinationPort(UDP.DHCP_CLIENT_PORT);
1203 } else {
1204 // forward to another dhcp relay
Yi Tseng93ba53c2017-09-14 13:24:21 -07001205 // FIXME: Currently we assume the DHCP comes from a L2 relay with
1206 // Option 82, this might not work if DHCP message comes from
1207 // L3 relay.
1208 udpPacket.setDestinationPort(UDP.DHCP_CLIENT_PORT);
Yi Tseng51301292017-07-28 13:02:59 -07001209 }
1210
1211 udpPacket.setPayload(dhcpPayload);
1212 ipv4Packet.setPayload(udpPacket);
1213 etherReply.setPayload(ipv4Packet);
Taras Lemkin96a0d342018-03-26 14:52:58 +00001214 return InternalPacket.internalPacket(etherReply, clientInterface.connectPoint());
Yi Tseng51301292017-07-28 13:02:59 -07001215 }
1216
Yi Tsengdcef2c22017-08-05 20:34:06 -07001217 /**
Charles Chand0dd7002017-10-08 23:53:36 -04001218 * Build the DHCP offer/ack with proper client port.
1219 *
1220 * @param ethernetPacket the original packet comes from server
1221 * @return new packet which will send to the client
1222 */
Taras Lemkin96a0d342018-03-26 14:52:58 +00001223 private InternalPacket processLeaseQueryFromServer(Ethernet ethernetPacket) {
Charles Chand0dd7002017-10-08 23:53:36 -04001224 // get dhcp header.
1225 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
1226 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
1227 UDP udpPacket = (UDP) ipv4Packet.getPayload();
1228 DHCP dhcpPayload = (DHCP) udpPacket.getPayload();
1229
1230 // determine the vlanId of the client host - note that this vlan id
1231 // could be different from the vlan in the packet from the server
Taras Lemkin96a0d342018-03-26 14:52:58 +00001232 Interface clientInterface = null;
1233 MacAddress destinationMac = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
1234
1235 if (!learnRouteFromLeasequery) {
1236 int giaddr = ipv4Packet.getDestinationAddress();
1237 IpAddress destinationAddress = Ip4Address.valueOf(giaddr);
1238 log.debug("DHCPLEASEQUERYRESP giaddr: {}({})", giaddr, destinationAddress);
1239
1240 Host destinationHost = hostService.getHostsByIp(destinationAddress).stream().findFirst().orElse(null);
1241 if (destinationHost != null) {
1242 destinationMac = destinationHost.mac();
1243 log.trace("DHCPLEASEQUERYRESP destination mac is: {}", destinationMac);
1244 ConnectPoint destinationLocation = destinationHost.location();
1245 log.trace("Lookup for client interface by destination location {}", destinationLocation);
1246 clientInterface = interfaceService.getInterfacesByPort(destinationLocation)
1247 .stream()
1248 .filter(iface -> interfaceContainsVlan(iface, VlanId.vlanId(etherReply.getVlanID())))
1249 .findFirst()
1250 .orElse(null);
1251 log.trace("Found Host {} by ip {}", destinationHost, destinationAddress);
1252 log.debug("DHCPLEASEQUERYRESP Client interface: {}",
1253 (clientInterface != null ? clientInterface : "not resolved"));
1254
1255 }
1256 } else {
1257 clientInterface = getClientInterface(ethernetPacket, dhcpPayload).orElse(null);
1258 }
Charles Chand0dd7002017-10-08 23:53:36 -04001259
1260 if (clientInterface == null) {
1261 log.warn("Cannot find the interface for the DHCP {}", dhcpPayload);
1262 return null;
1263 }
1264 VlanId vlanId;
1265 if (clientInterface.vlanTagged().isEmpty()) {
1266 vlanId = clientInterface.vlan();
1267 } else {
1268 // might be multiple vlan in same interface
1269 vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
1270 }
1271 if (vlanId == null) {
1272 vlanId = VlanId.NONE;
1273 }
1274 etherReply.setVlanID(vlanId.toShort());
1275 etherReply.setSourceMACAddress(clientInterface.mac());
1276
Taras Lemkin96a0d342018-03-26 14:52:58 +00001277 if (!directlyConnected(dhcpPayload) && learnRouteFromLeasequery) {
Charles Chand0dd7002017-10-08 23:53:36 -04001278 // if client is indirectly connected, try use next hop mac address
1279 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
1280 HostId hostId = HostId.hostId(macAddress, vlanId);
1281 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1282 if (record != null) {
1283 // if next hop can be found, use mac address of next hop
Taras Lemkin96a0d342018-03-26 14:52:58 +00001284 Optional<MacAddress> nextHop = record.nextHopTemp();
1285 if (!nextHop.isPresent()) {
1286 nextHop = record.nextHop();
1287 }
1288 nextHop.ifPresent(etherReply::setDestinationMACAddress);
Charles Chand0dd7002017-10-08 23:53:36 -04001289 } else {
1290 // otherwise, discard the packet
1291 log.warn("Can't find record for host id {}, discard packet", hostId);
1292 return null;
1293 }
1294 } else {
Taras Lemkin96a0d342018-03-26 14:52:58 +00001295 etherReply.setDestinationMACAddress(destinationMac);
Charles Chand0dd7002017-10-08 23:53:36 -04001296 }
1297
Charles Chand0dd7002017-10-08 23:53:36 -04001298 udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
Taras Lemkin96a0d342018-03-26 14:52:58 +00001299 if (directlyConnected(dhcpPayload)) {
1300 udpPacket.setDestinationPort(UDP.DHCP_CLIENT_PORT);
1301 } else {
1302 udpPacket.setDestinationPort(UDP.DHCP_SERVER_PORT);
1303 }
Charles Chand0dd7002017-10-08 23:53:36 -04001304
1305 udpPacket.setPayload(dhcpPayload);
1306 ipv4Packet.setPayload(udpPacket);
1307 etherReply.setPayload(ipv4Packet);
Taras Lemkin96a0d342018-03-26 14:52:58 +00001308 udpPacket.resetChecksum();
1309
1310 return InternalPacket.internalPacket(etherReply, clientInterface.connectPoint());
Charles Chand0dd7002017-10-08 23:53:36 -04001311 }
1312 /**
Yi Tsengdcef2c22017-08-05 20:34:06 -07001313 * Extracts VLAN ID from relay agent option.
1314 *
1315 * @param dhcpPayload the DHCP payload
1316 * @return VLAN ID from DHCP payload; null if not exists
1317 */
Yi Tseng4f2a0462017-08-31 11:21:00 -07001318 private VlanId getVlanIdFromRelayAgentOption(DHCP dhcpPayload) {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001319 DhcpRelayAgentOption option = (DhcpRelayAgentOption) dhcpPayload.getOption(OptionCode_CircuitID);
1320 if (option == null) {
1321 return null;
1322 }
1323 DhcpOption circuitIdSubOption = option.getSubOption(CIRCUIT_ID.getValue());
1324 if (circuitIdSubOption == null) {
1325 return null;
1326 }
1327 try {
1328 CircuitId circuitId = CircuitId.deserialize(circuitIdSubOption.getData());
1329 return circuitId.vlanId();
1330 } catch (IllegalArgumentException e) {
1331 // can't deserialize the circuit ID
1332 return null;
1333 }
1334 }
1335
1336 /**
1337 * Removes DHCP relay agent information option (option 82) from DHCP payload.
1338 * Also reset giaddr to 0
1339 *
1340 * @param ethPacket the Ethernet packet to be processed
1341 * @return Ethernet packet processed
1342 */
1343 private Ethernet removeRelayAgentOption(Ethernet ethPacket) {
rsahot036620655b2018-02-26 15:01:37 -05001344 Ethernet ethernet = (Ethernet) ethPacket.duplicate();
Yi Tsengdcef2c22017-08-05 20:34:06 -07001345 IPv4 ipv4 = (IPv4) ethernet.getPayload();
1346 UDP udp = (UDP) ipv4.getPayload();
1347 DHCP dhcpPayload = (DHCP) udp.getPayload();
1348
1349 // removes relay agent information option
1350 List<DhcpOption> options = dhcpPayload.getOptions();
1351 options = options.stream()
1352 .filter(option -> option.getCode() != OptionCode_CircuitID.getValue())
1353 .collect(Collectors.toList());
1354 dhcpPayload.setOptions(options);
1355 dhcpPayload.setGatewayIPAddress(0);
1356
1357 udp.setPayload(dhcpPayload);
1358 ipv4.setPayload(udp);
1359 ethernet.setPayload(ipv4);
1360 return ethernet;
1361 }
1362
Taras Lemkin96a0d342018-03-26 14:52:58 +00001363 private boolean isDhcpPacketLeasequery(DHCP dhcpPacket) {
1364 switch (dhcpPacket.getPacketType()) {
1365 case DHCPLEASEACTIVE:
1366 case DHCPLEASEQUERY:
1367 case DHCPLEASEUNASSIGNED:
1368 case DHCPLEASEUNKNOWN:
1369 return true;
1370 default:
1371 return false;
1372 }
1373 }
Yi Tseng51301292017-07-28 13:02:59 -07001374
1375 /**
1376 * Check if the host is directly connected to the network or not.
1377 *
1378 * @param dhcpPayload the dhcp payload
1379 * @return true if the host is directly connected to the network; false otherwise
1380 */
1381 private boolean directlyConnected(DHCP dhcpPayload) {
Taras Lemkin96a0d342018-03-26 14:52:58 +00001382 // leasequery is always indirect
1383 if (isDhcpPacketLeasequery(dhcpPayload)) {
1384 return false;
1385 }
1386
Yi Tseng440e2b72017-08-24 14:47:34 -07001387 DhcpRelayAgentOption relayAgentOption =
1388 (DhcpRelayAgentOption) dhcpPayload.getOption(OptionCode_CircuitID);
Yi Tseng51301292017-07-28 13:02:59 -07001389
1390 // Doesn't contains relay option
1391 if (relayAgentOption == null) {
1392 return true;
1393 }
1394
Yi Tseng440e2b72017-08-24 14:47:34 -07001395 // check circuit id, if circuit id is invalid, we say it is an indirect host
1396 DhcpOption circuitIdOpt = relayAgentOption.getSubOption(CIRCUIT_ID.getValue());
Yi Tseng51301292017-07-28 13:02:59 -07001397
Yi Tseng440e2b72017-08-24 14:47:34 -07001398 try {
1399 CircuitId.deserialize(circuitIdOpt.getData());
Yi Tseng51301292017-07-28 13:02:59 -07001400 return true;
Yi Tseng440e2b72017-08-24 14:47:34 -07001401 } catch (Exception e) {
1402 // invalid circuit id
1403 return false;
Yi Tseng51301292017-07-28 13:02:59 -07001404 }
Yi Tseng51301292017-07-28 13:02:59 -07001405 }
1406
1407
1408 /**
1409 * Send the DHCP ack to the requester host.
1410 * Modify Host or Route store according to the type of DHCP.
1411 *
1412 * @param ethernetPacketAck the packet
1413 * @param dhcpPayload the DHCP data
1414 */
1415 private void handleDhcpAck(Ethernet ethernetPacketAck, DHCP dhcpPayload) {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001416 Optional<Interface> outInterface = getClientInterface(ethernetPacketAck, dhcpPayload);
Yi Tseng51301292017-07-28 13:02:59 -07001417 if (!outInterface.isPresent()) {
1418 log.warn("Can't find output interface for dhcp: {}", dhcpPayload);
1419 return;
1420 }
1421
1422 Interface outIface = outInterface.get();
1423 HostLocation hostLocation = new HostLocation(outIface.connectPoint(), System.currentTimeMillis());
1424 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
Yi Tseng4f2a0462017-08-31 11:21:00 -07001425 VlanId vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -07001426 if (vlanId == null) {
1427 vlanId = outIface.vlan();
1428 }
Yi Tseng51301292017-07-28 13:02:59 -07001429 HostId hostId = HostId.hostId(macAddress, vlanId);
1430 Ip4Address ip = Ip4Address.valueOf(dhcpPayload.getYourIPAddress());
1431
1432 if (directlyConnected(dhcpPayload)) {
1433 // Add to host store if it connect to network directly
1434 Set<IpAddress> ips = Sets.newHashSet(ip);
Yi Tsengaa417a62017-09-08 17:22:51 -07001435 Host host = hostService.getHost(hostId);
Yi Tseng51301292017-07-28 13:02:59 -07001436
Yi Tsengaa417a62017-09-08 17:22:51 -07001437 Set<HostLocation> hostLocations = Sets.newHashSet(hostLocation);
1438 if (host != null) {
1439 // Dual homing support:
1440 // if host exists, use old locations and new location
1441 hostLocations.addAll(host.locations());
1442 }
1443 HostDescription desc = new DefaultHostDescription(macAddress, vlanId,
1444 hostLocations, ips, false);
1445 // Add IP address when dhcp server give the host new ip address
1446 providerService.hostDetected(hostId, desc, false);
Yi Tseng51301292017-07-28 13:02:59 -07001447 } else {
1448 // Add to route store if it does not connect to network directly
1449 // Get gateway host IP according to host mac address
Yi Tsengdcef2c22017-08-05 20:34:06 -07001450 // TODO: remove relay store here
Yi Tseng51301292017-07-28 13:02:59 -07001451 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1452
1453 if (record == null) {
1454 log.warn("Can't find DHCP record of host {}", hostId);
1455 return;
1456 }
1457
1458 MacAddress gwMac = record.nextHop().orElse(null);
1459 if (gwMac == null) {
1460 log.warn("Can't find gateway mac address from record {}", record);
1461 return;
1462 }
1463
1464 HostId gwHostId = HostId.hostId(gwMac, record.vlanId());
1465 Host gwHost = hostService.getHost(gwHostId);
1466
1467 if (gwHost == null) {
1468 log.warn("Can't find gateway host {}", gwHostId);
1469 return;
1470 }
1471
1472 Ip4Address nextHopIp = gwHost.ipAddresses()
1473 .stream()
1474 .filter(IpAddress::isIp4)
1475 .map(IpAddress::getIp4Address)
1476 .findFirst()
1477 .orElse(null);
1478
1479 if (nextHopIp == null) {
1480 log.warn("Can't find IP address of gateway {}", gwHost);
1481 return;
1482 }
1483
Charles Chan6305b692018-04-04 11:43:54 -07001484 Route route = new Route(Route.Source.DHCP, ip.toIpPrefix(), nextHopIp);
Daniel Ginsburg83b76452018-06-09 01:43:59 +03001485 routeStore.replaceRoute(route);
Yi Tseng51301292017-07-28 13:02:59 -07001486 }
Yi Tseng51301292017-07-28 13:02:59 -07001487 }
1488
1489 /**
Yi Tseng51301292017-07-28 13:02:59 -07001490 * Gets output interface of a dhcp packet.
1491 * If option 82 exists in the dhcp packet and the option was sent by
Yi Tseng4f2a0462017-08-31 11:21:00 -07001492 * ONOS (circuit format is correct), use the connect
Yi Tseng51301292017-07-28 13:02:59 -07001493 * point and vlan id from circuit id; otherwise, find host by destination
1494 * address and use vlan id from sender (dhcp server).
1495 *
1496 * @param ethPacket the ethernet packet
1497 * @param dhcpPayload the dhcp packet
1498 * @return an interface represent the output port and vlan; empty value
1499 * if the host or circuit id not found
1500 */
Yi Tsengdcef2c22017-08-05 20:34:06 -07001501 private Optional<Interface> getClientInterface(Ethernet ethPacket, DHCP dhcpPayload) {
Yi Tseng51301292017-07-28 13:02:59 -07001502 VlanId originalPacketVlanId = VlanId.vlanId(ethPacket.getVlanID());
Yi Tseng51301292017-07-28 13:02:59 -07001503 DhcpRelayAgentOption option = (DhcpRelayAgentOption) dhcpPayload.getOption(OptionCode_CircuitID);
1504
Yi Tseng4f2a0462017-08-31 11:21:00 -07001505 DhcpOption circuitIdSubOption = option.getSubOption(CIRCUIT_ID.getValue());
1506 try {
1507 CircuitId circuitId = CircuitId.deserialize(circuitIdSubOption.getData());
1508 ConnectPoint connectPoint = ConnectPoint.deviceConnectPoint(circuitId.connectPoint());
1509 VlanId vlanId = circuitId.vlanId();
1510 return interfaceService.getInterfacesByPort(connectPoint)
1511 .stream()
1512 .filter(iface -> interfaceContainsVlan(iface, vlanId))
1513 .findFirst();
1514 } catch (IllegalArgumentException ex) {
1515 // invalid circuit format, didn't sent by ONOS
1516 log.debug("Invalid circuit {}, use information from dhcp payload",
1517 circuitIdSubOption.getData());
Yi Tseng51301292017-07-28 13:02:59 -07001518 }
1519
1520 // Use Vlan Id from DHCP server if DHCP relay circuit id was not
1521 // sent by ONOS or circuit Id can't be parsed
Yi Tsengdcef2c22017-08-05 20:34:06 -07001522 // TODO: remove relay store from this method
Yi Tseng51301292017-07-28 13:02:59 -07001523 MacAddress dstMac = valueOf(dhcpPayload.getClientHardwareAddress());
jayakumarthazhathed5f05d2018-09-25 15:56:51 -04001524 VlanId filteredVlanId = getVlanIdFromDhcpRecord(dstMac, originalPacketVlanId);
1525 // Get the vlan from the dhcp record
1526 if (filteredVlanId == null) {
1527 log.debug("not find the matching DHCP record for mac: {} and vlan: {}", dstMac, originalPacketVlanId);
1528 return Optional.empty();
1529 }
1530
1531 Optional<DhcpRecord> dhcpRecord = dhcpRelayStore.getDhcpRecord(HostId.hostId(dstMac, filteredVlanId));
Yi Tsengdcef2c22017-08-05 20:34:06 -07001532 ConnectPoint clientConnectPoint = dhcpRecord
Yi Tseng51301292017-07-28 13:02:59 -07001533 .map(DhcpRecord::locations)
1534 .orElse(Collections.emptySet())
1535 .stream()
1536 .reduce((hl1, hl2) -> {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001537 // find latest host connect point
Yi Tseng51301292017-07-28 13:02:59 -07001538 if (hl1 == null || hl2 == null) {
1539 return hl1 == null ? hl2 : hl1;
1540 }
1541 return hl1.time() > hl2.time() ? hl1 : hl2;
1542 })
Yi Tsengdcef2c22017-08-05 20:34:06 -07001543 .orElse(null);
Yi Tseng51301292017-07-28 13:02:59 -07001544
Yi Tsengdcef2c22017-08-05 20:34:06 -07001545 if (clientConnectPoint != null) {
1546 return interfaceService.getInterfacesByPort(clientConnectPoint)
1547 .stream()
jayakumarthazhathed5f05d2018-09-25 15:56:51 -04001548 .filter(iface -> interfaceContainsVlan(iface, filteredVlanId))
Yi Tsengdcef2c22017-08-05 20:34:06 -07001549 .findFirst();
1550 }
1551 return Optional.empty();
Yi Tseng51301292017-07-28 13:02:59 -07001552 }
1553
1554 /**
jayakumarthazhathed5f05d2018-09-25 15:56:51 -04001555 * Get the required vlanId in case the DCHP record has more than one vlanId for a given MAC.
1556 *
1557 * @param mac MAC address of the DHCP client
1558 * @param vlan Expected vlan of the DHCP client
1559 */
1560 private VlanId getVlanIdFromDhcpRecord(MacAddress mac, VlanId vlan) {
1561 // Get all the DHCP records matching with the mac address
1562 // If only one entry is present then pick the vlan of that entry
1563 // If more then one entry is present then look for an entry with matching vlan
1564 // else return null
1565 Collection<DhcpRecord> records = dhcpRelayStore.getDhcpRecords();
1566 List<DhcpRecord> filteredRecords = new ArrayList<>();
1567 for (DhcpRecord e: records) {
1568 if (e.macAddress().equals(mac)) {
1569 filteredRecords.add(e);
1570 }
1571 }
1572 log.debug("getVlanIdFromDhcpRecord mac: {} vlan: {}", mac, vlan);
1573 log.debug("filteredRecords are: {}", filteredRecords);
1574 if (filteredRecords.size() == 1) {
1575 log.debug("Only one DHCP record entry. Returning back the vlan of that DHCP record: {}", filteredRecords);
1576 return filteredRecords.get(0).vlanId();
1577 }
1578 // Check in the DHCP filtered record for matching vlan
1579 for (DhcpRecord e: filteredRecords) {
1580 if (e.vlanId().equals(vlan)) {
1581 log.debug("Found a matching vlan entry in the DHCP record:{}", e);
1582 return vlan;
1583 }
1584 }
1585 // Found nothing return null
1586 log.debug("Returning null as no matching or more than one matching entry found");
1587 return null;
1588
1589 }
1590
1591
1592
1593 /**
Yi Tseng51301292017-07-28 13:02:59 -07001594 * Send the response DHCP to the requester host.
1595 *
Taras Lemkin96a0d342018-03-26 14:52:58 +00001596 * @param thePacket the packet
Yi Tseng51301292017-07-28 13:02:59 -07001597 * @param dhcpPayload the DHCP data
1598 */
Taras Lemkin96a0d342018-03-26 14:52:58 +00001599 private void sendResponseToClient(InternalPacket thePacket, DHCP dhcpPayload) {
1600 checkNotNull(thePacket, "Nothing to send");
1601 checkNotNull(thePacket.getPacket(), "Packet to send must not be empty");
1602 checkNotNull(thePacket.getDestLocation(), "Packet destination not be empty");
1603
1604 Ethernet ethPacket = thePacket.getPacket();
Yi Tsengdcef2c22017-08-05 20:34:06 -07001605 if (directlyConnected(dhcpPayload)) {
1606 ethPacket = removeRelayAgentOption(ethPacket);
1607 }
Taras Lemkin96a0d342018-03-26 14:52:58 +00001608
Yi Tsengdcef2c22017-08-05 20:34:06 -07001609 TrafficTreatment treatment = DefaultTrafficTreatment.builder()
Taras Lemkin96a0d342018-03-26 14:52:58 +00001610 .setOutput(thePacket.getDestLocation().port())
Yi Tsengdcef2c22017-08-05 20:34:06 -07001611 .build();
1612 OutboundPacket o = new DefaultOutboundPacket(
Taras Lemkin96a0d342018-03-26 14:52:58 +00001613 thePacket.getDestLocation().deviceId(),
Yi Tsengdcef2c22017-08-05 20:34:06 -07001614 treatment,
1615 ByteBuffer.wrap(ethPacket.serialize()));
1616 if (log.isTraceEnabled()) {
Taras Lemkin96a0d342018-03-26 14:52:58 +00001617 log.trace("Relaying packet to DHCP client {} via {}",
Yi Tsengdcef2c22017-08-05 20:34:06 -07001618 ethPacket,
Taras Lemkin96a0d342018-03-26 14:52:58 +00001619 thePacket.getDestLocation());
Yi Tsengdcef2c22017-08-05 20:34:06 -07001620 }
1621 packetService.emit(o);
Yi Tseng51301292017-07-28 13:02:59 -07001622 }
Yi Tseng483ac6f2017-08-02 15:03:31 -07001623
Yi Tsengaa417a62017-09-08 17:22:51 -07001624 @Override
1625 public void triggerProbe(Host host) {
1626 // Do nothing here
1627 }
1628
1629 @Override
1630 public ProviderId id() {
Charles Chand988c282017-09-12 17:09:32 -07001631 return PROVIDER_ID;
Yi Tsengaa417a62017-09-08 17:22:51 -07001632 }
1633
Yi Tseng483ac6f2017-08-02 15:03:31 -07001634 class InternalHostListener implements HostListener {
1635 @Override
1636 public void event(HostEvent event) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001637 if (!configured()) {
1638 return;
1639 }
Yi Tseng483ac6f2017-08-02 15:03:31 -07001640 switch (event.type()) {
1641 case HOST_ADDED:
1642 case HOST_UPDATED:
Charles Chan24a96ff2018-08-13 10:32:03 -07001643 case HOST_MOVED:
Jordan Halterman6328db72018-04-10 13:34:50 -04001644 log.trace("Scheduled host event {}", event);
1645 hostEventExecutor.execute(() -> hostUpdated(event.subject()));
Yi Tseng483ac6f2017-08-02 15:03:31 -07001646 break;
1647 case HOST_REMOVED:
Jordan Halterman6328db72018-04-10 13:34:50 -04001648 log.trace("Scheduled host event {}", event);
1649 hostEventExecutor.execute(() -> hostRemoved(event.subject()));
Yi Tseng483ac6f2017-08-02 15:03:31 -07001650 break;
Yi Tseng483ac6f2017-08-02 15:03:31 -07001651 default:
1652 break;
1653 }
1654 }
1655 }
1656
1657 /**
Yi Tseng483ac6f2017-08-02 15:03:31 -07001658 * Handle host updated.
1659 * If the host is DHCP server or gateway, update connect mac and vlan.
1660 *
1661 * @param host the host
1662 */
1663 private void hostUpdated(Host host) {
Yi Tseng525ff402017-10-23 19:39:39 -07001664 hostUpdated(host, defaultServerInfoList);
1665 hostUpdated(host, indirectServerInfoList);
Yi Tseng483ac6f2017-08-02 15:03:31 -07001666 }
1667
Yi Tseng525ff402017-10-23 19:39:39 -07001668 private void hostUpdated(Host host, List<DhcpServerInfo> srverInfoList) {
jjosep004c05f55ab2018-08-21 09:01:10 -04001669 srverInfoList.stream().forEach(serverInfo -> {
1670 Ip4Address targetIp = serverInfo.getDhcpGatewayIp4().orElse(null);
Yi Tseng525ff402017-10-23 19:39:39 -07001671 Ip4Address serverIp = serverInfo.getDhcpServerIp4().orElse(null);
Yi Tseng525ff402017-10-23 19:39:39 -07001672 if (targetIp == null) {
1673 targetIp = serverIp;
1674 }
Yi Tseng525ff402017-10-23 19:39:39 -07001675 if (targetIp != null) {
1676 if (host.ipAddresses().contains(targetIp)) {
1677 serverInfo.setDhcpConnectMac(host.mac());
1678 serverInfo.setDhcpConnectVlan(host.vlan());
1679 requestDhcpPacket(serverIp);
1680 }
1681 }
jjosep004c05f55ab2018-08-21 09:01:10 -04001682 });
Yi Tseng525ff402017-10-23 19:39:39 -07001683 }
1684
1685
Yi Tseng483ac6f2017-08-02 15:03:31 -07001686 /**
1687 * Handle host removed.
1688 * If the host is DHCP server or gateway, unset connect mac and vlan.
1689 *
1690 * @param host the host
1691 */
1692 private void hostRemoved(Host host) {
Yi Tseng525ff402017-10-23 19:39:39 -07001693 hostRemoved(host, defaultServerInfoList);
1694 hostRemoved(host, indirectServerInfoList);
1695 }
1696
1697 private void hostRemoved(Host host, List<DhcpServerInfo> serverInfoList) {
jjosep004c05f55ab2018-08-21 09:01:10 -04001698 serverInfoList.stream().forEach(serverInfo -> {
1699 Ip4Address targetIp = serverInfo.getDhcpGatewayIp4().orElse(null);
Yi Tseng525ff402017-10-23 19:39:39 -07001700 Ip4Address serverIp = serverInfo.getDhcpServerIp4().orElse(null);
Yi Tseng525ff402017-10-23 19:39:39 -07001701 if (targetIp == null) {
1702 targetIp = serverIp;
Yi Tseng919b2df2017-09-07 16:22:51 -07001703 }
Yi Tseng525ff402017-10-23 19:39:39 -07001704
1705 if (targetIp != null) {
1706 if (host.ipAddresses().contains(targetIp)) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001707 serverInfo.setDhcpConnectVlan(null);
1708 serverInfo.setDhcpConnectMac(null);
Yi Tseng525ff402017-10-23 19:39:39 -07001709 cancelDhcpPacket(serverIp);
Yi Tseng919b2df2017-09-07 16:22:51 -07001710 }
Yi Tseng483ac6f2017-08-02 15:03:31 -07001711 }
jjosep004c05f55ab2018-08-21 09:01:10 -04001712 });
Yi Tseng525ff402017-10-23 19:39:39 -07001713 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001714
Yi Tseng525ff402017-10-23 19:39:39 -07001715 private void requestDhcpPacket(Ip4Address serverIp) {
1716 requestServerDhcpPacket(serverIp);
1717 requestClientDhcpPacket(serverIp);
1718 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001719
Yi Tseng525ff402017-10-23 19:39:39 -07001720 private void cancelDhcpPacket(Ip4Address serverIp) {
1721 cancelServerDhcpPacket(serverIp);
1722 cancelClientDhcpPacket(serverIp);
1723 }
1724
1725 private void cancelServerDhcpPacket(Ip4Address serverIp) {
1726 TrafficSelector serverSelector =
1727 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1728 .matchIPSrc(serverIp.toIpPrefix())
1729 .build();
1730 packetService.cancelPackets(serverSelector,
1731 PacketPriority.CONTROL,
1732 appId);
1733 }
1734
1735 private void requestServerDhcpPacket(Ip4Address serverIp) {
1736 TrafficSelector serverSelector =
1737 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1738 .matchIPSrc(serverIp.toIpPrefix())
1739 .build();
1740 packetService.requestPackets(serverSelector,
1741 PacketPriority.CONTROL,
1742 appId);
1743 }
1744
1745 private void cancelClientDhcpPacket(Ip4Address serverIp) {
1746 // Packet comes from relay
1747 TrafficSelector indirectClientSelector =
1748 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1749 .matchIPDst(serverIp.toIpPrefix())
1750 .build();
1751 packetService.cancelPackets(indirectClientSelector,
1752 PacketPriority.CONTROL,
1753 appId);
1754
1755 // Packet comes from client
1756 packetService.cancelPackets(CLIENT_SERVER_SELECTOR,
1757 PacketPriority.CONTROL,
1758 appId);
1759 }
1760
1761 private void requestClientDhcpPacket(Ip4Address serverIp) {
1762 // Packet comes from relay
1763 TrafficSelector indirectClientSelector =
1764 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1765 .matchIPDst(serverIp.toIpPrefix())
1766 .build();
1767 packetService.requestPackets(indirectClientSelector,
1768 PacketPriority.CONTROL,
1769 appId);
1770
1771 // Packet comes from client
1772 packetService.requestPackets(CLIENT_SERVER_SELECTOR,
1773 PacketPriority.CONTROL,
1774 appId);
1775 }
1776
1777 /**
1778 * Process the ignore rules.
1779 *
1780 * @param deviceId the device id
1781 * @param vlanId the vlan to be ignored
1782 * @param op the operation, ADD to install; REMOVE to uninstall rules
1783 */
1784 private void processIgnoreVlanRule(DeviceId deviceId, VlanId vlanId, Objective.Operation op) {
Yi Tseng525ff402017-10-23 19:39:39 -07001785 AtomicInteger installedCount = new AtomicInteger(DHCP_SELECTORS.size());
1786 DHCP_SELECTORS.forEach(trafficSelector -> {
1787 TrafficSelector selector = DefaultTrafficSelector.builder(trafficSelector)
1788 .matchVlanId(vlanId)
1789 .build();
1790
1791 ForwardingObjective.Builder builder = DefaultForwardingObjective.builder()
1792 .withFlag(ForwardingObjective.Flag.VERSATILE)
1793 .withSelector(selector)
1794 .withPriority(IGNORE_CONTROL_PRIORITY)
Yi Tsengdbabeed2017-11-29 10:49:20 -08001795 .withTreatment(DefaultTrafficTreatment.emptyTreatment())
Yi Tseng525ff402017-10-23 19:39:39 -07001796 .fromApp(appId);
1797
1798
1799 ObjectiveContext objectiveContext = new ObjectiveContext() {
1800 @Override
1801 public void onSuccess(Objective objective) {
1802 log.info("Ignore rule {} (Vlan id {}, device {}, selector {})",
1803 op, vlanId, deviceId, selector);
1804 int countDown = installedCount.decrementAndGet();
1805 if (countDown != 0) {
1806 return;
1807 }
1808 switch (op) {
1809 case ADD:
1810 ignoredVlans.put(deviceId, vlanId);
1811 break;
1812 case REMOVE:
1813 ignoredVlans.remove(deviceId, vlanId);
1814 break;
1815 default:
1816 log.warn("Unsupported objective operation {}", op);
1817 break;
1818 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001819 }
Yi Tseng525ff402017-10-23 19:39:39 -07001820
1821 @Override
1822 public void onError(Objective objective, ObjectiveError error) {
1823 log.warn("Can't {} ignore rule (vlan id {}, selector {}, device {}) due to {}",
1824 op, vlanId, selector, deviceId, error);
Yi Tseng919b2df2017-09-07 16:22:51 -07001825 }
Yi Tseng525ff402017-10-23 19:39:39 -07001826 };
1827
1828 ForwardingObjective fwd;
1829 switch (op) {
1830 case ADD:
1831 fwd = builder.add(objectiveContext);
1832 break;
1833 case REMOVE:
1834 fwd = builder.remove(objectiveContext);
1835 break;
1836 default:
1837 log.warn("Unsupported objective operation {}", op);
1838 return;
Yi Tseng4f2a0462017-08-31 11:21:00 -07001839 }
Yi Tseng525ff402017-10-23 19:39:39 -07001840
1841 Device device = deviceService.getDevice(deviceId);
1842 if (device == null || !device.is(Pipeliner.class)) {
1843 log.warn("Device {} is not available now, wait until device is available", deviceId);
1844 return;
1845 }
1846 flowObjectiveService.apply(deviceId, fwd);
1847 });
Yi Tseng483ac6f2017-08-02 15:03:31 -07001848 }
Kalhee Kimba366062017-11-07 16:32:09 +00001849
1850 @Override
1851 public void setDhcpFpmEnabled(Boolean enabled) {
1852 // v4 does not use fpm. Do nothing.
1853 }
rsahot036620655b2018-02-26 15:01:37 -05001854 private List<DhcpServerInfo> findValidServerInfo(boolean directConnFlag) {
1855 List<DhcpServerInfo> validServerInfo;
1856
1857 if (directConnFlag || indirectServerInfoList.isEmpty()) {
1858 validServerInfo = new ArrayList<DhcpServerInfo>(defaultServerInfoList);
1859 } else {
1860 validServerInfo = new ArrayList<DhcpServerInfo>(indirectServerInfoList);
1861 }
1862 return validServerInfo;
1863 }
1864
1865
1866 private boolean checkDhcpServerConnPt(boolean directConnFlag,
1867 DhcpServerInfo serverInfo) {
1868 if (serverInfo.getDhcpServerConnectPoint() == null) {
1869 log.warn("DHCP4 server connect point for {} connPt {}",
1870 directConnFlag ? "direct" : "indirect", serverInfo.getDhcpServerConnectPoint());
1871 return false;
1872 }
1873 return true;
1874 }
1875
1876 /**
1877 * Checks if serverInfo's host info (mac and vlan) is filled in; if not, fills in.
1878 *
1879 * @param serverInfo server information
1880 * @return newServerInfo if host info can be either found or filled in.
1881 */
1882 private DhcpServerInfo getHostInfoForServerInfo(DhcpServerInfo serverInfo, List<DhcpServerInfo> sererInfoList) {
1883 DhcpServerInfo newServerInfo = null;
1884 MacAddress dhcpServerConnectMac = serverInfo.getDhcpConnectMac().orElse(null);
1885 VlanId dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1886 ConnectPoint dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1887
1888 if (dhcpServerConnectMac != null && dhcpConnectVlan != null) {
1889 newServerInfo = serverInfo;
Charles Chan2de55302018-03-02 18:27:59 -08001890 log.debug("DHCP server {} host info found. ConnectPt{} Mac {} vlan {}", serverInfo.getDhcpServerIp4(),
rsahot036620655b2018-02-26 15:01:37 -05001891 dhcpServerConnectPoint, dhcpServerConnectMac, dhcpConnectVlan);
1892 } else {
1893 log.warn("DHCP server {} not resolve yet connectPt {} mac {} vlan {}", serverInfo.getDhcpServerIp4(),
1894 dhcpServerConnectPoint, dhcpServerConnectMac, dhcpConnectVlan);
1895
1896 Ip4Address ipToProbe;
1897 if (serverInfo.getDhcpGatewayIp4().isPresent()) {
1898 ipToProbe = serverInfo.getDhcpGatewayIp4().get();
1899 } else {
1900 ipToProbe = serverInfo.getDhcpServerIp4().orElse(null);
1901 }
1902 String hostToProbe = serverInfo.getDhcpGatewayIp6()
1903 .map(ip -> "gateway").orElse("server");
1904
1905 log.warn("Dynamically probing to resolve {} IP {}", hostToProbe, ipToProbe);
1906 hostService.startMonitoringIp(ipToProbe);
1907
1908 Set<Host> hosts = hostService.getHostsByIp(ipToProbe);
1909 if (!hosts.isEmpty()) {
1910 int serverInfoIndex = sererInfoList.indexOf(serverInfo);
1911 Host host = hosts.iterator().next();
1912 serverInfo.setDhcpConnectVlan(host.vlan());
1913 serverInfo.setDhcpConnectMac(host.mac());
1914 // replace the serverInfo in the list
1915 sererInfoList.set(serverInfoIndex, serverInfo);
1916 newServerInfo = serverInfo;
1917 log.warn("Dynamically host found host {}", host);
1918 } else {
1919 log.warn("No host found host ip {} dynamically", ipToProbe);
1920 }
1921 }
1922 return newServerInfo;
1923 }
1924
1925 /**
1926 * Gets Interface facing to the server for default host.
1927 *
1928 * @param serverInfo server information
1929 * @return the Interface facing to the server; null if not found
1930 */
1931 private Interface getServerInterface(DhcpServerInfo serverInfo) {
1932 Interface serverInterface = null;
1933
1934 ConnectPoint dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1935 VlanId dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1936
1937 if (dhcpServerConnectPoint != null && dhcpConnectVlan != null) {
1938 serverInterface = interfaceService.getInterfacesByPort(dhcpServerConnectPoint)
1939 .stream()
Taras Lemkin96a0d342018-03-26 14:52:58 +00001940 .filter(iface -> Dhcp4HandlerUtil.interfaceContainsVlan(iface, dhcpConnectVlan))
rsahot036620655b2018-02-26 15:01:37 -05001941 .findFirst()
1942 .orElse(null);
1943 } else {
1944 log.warn("DHCP server {} not resolve yet connectPoint {} vlan {}", serverInfo.getDhcpServerIp6(),
1945 dhcpServerConnectPoint, dhcpConnectVlan);
1946 }
1947
1948 return serverInterface;
1949 }
1950
1951 //forward the packet to ConnectPoint where the DHCP server is attached.
1952 private void forwardPacket(InternalPacket packet) {
1953 //send Packetout to dhcp server connectpoint.
Taras Lemkin96a0d342018-03-26 14:52:58 +00001954 if (packet.getDestLocation() != null) {
rsahot036620655b2018-02-26 15:01:37 -05001955 TrafficTreatment t = DefaultTrafficTreatment.builder()
Taras Lemkin96a0d342018-03-26 14:52:58 +00001956 .setOutput(packet.getDestLocation().port()).build();
rsahot036620655b2018-02-26 15:01:37 -05001957 OutboundPacket o = new DefaultOutboundPacket(
Taras Lemkin96a0d342018-03-26 14:52:58 +00001958 packet.getDestLocation().deviceId(), t, ByteBuffer.wrap(packet.getPacket().serialize()));
rsahot036620655b2018-02-26 15:01:37 -05001959 if (log.isTraceEnabled()) {
Taras Lemkin96a0d342018-03-26 14:52:58 +00001960 log.trace("Relaying packet to destination {}", packet.getDestLocation());
rsahot036620655b2018-02-26 15:01:37 -05001961 }
Taras Lemkin96a0d342018-03-26 14:52:58 +00001962 log.debug("packetService.emit(o) to port {}", packet.getDestLocation());
rsahot036620655b2018-02-26 15:01:37 -05001963 packetService.emit(o);
1964 }
1965 }
1966
1967
1968 private DhcpServerInfo findServerInfoFromServer(boolean directConnFlag, ConnectPoint inPort) {
1969 List<DhcpServerInfo> validServerInfoList = findValidServerInfo(directConnFlag);
1970 DhcpServerInfo foundServerInfo = null;
1971 for (DhcpServerInfo serverInfo : validServerInfoList) {
1972 if (inPort.equals(serverInfo.getDhcpServerConnectPoint().get())) {
1973 foundServerInfo = serverInfo;
Charles Chan2de55302018-03-02 18:27:59 -08001974 log.debug("ServerInfo found for Rcv port {} Server Connect Point {} for {}",
rsahot036620655b2018-02-26 15:01:37 -05001975 inPort, serverInfo.getDhcpServerConnectPoint(), directConnFlag ? "direct" : "indirect");
1976 break;
rsahot036620655b2018-02-26 15:01:37 -05001977 }
1978 }
1979 return foundServerInfo;
1980 }
Yi Tseng51301292017-07-28 13:02:59 -07001981}