blob: 886115bde126e4357fa9ac28bff36a1c9314f6a5 [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) {
1140 log.warn("Cannot find server info");
1141 return null;
1142 } else {
Taras Lemkin96a0d342018-03-26 14:52:58 +00001143 if (Dhcp4HandlerUtil.isServerIpEmpty(foundServerInfo)) {
rsahot036620655b2018-02-26 15:01:37 -05001144 log.warn("Cannot find server info's ipaddress");
1145 return null;
1146 }
1147 }
Yi Tsengdcef2c22017-08-05 20:34:06 -07001148 if (clientInterface.vlanTagged().isEmpty()) {
1149 vlanId = clientInterface.vlan();
1150 } else {
1151 // might be multiple vlan in same interface
Yi Tseng4f2a0462017-08-31 11:21:00 -07001152 vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -07001153 }
1154 if (vlanId == null) {
1155 vlanId = VlanId.NONE;
1156 }
1157 etherReply.setVlanID(vlanId.toShort());
1158 etherReply.setSourceMACAddress(clientInterface.mac());
Yi Tseng51301292017-07-28 13:02:59 -07001159
Yi Tsengdcef2c22017-08-05 20:34:06 -07001160 if (!directlyConnected(dhcpPayload)) {
1161 // if client is indirectly connected, try use next hop mac address
1162 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
1163 HostId hostId = HostId.hostId(macAddress, vlanId);
Daniel Ginsburgb1dec912018-01-29 11:40:22 -08001164 if (((int) dhcpPayload.getFlags() & 0x8000) == 0x0000) {
1165 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1166 if (record != null) {
1167 // if next hop can be found, use mac address of next hop
1168 record.nextHop().ifPresent(etherReply::setDestinationMACAddress);
1169 } else {
1170 // otherwise, discard the packet
1171 log.warn("Can't find record for host id {}, discard packet", hostId);
1172 return null;
1173 }
Yi Tsengdcef2c22017-08-05 20:34:06 -07001174 } else {
Daniel Ginsburgb1dec912018-01-29 11:40:22 -08001175 etherReply.setDestinationMACAddress(MacAddress.BROADCAST);
Yi Tsengdcef2c22017-08-05 20:34:06 -07001176 }
Yi Tseng1696f562017-08-17 17:43:38 -07001177 } else {
1178 etherReply.setDestinationMACAddress(dhcpPayload.getClientHardwareAddress());
Yi Tsengdcef2c22017-08-05 20:34:06 -07001179 }
1180
Yi Tseng51301292017-07-28 13:02:59 -07001181 // we leave the srcMac from the original packet
Yi Tseng51301292017-07-28 13:02:59 -07001182 // figure out the relay agent IP corresponding to the original request
Yi Tseng3df7f9d2017-08-17 13:08:31 -07001183 Ip4Address ipFacingClient = getFirstIpFromInterface(clientInterface);
1184 if (ipFacingClient == null) {
Yi Tseng51301292017-07-28 13:02:59 -07001185 log.warn("Cannot determine relay agent interface Ipv4 addr for host {}/{}. "
1186 + "Aborting relay for dhcp packet from server {}",
Yi Tsengdcef2c22017-08-05 20:34:06 -07001187 etherReply.getDestinationMAC(), clientInterface.vlan(),
Yi Tseng51301292017-07-28 13:02:59 -07001188 ethernetPacket);
1189 return null;
1190 }
1191 // SRC_IP: relay agent IP
1192 // DST_IP: offered IP
Yi Tseng3df7f9d2017-08-17 13:08:31 -07001193 ipv4Packet.setSourceAddress(ipFacingClient.toInt());
Daniel Ginsburgb1dec912018-01-29 11:40:22 -08001194 if (((int) dhcpPayload.getFlags() & 0x8000) == 0x0000) {
1195 ipv4Packet.setDestinationAddress(dhcpPayload.getYourIPAddress());
1196 } else {
1197 ipv4Packet.setDestinationAddress(BROADCAST_IP);
1198 }
Yi Tseng51301292017-07-28 13:02:59 -07001199 udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
1200 if (directlyConnected(dhcpPayload)) {
1201 udpPacket.setDestinationPort(UDP.DHCP_CLIENT_PORT);
1202 } else {
1203 // forward to another dhcp relay
Yi Tseng93ba53c2017-09-14 13:24:21 -07001204 // FIXME: Currently we assume the DHCP comes from a L2 relay with
1205 // Option 82, this might not work if DHCP message comes from
1206 // L3 relay.
1207 udpPacket.setDestinationPort(UDP.DHCP_CLIENT_PORT);
Yi Tseng51301292017-07-28 13:02:59 -07001208 }
1209
1210 udpPacket.setPayload(dhcpPayload);
1211 ipv4Packet.setPayload(udpPacket);
1212 etherReply.setPayload(ipv4Packet);
Taras Lemkin96a0d342018-03-26 14:52:58 +00001213 return InternalPacket.internalPacket(etherReply, clientInterface.connectPoint());
Yi Tseng51301292017-07-28 13:02:59 -07001214 }
1215
Yi Tsengdcef2c22017-08-05 20:34:06 -07001216 /**
Charles Chand0dd7002017-10-08 23:53:36 -04001217 * Build the DHCP offer/ack with proper client port.
1218 *
1219 * @param ethernetPacket the original packet comes from server
1220 * @return new packet which will send to the client
1221 */
Taras Lemkin96a0d342018-03-26 14:52:58 +00001222 private InternalPacket processLeaseQueryFromServer(Ethernet ethernetPacket) {
Charles Chand0dd7002017-10-08 23:53:36 -04001223 // get dhcp header.
1224 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
1225 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
1226 UDP udpPacket = (UDP) ipv4Packet.getPayload();
1227 DHCP dhcpPayload = (DHCP) udpPacket.getPayload();
1228
1229 // determine the vlanId of the client host - note that this vlan id
1230 // could be different from the vlan in the packet from the server
Taras Lemkin96a0d342018-03-26 14:52:58 +00001231 Interface clientInterface = null;
1232 MacAddress destinationMac = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
1233
1234 if (!learnRouteFromLeasequery) {
1235 int giaddr = ipv4Packet.getDestinationAddress();
1236 IpAddress destinationAddress = Ip4Address.valueOf(giaddr);
1237 log.debug("DHCPLEASEQUERYRESP giaddr: {}({})", giaddr, destinationAddress);
1238
1239 Host destinationHost = hostService.getHostsByIp(destinationAddress).stream().findFirst().orElse(null);
1240 if (destinationHost != null) {
1241 destinationMac = destinationHost.mac();
1242 log.trace("DHCPLEASEQUERYRESP destination mac is: {}", destinationMac);
1243 ConnectPoint destinationLocation = destinationHost.location();
1244 log.trace("Lookup for client interface by destination location {}", destinationLocation);
1245 clientInterface = interfaceService.getInterfacesByPort(destinationLocation)
1246 .stream()
1247 .filter(iface -> interfaceContainsVlan(iface, VlanId.vlanId(etherReply.getVlanID())))
1248 .findFirst()
1249 .orElse(null);
1250 log.trace("Found Host {} by ip {}", destinationHost, destinationAddress);
1251 log.debug("DHCPLEASEQUERYRESP Client interface: {}",
1252 (clientInterface != null ? clientInterface : "not resolved"));
1253
1254 }
1255 } else {
1256 clientInterface = getClientInterface(ethernetPacket, dhcpPayload).orElse(null);
1257 }
Charles Chand0dd7002017-10-08 23:53:36 -04001258
1259 if (clientInterface == null) {
1260 log.warn("Cannot find the interface for the DHCP {}", dhcpPayload);
1261 return null;
1262 }
1263 VlanId vlanId;
1264 if (clientInterface.vlanTagged().isEmpty()) {
1265 vlanId = clientInterface.vlan();
1266 } else {
1267 // might be multiple vlan in same interface
1268 vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
1269 }
1270 if (vlanId == null) {
1271 vlanId = VlanId.NONE;
1272 }
1273 etherReply.setVlanID(vlanId.toShort());
1274 etherReply.setSourceMACAddress(clientInterface.mac());
1275
Taras Lemkin96a0d342018-03-26 14:52:58 +00001276 if (!directlyConnected(dhcpPayload) && learnRouteFromLeasequery) {
Charles Chand0dd7002017-10-08 23:53:36 -04001277 // if client is indirectly connected, try use next hop mac address
1278 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
1279 HostId hostId = HostId.hostId(macAddress, vlanId);
1280 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1281 if (record != null) {
1282 // if next hop can be found, use mac address of next hop
Taras Lemkin96a0d342018-03-26 14:52:58 +00001283 Optional<MacAddress> nextHop = record.nextHopTemp();
1284 if (!nextHop.isPresent()) {
1285 nextHop = record.nextHop();
1286 }
1287 nextHop.ifPresent(etherReply::setDestinationMACAddress);
Charles Chand0dd7002017-10-08 23:53:36 -04001288 } else {
1289 // otherwise, discard the packet
1290 log.warn("Can't find record for host id {}, discard packet", hostId);
1291 return null;
1292 }
1293 } else {
Taras Lemkin96a0d342018-03-26 14:52:58 +00001294 etherReply.setDestinationMACAddress(destinationMac);
Charles Chand0dd7002017-10-08 23:53:36 -04001295 }
1296
Charles Chand0dd7002017-10-08 23:53:36 -04001297 udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
Taras Lemkin96a0d342018-03-26 14:52:58 +00001298 if (directlyConnected(dhcpPayload)) {
1299 udpPacket.setDestinationPort(UDP.DHCP_CLIENT_PORT);
1300 } else {
1301 udpPacket.setDestinationPort(UDP.DHCP_SERVER_PORT);
1302 }
Charles Chand0dd7002017-10-08 23:53:36 -04001303
1304 udpPacket.setPayload(dhcpPayload);
1305 ipv4Packet.setPayload(udpPacket);
1306 etherReply.setPayload(ipv4Packet);
Taras Lemkin96a0d342018-03-26 14:52:58 +00001307 udpPacket.resetChecksum();
1308
1309 return InternalPacket.internalPacket(etherReply, clientInterface.connectPoint());
Charles Chand0dd7002017-10-08 23:53:36 -04001310 }
1311 /**
Yi Tsengdcef2c22017-08-05 20:34:06 -07001312 * Extracts VLAN ID from relay agent option.
1313 *
1314 * @param dhcpPayload the DHCP payload
1315 * @return VLAN ID from DHCP payload; null if not exists
1316 */
Yi Tseng4f2a0462017-08-31 11:21:00 -07001317 private VlanId getVlanIdFromRelayAgentOption(DHCP dhcpPayload) {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001318 DhcpRelayAgentOption option = (DhcpRelayAgentOption) dhcpPayload.getOption(OptionCode_CircuitID);
1319 if (option == null) {
1320 return null;
1321 }
1322 DhcpOption circuitIdSubOption = option.getSubOption(CIRCUIT_ID.getValue());
1323 if (circuitIdSubOption == null) {
1324 return null;
1325 }
1326 try {
1327 CircuitId circuitId = CircuitId.deserialize(circuitIdSubOption.getData());
1328 return circuitId.vlanId();
1329 } catch (IllegalArgumentException e) {
1330 // can't deserialize the circuit ID
1331 return null;
1332 }
1333 }
1334
1335 /**
1336 * Removes DHCP relay agent information option (option 82) from DHCP payload.
1337 * Also reset giaddr to 0
1338 *
1339 * @param ethPacket the Ethernet packet to be processed
1340 * @return Ethernet packet processed
1341 */
1342 private Ethernet removeRelayAgentOption(Ethernet ethPacket) {
rsahot036620655b2018-02-26 15:01:37 -05001343 Ethernet ethernet = (Ethernet) ethPacket.duplicate();
Yi Tsengdcef2c22017-08-05 20:34:06 -07001344 IPv4 ipv4 = (IPv4) ethernet.getPayload();
1345 UDP udp = (UDP) ipv4.getPayload();
1346 DHCP dhcpPayload = (DHCP) udp.getPayload();
1347
1348 // removes relay agent information option
1349 List<DhcpOption> options = dhcpPayload.getOptions();
1350 options = options.stream()
1351 .filter(option -> option.getCode() != OptionCode_CircuitID.getValue())
1352 .collect(Collectors.toList());
1353 dhcpPayload.setOptions(options);
1354 dhcpPayload.setGatewayIPAddress(0);
1355
1356 udp.setPayload(dhcpPayload);
1357 ipv4.setPayload(udp);
1358 ethernet.setPayload(ipv4);
1359 return ethernet;
1360 }
1361
Taras Lemkin96a0d342018-03-26 14:52:58 +00001362 private boolean isDhcpPacketLeasequery(DHCP dhcpPacket) {
1363 switch (dhcpPacket.getPacketType()) {
1364 case DHCPLEASEACTIVE:
1365 case DHCPLEASEQUERY:
1366 case DHCPLEASEUNASSIGNED:
1367 case DHCPLEASEUNKNOWN:
1368 return true;
1369 default:
1370 return false;
1371 }
1372 }
Yi Tseng51301292017-07-28 13:02:59 -07001373
1374 /**
1375 * Check if the host is directly connected to the network or not.
1376 *
1377 * @param dhcpPayload the dhcp payload
1378 * @return true if the host is directly connected to the network; false otherwise
1379 */
1380 private boolean directlyConnected(DHCP dhcpPayload) {
Taras Lemkin96a0d342018-03-26 14:52:58 +00001381 // leasequery is always indirect
1382 if (isDhcpPacketLeasequery(dhcpPayload)) {
1383 return false;
1384 }
1385
Yi Tseng440e2b72017-08-24 14:47:34 -07001386 DhcpRelayAgentOption relayAgentOption =
1387 (DhcpRelayAgentOption) dhcpPayload.getOption(OptionCode_CircuitID);
Yi Tseng51301292017-07-28 13:02:59 -07001388
1389 // Doesn't contains relay option
1390 if (relayAgentOption == null) {
1391 return true;
1392 }
1393
Yi Tseng440e2b72017-08-24 14:47:34 -07001394 // check circuit id, if circuit id is invalid, we say it is an indirect host
1395 DhcpOption circuitIdOpt = relayAgentOption.getSubOption(CIRCUIT_ID.getValue());
Yi Tseng51301292017-07-28 13:02:59 -07001396
Yi Tseng440e2b72017-08-24 14:47:34 -07001397 try {
1398 CircuitId.deserialize(circuitIdOpt.getData());
Yi Tseng51301292017-07-28 13:02:59 -07001399 return true;
Yi Tseng440e2b72017-08-24 14:47:34 -07001400 } catch (Exception e) {
1401 // invalid circuit id
1402 return false;
Yi Tseng51301292017-07-28 13:02:59 -07001403 }
Yi Tseng51301292017-07-28 13:02:59 -07001404 }
1405
1406
1407 /**
1408 * Send the DHCP ack to the requester host.
1409 * Modify Host or Route store according to the type of DHCP.
1410 *
1411 * @param ethernetPacketAck the packet
1412 * @param dhcpPayload the DHCP data
1413 */
1414 private void handleDhcpAck(Ethernet ethernetPacketAck, DHCP dhcpPayload) {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001415 Optional<Interface> outInterface = getClientInterface(ethernetPacketAck, dhcpPayload);
Yi Tseng51301292017-07-28 13:02:59 -07001416 if (!outInterface.isPresent()) {
1417 log.warn("Can't find output interface for dhcp: {}", dhcpPayload);
1418 return;
1419 }
1420
1421 Interface outIface = outInterface.get();
1422 HostLocation hostLocation = new HostLocation(outIface.connectPoint(), System.currentTimeMillis());
1423 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
Yi Tseng4f2a0462017-08-31 11:21:00 -07001424 VlanId vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -07001425 if (vlanId == null) {
1426 vlanId = outIface.vlan();
1427 }
Yi Tseng51301292017-07-28 13:02:59 -07001428 HostId hostId = HostId.hostId(macAddress, vlanId);
1429 Ip4Address ip = Ip4Address.valueOf(dhcpPayload.getYourIPAddress());
1430
1431 if (directlyConnected(dhcpPayload)) {
1432 // Add to host store if it connect to network directly
1433 Set<IpAddress> ips = Sets.newHashSet(ip);
Yi Tsengaa417a62017-09-08 17:22:51 -07001434 Host host = hostService.getHost(hostId);
Yi Tseng51301292017-07-28 13:02:59 -07001435
Yi Tsengaa417a62017-09-08 17:22:51 -07001436 Set<HostLocation> hostLocations = Sets.newHashSet(hostLocation);
1437 if (host != null) {
1438 // Dual homing support:
1439 // if host exists, use old locations and new location
1440 hostLocations.addAll(host.locations());
1441 }
1442 HostDescription desc = new DefaultHostDescription(macAddress, vlanId,
1443 hostLocations, ips, false);
1444 // Add IP address when dhcp server give the host new ip address
1445 providerService.hostDetected(hostId, desc, false);
Yi Tseng51301292017-07-28 13:02:59 -07001446 } else {
1447 // Add to route store if it does not connect to network directly
1448 // Get gateway host IP according to host mac address
Yi Tsengdcef2c22017-08-05 20:34:06 -07001449 // TODO: remove relay store here
Yi Tseng51301292017-07-28 13:02:59 -07001450 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1451
1452 if (record == null) {
1453 log.warn("Can't find DHCP record of host {}", hostId);
1454 return;
1455 }
1456
1457 MacAddress gwMac = record.nextHop().orElse(null);
1458 if (gwMac == null) {
1459 log.warn("Can't find gateway mac address from record {}", record);
1460 return;
1461 }
1462
1463 HostId gwHostId = HostId.hostId(gwMac, record.vlanId());
1464 Host gwHost = hostService.getHost(gwHostId);
1465
1466 if (gwHost == null) {
1467 log.warn("Can't find gateway host {}", gwHostId);
1468 return;
1469 }
1470
1471 Ip4Address nextHopIp = gwHost.ipAddresses()
1472 .stream()
1473 .filter(IpAddress::isIp4)
1474 .map(IpAddress::getIp4Address)
1475 .findFirst()
1476 .orElse(null);
1477
1478 if (nextHopIp == null) {
1479 log.warn("Can't find IP address of gateway {}", gwHost);
1480 return;
1481 }
1482
Charles Chan6305b692018-04-04 11:43:54 -07001483 Route route = new Route(Route.Source.DHCP, ip.toIpPrefix(), nextHopIp);
Daniel Ginsburg83b76452018-06-09 01:43:59 +03001484 routeStore.replaceRoute(route);
Yi Tseng51301292017-07-28 13:02:59 -07001485 }
Yi Tseng51301292017-07-28 13:02:59 -07001486 }
1487
1488 /**
Yi Tseng51301292017-07-28 13:02:59 -07001489 * Gets output interface of a dhcp packet.
1490 * If option 82 exists in the dhcp packet and the option was sent by
Yi Tseng4f2a0462017-08-31 11:21:00 -07001491 * ONOS (circuit format is correct), use the connect
Yi Tseng51301292017-07-28 13:02:59 -07001492 * point and vlan id from circuit id; otherwise, find host by destination
1493 * address and use vlan id from sender (dhcp server).
1494 *
1495 * @param ethPacket the ethernet packet
1496 * @param dhcpPayload the dhcp packet
1497 * @return an interface represent the output port and vlan; empty value
1498 * if the host or circuit id not found
1499 */
Yi Tsengdcef2c22017-08-05 20:34:06 -07001500 private Optional<Interface> getClientInterface(Ethernet ethPacket, DHCP dhcpPayload) {
Yi Tseng51301292017-07-28 13:02:59 -07001501 VlanId originalPacketVlanId = VlanId.vlanId(ethPacket.getVlanID());
Yi Tseng51301292017-07-28 13:02:59 -07001502 DhcpRelayAgentOption option = (DhcpRelayAgentOption) dhcpPayload.getOption(OptionCode_CircuitID);
1503
Yi Tseng4f2a0462017-08-31 11:21:00 -07001504 DhcpOption circuitIdSubOption = option.getSubOption(CIRCUIT_ID.getValue());
1505 try {
1506 CircuitId circuitId = CircuitId.deserialize(circuitIdSubOption.getData());
1507 ConnectPoint connectPoint = ConnectPoint.deviceConnectPoint(circuitId.connectPoint());
1508 VlanId vlanId = circuitId.vlanId();
1509 return interfaceService.getInterfacesByPort(connectPoint)
1510 .stream()
1511 .filter(iface -> interfaceContainsVlan(iface, vlanId))
1512 .findFirst();
1513 } catch (IllegalArgumentException ex) {
1514 // invalid circuit format, didn't sent by ONOS
1515 log.debug("Invalid circuit {}, use information from dhcp payload",
1516 circuitIdSubOption.getData());
Yi Tseng51301292017-07-28 13:02:59 -07001517 }
1518
1519 // Use Vlan Id from DHCP server if DHCP relay circuit id was not
1520 // sent by ONOS or circuit Id can't be parsed
Yi Tsengdcef2c22017-08-05 20:34:06 -07001521 // TODO: remove relay store from this method
Yi Tseng51301292017-07-28 13:02:59 -07001522 MacAddress dstMac = valueOf(dhcpPayload.getClientHardwareAddress());
1523 Optional<DhcpRecord> dhcpRecord = dhcpRelayStore.getDhcpRecord(HostId.hostId(dstMac, originalPacketVlanId));
Yi Tsengdcef2c22017-08-05 20:34:06 -07001524 ConnectPoint clientConnectPoint = dhcpRecord
Yi Tseng51301292017-07-28 13:02:59 -07001525 .map(DhcpRecord::locations)
1526 .orElse(Collections.emptySet())
1527 .stream()
1528 .reduce((hl1, hl2) -> {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001529 // find latest host connect point
Yi Tseng51301292017-07-28 13:02:59 -07001530 if (hl1 == null || hl2 == null) {
1531 return hl1 == null ? hl2 : hl1;
1532 }
1533 return hl1.time() > hl2.time() ? hl1 : hl2;
1534 })
Yi Tsengdcef2c22017-08-05 20:34:06 -07001535 .orElse(null);
Yi Tseng51301292017-07-28 13:02:59 -07001536
Yi Tsengdcef2c22017-08-05 20:34:06 -07001537 if (clientConnectPoint != null) {
1538 return interfaceService.getInterfacesByPort(clientConnectPoint)
1539 .stream()
Yi Tseng4f2a0462017-08-31 11:21:00 -07001540 .filter(iface -> interfaceContainsVlan(iface, originalPacketVlanId))
Yi Tsengdcef2c22017-08-05 20:34:06 -07001541 .findFirst();
1542 }
1543 return Optional.empty();
Yi Tseng51301292017-07-28 13:02:59 -07001544 }
1545
1546 /**
1547 * Send the response DHCP to the requester host.
1548 *
Taras Lemkin96a0d342018-03-26 14:52:58 +00001549 * @param thePacket the packet
Yi Tseng51301292017-07-28 13:02:59 -07001550 * @param dhcpPayload the DHCP data
1551 */
Taras Lemkin96a0d342018-03-26 14:52:58 +00001552 private void sendResponseToClient(InternalPacket thePacket, DHCP dhcpPayload) {
1553 checkNotNull(thePacket, "Nothing to send");
1554 checkNotNull(thePacket.getPacket(), "Packet to send must not be empty");
1555 checkNotNull(thePacket.getDestLocation(), "Packet destination not be empty");
1556
1557 Ethernet ethPacket = thePacket.getPacket();
Yi Tsengdcef2c22017-08-05 20:34:06 -07001558 if (directlyConnected(dhcpPayload)) {
1559 ethPacket = removeRelayAgentOption(ethPacket);
1560 }
Taras Lemkin96a0d342018-03-26 14:52:58 +00001561
Yi Tsengdcef2c22017-08-05 20:34:06 -07001562 TrafficTreatment treatment = DefaultTrafficTreatment.builder()
Taras Lemkin96a0d342018-03-26 14:52:58 +00001563 .setOutput(thePacket.getDestLocation().port())
Yi Tsengdcef2c22017-08-05 20:34:06 -07001564 .build();
1565 OutboundPacket o = new DefaultOutboundPacket(
Taras Lemkin96a0d342018-03-26 14:52:58 +00001566 thePacket.getDestLocation().deviceId(),
Yi Tsengdcef2c22017-08-05 20:34:06 -07001567 treatment,
1568 ByteBuffer.wrap(ethPacket.serialize()));
1569 if (log.isTraceEnabled()) {
Taras Lemkin96a0d342018-03-26 14:52:58 +00001570 log.trace("Relaying packet to DHCP client {} via {}",
Yi Tsengdcef2c22017-08-05 20:34:06 -07001571 ethPacket,
Taras Lemkin96a0d342018-03-26 14:52:58 +00001572 thePacket.getDestLocation());
Yi Tsengdcef2c22017-08-05 20:34:06 -07001573 }
1574 packetService.emit(o);
Yi Tseng51301292017-07-28 13:02:59 -07001575 }
Yi Tseng483ac6f2017-08-02 15:03:31 -07001576
Yi Tsengaa417a62017-09-08 17:22:51 -07001577 @Override
1578 public void triggerProbe(Host host) {
1579 // Do nothing here
1580 }
1581
1582 @Override
1583 public ProviderId id() {
Charles Chand988c282017-09-12 17:09:32 -07001584 return PROVIDER_ID;
Yi Tsengaa417a62017-09-08 17:22:51 -07001585 }
1586
Yi Tseng483ac6f2017-08-02 15:03:31 -07001587 class InternalHostListener implements HostListener {
1588 @Override
1589 public void event(HostEvent event) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001590 if (!configured()) {
1591 return;
1592 }
Yi Tseng483ac6f2017-08-02 15:03:31 -07001593 switch (event.type()) {
1594 case HOST_ADDED:
1595 case HOST_UPDATED:
Charles Chan24a96ff2018-08-13 10:32:03 -07001596 case HOST_MOVED:
Jordan Halterman6328db72018-04-10 13:34:50 -04001597 log.trace("Scheduled host event {}", event);
1598 hostEventExecutor.execute(() -> hostUpdated(event.subject()));
Yi Tseng483ac6f2017-08-02 15:03:31 -07001599 break;
1600 case HOST_REMOVED:
Jordan Halterman6328db72018-04-10 13:34:50 -04001601 log.trace("Scheduled host event {}", event);
1602 hostEventExecutor.execute(() -> hostRemoved(event.subject()));
Yi Tseng483ac6f2017-08-02 15:03:31 -07001603 break;
Yi Tseng483ac6f2017-08-02 15:03:31 -07001604 default:
1605 break;
1606 }
1607 }
1608 }
1609
1610 /**
Yi Tseng483ac6f2017-08-02 15:03:31 -07001611 * Handle host updated.
1612 * If the host is DHCP server or gateway, update connect mac and vlan.
1613 *
1614 * @param host the host
1615 */
1616 private void hostUpdated(Host host) {
Yi Tseng525ff402017-10-23 19:39:39 -07001617 hostUpdated(host, defaultServerInfoList);
1618 hostUpdated(host, indirectServerInfoList);
Yi Tseng483ac6f2017-08-02 15:03:31 -07001619 }
1620
Yi Tseng525ff402017-10-23 19:39:39 -07001621 private void hostUpdated(Host host, List<DhcpServerInfo> srverInfoList) {
jjosep004c05f55ab2018-08-21 09:01:10 -04001622 srverInfoList.stream().forEach(serverInfo -> {
1623 Ip4Address targetIp = serverInfo.getDhcpGatewayIp4().orElse(null);
Yi Tseng525ff402017-10-23 19:39:39 -07001624 Ip4Address serverIp = serverInfo.getDhcpServerIp4().orElse(null);
Yi Tseng525ff402017-10-23 19:39:39 -07001625 if (targetIp == null) {
1626 targetIp = serverIp;
1627 }
Yi Tseng525ff402017-10-23 19:39:39 -07001628 if (targetIp != null) {
1629 if (host.ipAddresses().contains(targetIp)) {
1630 serverInfo.setDhcpConnectMac(host.mac());
1631 serverInfo.setDhcpConnectVlan(host.vlan());
1632 requestDhcpPacket(serverIp);
1633 }
1634 }
jjosep004c05f55ab2018-08-21 09:01:10 -04001635 });
Yi Tseng525ff402017-10-23 19:39:39 -07001636 }
1637
1638
Yi Tseng483ac6f2017-08-02 15:03:31 -07001639 /**
1640 * Handle host removed.
1641 * If the host is DHCP server or gateway, unset connect mac and vlan.
1642 *
1643 * @param host the host
1644 */
1645 private void hostRemoved(Host host) {
Yi Tseng525ff402017-10-23 19:39:39 -07001646 hostRemoved(host, defaultServerInfoList);
1647 hostRemoved(host, indirectServerInfoList);
1648 }
1649
1650 private void hostRemoved(Host host, List<DhcpServerInfo> serverInfoList) {
jjosep004c05f55ab2018-08-21 09:01:10 -04001651 serverInfoList.stream().forEach(serverInfo -> {
1652 Ip4Address targetIp = serverInfo.getDhcpGatewayIp4().orElse(null);
Yi Tseng525ff402017-10-23 19:39:39 -07001653 Ip4Address serverIp = serverInfo.getDhcpServerIp4().orElse(null);
Yi Tseng525ff402017-10-23 19:39:39 -07001654 if (targetIp == null) {
1655 targetIp = serverIp;
Yi Tseng919b2df2017-09-07 16:22:51 -07001656 }
Yi Tseng525ff402017-10-23 19:39:39 -07001657
1658 if (targetIp != null) {
1659 if (host.ipAddresses().contains(targetIp)) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001660 serverInfo.setDhcpConnectVlan(null);
1661 serverInfo.setDhcpConnectMac(null);
Yi Tseng525ff402017-10-23 19:39:39 -07001662 cancelDhcpPacket(serverIp);
Yi Tseng919b2df2017-09-07 16:22:51 -07001663 }
Yi Tseng483ac6f2017-08-02 15:03:31 -07001664 }
jjosep004c05f55ab2018-08-21 09:01:10 -04001665 });
Yi Tseng525ff402017-10-23 19:39:39 -07001666 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001667
Yi Tseng525ff402017-10-23 19:39:39 -07001668 private void requestDhcpPacket(Ip4Address serverIp) {
1669 requestServerDhcpPacket(serverIp);
1670 requestClientDhcpPacket(serverIp);
1671 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001672
Yi Tseng525ff402017-10-23 19:39:39 -07001673 private void cancelDhcpPacket(Ip4Address serverIp) {
1674 cancelServerDhcpPacket(serverIp);
1675 cancelClientDhcpPacket(serverIp);
1676 }
1677
1678 private void cancelServerDhcpPacket(Ip4Address serverIp) {
1679 TrafficSelector serverSelector =
1680 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1681 .matchIPSrc(serverIp.toIpPrefix())
1682 .build();
1683 packetService.cancelPackets(serverSelector,
1684 PacketPriority.CONTROL,
1685 appId);
1686 }
1687
1688 private void requestServerDhcpPacket(Ip4Address serverIp) {
1689 TrafficSelector serverSelector =
1690 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1691 .matchIPSrc(serverIp.toIpPrefix())
1692 .build();
1693 packetService.requestPackets(serverSelector,
1694 PacketPriority.CONTROL,
1695 appId);
1696 }
1697
1698 private void cancelClientDhcpPacket(Ip4Address serverIp) {
1699 // Packet comes from relay
1700 TrafficSelector indirectClientSelector =
1701 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1702 .matchIPDst(serverIp.toIpPrefix())
1703 .build();
1704 packetService.cancelPackets(indirectClientSelector,
1705 PacketPriority.CONTROL,
1706 appId);
1707
1708 // Packet comes from client
1709 packetService.cancelPackets(CLIENT_SERVER_SELECTOR,
1710 PacketPriority.CONTROL,
1711 appId);
1712 }
1713
1714 private void requestClientDhcpPacket(Ip4Address serverIp) {
1715 // Packet comes from relay
1716 TrafficSelector indirectClientSelector =
1717 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1718 .matchIPDst(serverIp.toIpPrefix())
1719 .build();
1720 packetService.requestPackets(indirectClientSelector,
1721 PacketPriority.CONTROL,
1722 appId);
1723
1724 // Packet comes from client
1725 packetService.requestPackets(CLIENT_SERVER_SELECTOR,
1726 PacketPriority.CONTROL,
1727 appId);
1728 }
1729
1730 /**
1731 * Process the ignore rules.
1732 *
1733 * @param deviceId the device id
1734 * @param vlanId the vlan to be ignored
1735 * @param op the operation, ADD to install; REMOVE to uninstall rules
1736 */
1737 private void processIgnoreVlanRule(DeviceId deviceId, VlanId vlanId, Objective.Operation op) {
Yi Tseng525ff402017-10-23 19:39:39 -07001738 AtomicInteger installedCount = new AtomicInteger(DHCP_SELECTORS.size());
1739 DHCP_SELECTORS.forEach(trafficSelector -> {
1740 TrafficSelector selector = DefaultTrafficSelector.builder(trafficSelector)
1741 .matchVlanId(vlanId)
1742 .build();
1743
1744 ForwardingObjective.Builder builder = DefaultForwardingObjective.builder()
1745 .withFlag(ForwardingObjective.Flag.VERSATILE)
1746 .withSelector(selector)
1747 .withPriority(IGNORE_CONTROL_PRIORITY)
Yi Tsengdbabeed2017-11-29 10:49:20 -08001748 .withTreatment(DefaultTrafficTreatment.emptyTreatment())
Yi Tseng525ff402017-10-23 19:39:39 -07001749 .fromApp(appId);
1750
1751
1752 ObjectiveContext objectiveContext = new ObjectiveContext() {
1753 @Override
1754 public void onSuccess(Objective objective) {
1755 log.info("Ignore rule {} (Vlan id {}, device {}, selector {})",
1756 op, vlanId, deviceId, selector);
1757 int countDown = installedCount.decrementAndGet();
1758 if (countDown != 0) {
1759 return;
1760 }
1761 switch (op) {
1762 case ADD:
1763 ignoredVlans.put(deviceId, vlanId);
1764 break;
1765 case REMOVE:
1766 ignoredVlans.remove(deviceId, vlanId);
1767 break;
1768 default:
1769 log.warn("Unsupported objective operation {}", op);
1770 break;
1771 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001772 }
Yi Tseng525ff402017-10-23 19:39:39 -07001773
1774 @Override
1775 public void onError(Objective objective, ObjectiveError error) {
1776 log.warn("Can't {} ignore rule (vlan id {}, selector {}, device {}) due to {}",
1777 op, vlanId, selector, deviceId, error);
Yi Tseng919b2df2017-09-07 16:22:51 -07001778 }
Yi Tseng525ff402017-10-23 19:39:39 -07001779 };
1780
1781 ForwardingObjective fwd;
1782 switch (op) {
1783 case ADD:
1784 fwd = builder.add(objectiveContext);
1785 break;
1786 case REMOVE:
1787 fwd = builder.remove(objectiveContext);
1788 break;
1789 default:
1790 log.warn("Unsupported objective operation {}", op);
1791 return;
Yi Tseng4f2a0462017-08-31 11:21:00 -07001792 }
Yi Tseng525ff402017-10-23 19:39:39 -07001793
1794 Device device = deviceService.getDevice(deviceId);
1795 if (device == null || !device.is(Pipeliner.class)) {
1796 log.warn("Device {} is not available now, wait until device is available", deviceId);
1797 return;
1798 }
1799 flowObjectiveService.apply(deviceId, fwd);
1800 });
Yi Tseng483ac6f2017-08-02 15:03:31 -07001801 }
Kalhee Kimba366062017-11-07 16:32:09 +00001802
1803 @Override
1804 public void setDhcpFpmEnabled(Boolean enabled) {
1805 // v4 does not use fpm. Do nothing.
1806 }
rsahot036620655b2018-02-26 15:01:37 -05001807 private List<DhcpServerInfo> findValidServerInfo(boolean directConnFlag) {
1808 List<DhcpServerInfo> validServerInfo;
1809
1810 if (directConnFlag || indirectServerInfoList.isEmpty()) {
1811 validServerInfo = new ArrayList<DhcpServerInfo>(defaultServerInfoList);
1812 } else {
1813 validServerInfo = new ArrayList<DhcpServerInfo>(indirectServerInfoList);
1814 }
1815 return validServerInfo;
1816 }
1817
1818
1819 private boolean checkDhcpServerConnPt(boolean directConnFlag,
1820 DhcpServerInfo serverInfo) {
1821 if (serverInfo.getDhcpServerConnectPoint() == null) {
1822 log.warn("DHCP4 server connect point for {} connPt {}",
1823 directConnFlag ? "direct" : "indirect", serverInfo.getDhcpServerConnectPoint());
1824 return false;
1825 }
1826 return true;
1827 }
1828
1829 /**
1830 * Checks if serverInfo's host info (mac and vlan) is filled in; if not, fills in.
1831 *
1832 * @param serverInfo server information
1833 * @return newServerInfo if host info can be either found or filled in.
1834 */
1835 private DhcpServerInfo getHostInfoForServerInfo(DhcpServerInfo serverInfo, List<DhcpServerInfo> sererInfoList) {
1836 DhcpServerInfo newServerInfo = null;
1837 MacAddress dhcpServerConnectMac = serverInfo.getDhcpConnectMac().orElse(null);
1838 VlanId dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1839 ConnectPoint dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1840
1841 if (dhcpServerConnectMac != null && dhcpConnectVlan != null) {
1842 newServerInfo = serverInfo;
Charles Chan2de55302018-03-02 18:27:59 -08001843 log.debug("DHCP server {} host info found. ConnectPt{} Mac {} vlan {}", serverInfo.getDhcpServerIp4(),
rsahot036620655b2018-02-26 15:01:37 -05001844 dhcpServerConnectPoint, dhcpServerConnectMac, dhcpConnectVlan);
1845 } else {
1846 log.warn("DHCP server {} not resolve yet connectPt {} mac {} vlan {}", serverInfo.getDhcpServerIp4(),
1847 dhcpServerConnectPoint, dhcpServerConnectMac, dhcpConnectVlan);
1848
1849 Ip4Address ipToProbe;
1850 if (serverInfo.getDhcpGatewayIp4().isPresent()) {
1851 ipToProbe = serverInfo.getDhcpGatewayIp4().get();
1852 } else {
1853 ipToProbe = serverInfo.getDhcpServerIp4().orElse(null);
1854 }
1855 String hostToProbe = serverInfo.getDhcpGatewayIp6()
1856 .map(ip -> "gateway").orElse("server");
1857
1858 log.warn("Dynamically probing to resolve {} IP {}", hostToProbe, ipToProbe);
1859 hostService.startMonitoringIp(ipToProbe);
1860
1861 Set<Host> hosts = hostService.getHostsByIp(ipToProbe);
1862 if (!hosts.isEmpty()) {
1863 int serverInfoIndex = sererInfoList.indexOf(serverInfo);
1864 Host host = hosts.iterator().next();
1865 serverInfo.setDhcpConnectVlan(host.vlan());
1866 serverInfo.setDhcpConnectMac(host.mac());
1867 // replace the serverInfo in the list
1868 sererInfoList.set(serverInfoIndex, serverInfo);
1869 newServerInfo = serverInfo;
1870 log.warn("Dynamically host found host {}", host);
1871 } else {
1872 log.warn("No host found host ip {} dynamically", ipToProbe);
1873 }
1874 }
1875 return newServerInfo;
1876 }
1877
1878 /**
1879 * Gets Interface facing to the server for default host.
1880 *
1881 * @param serverInfo server information
1882 * @return the Interface facing to the server; null if not found
1883 */
1884 private Interface getServerInterface(DhcpServerInfo serverInfo) {
1885 Interface serverInterface = null;
1886
1887 ConnectPoint dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1888 VlanId dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1889
1890 if (dhcpServerConnectPoint != null && dhcpConnectVlan != null) {
1891 serverInterface = interfaceService.getInterfacesByPort(dhcpServerConnectPoint)
1892 .stream()
Taras Lemkin96a0d342018-03-26 14:52:58 +00001893 .filter(iface -> Dhcp4HandlerUtil.interfaceContainsVlan(iface, dhcpConnectVlan))
rsahot036620655b2018-02-26 15:01:37 -05001894 .findFirst()
1895 .orElse(null);
1896 } else {
1897 log.warn("DHCP server {} not resolve yet connectPoint {} vlan {}", serverInfo.getDhcpServerIp6(),
1898 dhcpServerConnectPoint, dhcpConnectVlan);
1899 }
1900
1901 return serverInterface;
1902 }
1903
1904 //forward the packet to ConnectPoint where the DHCP server is attached.
1905 private void forwardPacket(InternalPacket packet) {
1906 //send Packetout to dhcp server connectpoint.
Taras Lemkin96a0d342018-03-26 14:52:58 +00001907 if (packet.getDestLocation() != null) {
rsahot036620655b2018-02-26 15:01:37 -05001908 TrafficTreatment t = DefaultTrafficTreatment.builder()
Taras Lemkin96a0d342018-03-26 14:52:58 +00001909 .setOutput(packet.getDestLocation().port()).build();
rsahot036620655b2018-02-26 15:01:37 -05001910 OutboundPacket o = new DefaultOutboundPacket(
Taras Lemkin96a0d342018-03-26 14:52:58 +00001911 packet.getDestLocation().deviceId(), t, ByteBuffer.wrap(packet.getPacket().serialize()));
rsahot036620655b2018-02-26 15:01:37 -05001912 if (log.isTraceEnabled()) {
Taras Lemkin96a0d342018-03-26 14:52:58 +00001913 log.trace("Relaying packet to destination {}", packet.getDestLocation());
rsahot036620655b2018-02-26 15:01:37 -05001914 }
Taras Lemkin96a0d342018-03-26 14:52:58 +00001915 log.debug("packetService.emit(o) to port {}", packet.getDestLocation());
rsahot036620655b2018-02-26 15:01:37 -05001916 packetService.emit(o);
1917 }
1918 }
1919
1920
1921 private DhcpServerInfo findServerInfoFromServer(boolean directConnFlag, ConnectPoint inPort) {
1922 List<DhcpServerInfo> validServerInfoList = findValidServerInfo(directConnFlag);
1923 DhcpServerInfo foundServerInfo = null;
1924 for (DhcpServerInfo serverInfo : validServerInfoList) {
1925 if (inPort.equals(serverInfo.getDhcpServerConnectPoint().get())) {
1926 foundServerInfo = serverInfo;
Charles Chan2de55302018-03-02 18:27:59 -08001927 log.debug("ServerInfo found for Rcv port {} Server Connect Point {} for {}",
rsahot036620655b2018-02-26 15:01:37 -05001928 inPort, serverInfo.getDhcpServerConnectPoint(), directConnFlag ? "direct" : "indirect");
1929 break;
1930 } else {
1931 log.warn("Rcv port {} not the same as Server Connect Point {} for {}",
1932 inPort, serverInfo.getDhcpServerConnectPoint(), directConnFlag ? "direct" : "indirect");
1933 }
1934 }
1935 return foundServerInfo;
1936 }
Yi Tseng51301292017-07-28 13:02:59 -07001937}