blob: de9b1929253fbd99fd7cdeb4912db53bf361b4a6 [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 Chan3eaa6e52018-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 Chanb8245c32018-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 Lemkin371ac5e2018-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 Lemkin371ac5e2018-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 Lemkin371ac5e2018-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 Lemkin371ac5e2018-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 Lemkin371ac5e2018-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 Chan436b8f22018-03-05 13:14:02 -0800106import java.util.concurrent.CopyOnWriteArrayList;
Jordan Halterman15e3b1e2018-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 Halterman15e3b1e2018-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 Halterman15e3b1e2018-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
123@Component
124@Service
125@Property(name = "version", value = "4")
Yi Tsengaa417a62017-09-08 17:22:51 -0700126public class Dhcp4HandlerImpl implements DhcpHandler, HostProvider {
Charles Chand988c282017-09-12 17:09:32 -0700127 public static final String DHCP_V4_RELAY_APP = "org.onosproject.Dhcp4HandlerImpl";
128 public static final ProviderId PROVIDER_ID = new ProviderId("dhcp4", DHCP_V4_RELAY_APP);
Yi Tseng525ff402017-10-23 19:39:39 -0700129 private static final String BROADCAST_IP = "255.255.255.255";
130 private static final int IGNORE_CONTROL_PRIORITY = PacketPriority.CONTROL.priorityValue() + 1000;
131
Taras Lemkin371ac5e2018-03-26 14:52:58 +0000132 private static final String LQ_ROUTE_PROPERTY_NAME = "learnRouteFromLeasequery";
133
Yi Tseng525ff402017-10-23 19:39:39 -0700134 private static final TrafficSelector CLIENT_SERVER_SELECTOR = DefaultTrafficSelector.builder()
135 .matchEthType(Ethernet.TYPE_IPV4)
136 .matchIPProtocol(IPv4.PROTOCOL_UDP)
137 .matchIPSrc(Ip4Address.ZERO.toIpPrefix())
138 .matchIPDst(Ip4Address.valueOf(BROADCAST_IP).toIpPrefix())
139 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_CLIENT_PORT))
140 .matchUdpDst(TpPort.tpPort(UDP.DHCP_SERVER_PORT))
141 .build();
142 private static final TrafficSelector SERVER_RELAY_SELECTOR = DefaultTrafficSelector.builder()
143 .matchEthType(Ethernet.TYPE_IPV4)
144 .matchIPProtocol(IPv4.PROTOCOL_UDP)
145 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_SERVER_PORT))
146 .matchUdpDst(TpPort.tpPort(UDP.DHCP_SERVER_PORT))
147 .build();
148 static final Set<TrafficSelector> DHCP_SELECTORS = ImmutableSet.of(
149 CLIENT_SERVER_SELECTOR,
150 SERVER_RELAY_SELECTOR
151 );
Yi Tseng51301292017-07-28 13:02:59 -0700152 private static Logger log = LoggerFactory.getLogger(Dhcp4HandlerImpl.class);
153
154 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
155 protected DhcpRelayStore dhcpRelayStore;
156
157 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
158 protected PacketService packetService;
159
160 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yi Tseng51301292017-07-28 13:02:59 -0700161 protected RouteStore routeStore;
162
163 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
164 protected InterfaceService interfaceService;
165
166 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
167 protected HostService hostService;
168
Yi Tsengaa417a62017-09-08 17:22:51 -0700169 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
170 protected HostProviderRegistry providerRegistry;
171
Yi Tseng525ff402017-10-23 19:39:39 -0700172 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
173 protected CoreService coreService;
174
175 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
176 protected DeviceService deviceService;
177
178 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
179 protected FlowObjectiveService flowObjectiveService;
180
Taras Lemkin371ac5e2018-03-26 14:52:58 +0000181 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
182 protected ComponentConfigService cfgService;
183
Yi Tsengaa417a62017-09-08 17:22:51 -0700184 protected HostProviderService providerService;
Yi Tseng525ff402017-10-23 19:39:39 -0700185 protected ApplicationId appId;
Charles Chanb8245c32018-03-07 17:36:06 -0800186 protected Multimap<DeviceId, VlanId> ignoredVlans = Multimaps.synchronizedMultimap(HashMultimap.create());
Yi Tseng483ac6f2017-08-02 15:03:31 -0700187 private InternalHostListener hostListener = new InternalHostListener();
188
Charles Chan436b8f22018-03-05 13:14:02 -0800189 private List<DhcpServerInfo> defaultServerInfoList = new CopyOnWriteArrayList<>();
190 private List<DhcpServerInfo> indirectServerInfoList = new CopyOnWriteArrayList<>();
Taras Lemkin371ac5e2018-03-26 14:52:58 +0000191
192 @Property(name = Dhcp4HandlerImpl.LQ_ROUTE_PROPERTY_NAME, boolValue = false,
193 label = "Enable learning routing information from LQ")
194 private Boolean learnRouteFromLeasequery = Boolean.TRUE;
Yi Tseng4f2a0462017-08-31 11:21:00 -0700195
Jordan Halterman15e3b1e2018-04-10 13:34:50 -0400196 private Executor hostEventExecutor = newSingleThreadExecutor(
197 groupedThreads("dhcp4-event-host", "%d", log));
198
Yi Tseng483ac6f2017-08-02 15:03:31 -0700199 @Activate
Taras Lemkin371ac5e2018-03-26 14:52:58 +0000200 protected void activate(ComponentContext context) {
201 cfgService.registerProperties(getClass());
202 modified(context);
Yi Tseng525ff402017-10-23 19:39:39 -0700203 appId = coreService.registerApplication(DHCP_V4_RELAY_APP);
Yi Tseng483ac6f2017-08-02 15:03:31 -0700204 hostService.addListener(hostListener);
Yi Tsengaa417a62017-09-08 17:22:51 -0700205 providerService = providerRegistry.register(this);
Yi Tseng483ac6f2017-08-02 15:03:31 -0700206 }
207
208 @Deactivate
209 protected void deactivate() {
Taras Lemkin371ac5e2018-03-26 14:52:58 +0000210 cfgService.unregisterProperties(getClass(), false);
Yi Tsengaa417a62017-09-08 17:22:51 -0700211 providerRegistry.unregister(this);
212 hostService.removeListener(hostListener);
Yi Tseng919b2df2017-09-07 16:22:51 -0700213 defaultServerInfoList.forEach(this::stopMonitoringIps);
214 defaultServerInfoList.clear();
215 indirectServerInfoList.forEach(this::stopMonitoringIps);
216 indirectServerInfoList.clear();
Yi Tseng483ac6f2017-08-02 15:03:31 -0700217 }
218
Taras Lemkin371ac5e2018-03-26 14:52:58 +0000219 @Modified
220 protected void modified(ComponentContext context) {
221 Dictionary<?, ?> properties = context.getProperties();
222 Boolean flag;
223 flag = Tools.isPropertyEnabled(properties, Dhcp4HandlerImpl.LQ_ROUTE_PROPERTY_NAME);
224 if (flag != null) {
225 learnRouteFromLeasequery = flag;
226 log.info("Learning routes from DHCP leasequery is {}",
227 learnRouteFromLeasequery ? "enabled" : "disabled");
228 }
229 }
230
Yi Tseng919b2df2017-09-07 16:22:51 -0700231 private void stopMonitoringIps(DhcpServerInfo serverInfo) {
232 serverInfo.getDhcpGatewayIp4().ifPresent(gatewayIp -> {
233 hostService.stopMonitoringIp(gatewayIp);
234 });
235 serverInfo.getDhcpServerIp4().ifPresent(serverIp -> {
236 hostService.stopMonitoringIp(serverIp);
237 });
Yi Tseng51301292017-07-28 13:02:59 -0700238 }
239
240 @Override
Yi Tseng483ac6f2017-08-02 15:03:31 -0700241 public void setDefaultDhcpServerConfigs(Collection<DhcpServerConfig> configs) {
Yi Tseng919b2df2017-09-07 16:22:51 -0700242 setDhcpServerConfigs(configs, defaultServerInfoList);
243 }
244
245 @Override
246 public void setIndirectDhcpServerConfigs(Collection<DhcpServerConfig> configs) {
247 setDhcpServerConfigs(configs, indirectServerInfoList);
248 }
249
250 @Override
251 public List<DhcpServerInfo> getDefaultDhcpServerInfoList() {
252 return defaultServerInfoList;
253 }
254
255 @Override
256 public List<DhcpServerInfo> getIndirectDhcpServerInfoList() {
257 return indirectServerInfoList;
258 }
259
Yi Tseng525ff402017-10-23 19:39:39 -0700260 @Override
261 public void updateIgnoreVlanConfig(IgnoreDhcpConfig config) {
262 if (config == null) {
263 ignoredVlans.forEach(((deviceId, vlanId) -> {
264 processIgnoreVlanRule(deviceId, vlanId, REMOVE);
265 }));
266 return;
267 }
268 config.ignoredVlans().forEach((deviceId, vlanId) -> {
269 if (ignoredVlans.get(deviceId).contains(vlanId)) {
270 // don't need to process if it already ignored
271 return;
272 }
273 processIgnoreVlanRule(deviceId, vlanId, ADD);
274 });
275
276 ignoredVlans.forEach((deviceId, vlanId) -> {
277 if (!config.ignoredVlans().get(deviceId).contains(vlanId)) {
278 // not contains in new config, remove it
279 processIgnoreVlanRule(deviceId, vlanId, REMOVE);
280 }
281 });
282 }
283
Saurav Dasfa9004b2017-12-13 16:19:35 -0800284 @Override
285 public void removeIgnoreVlanState(IgnoreDhcpConfig config) {
286 if (config == null) {
287 ignoredVlans.clear();
288 return;
289 }
290 config.ignoredVlans().forEach((deviceId, vlanId) -> {
291 ignoredVlans.remove(deviceId, vlanId);
292 });
293 }
294
Yi Tseng919b2df2017-09-07 16:22:51 -0700295 public void setDhcpServerConfigs(Collection<DhcpServerConfig> configs, List<DhcpServerInfo> serverInfoList) {
Yi Tseng483ac6f2017-08-02 15:03:31 -0700296 if (configs.size() == 0) {
297 // no config to update
298 return;
299 }
300
rsahot036b94dffc2018-02-26 15:01:37 -0500301 Boolean isConfigValid = false;
302 for (DhcpServerConfig serverConfig : configs) {
303 if (serverConfig.getDhcpServerIp4().isPresent()) {
304 isConfigValid = true;
305 break;
306 }
Yi Tseng483ac6f2017-08-02 15:03:31 -0700307 }
rsahot036b94dffc2018-02-26 15:01:37 -0500308 if (!isConfigValid) {
309 log.warn("No IP V4 server address found.");
310 return; // No IP V6 address found
311 }
312 // if (!serverInfoList.isEmpty()) {
313 for (DhcpServerInfo oldServerInfo : serverInfoList) {
314 log.info("In for (DhcpServerInfo oldServerInfo : serverInfoList) {");
Yi Tseng919b2df2017-09-07 16:22:51 -0700315 // remove old server info
rsahot036b94dffc2018-02-26 15:01:37 -0500316 //DhcpServerInfo oldServerInfo = serverInfoList.remove(0);
Yi Tseng483ac6f2017-08-02 15:03:31 -0700317
Yi Tseng919b2df2017-09-07 16:22:51 -0700318 // stop monitoring gateway or server
319 oldServerInfo.getDhcpGatewayIp4().ifPresent(gatewayIp -> {
320 hostService.stopMonitoringIp(gatewayIp);
321 });
322 oldServerInfo.getDhcpServerIp4().ifPresent(serverIp -> {
323 hostService.stopMonitoringIp(serverIp);
Yi Tseng525ff402017-10-23 19:39:39 -0700324 cancelDhcpPacket(serverIp);
Yi Tseng919b2df2017-09-07 16:22:51 -0700325 });
Yi Tseng483ac6f2017-08-02 15:03:31 -0700326 }
Yi Tseng3df7f9d2017-08-17 13:08:31 -0700327
Yi Tseng919b2df2017-09-07 16:22:51 -0700328 // Create new server info according to the config
rsahot036b94dffc2018-02-26 15:01:37 -0500329 serverInfoList.clear();
330 for (DhcpServerConfig serverConfig : configs) {
Taras Lemkin371ac5e2018-03-26 14:52:58 +0000331 log.debug("Create new server info according to the config");
rsahot036b94dffc2018-02-26 15:01:37 -0500332 DhcpServerInfo newServerInfo = new DhcpServerInfo(serverConfig,
333 DhcpServerInfo.Version.DHCP_V4);
334 checkState(newServerInfo.getDhcpServerConnectPoint().isPresent(),
335 "Connect point not exists");
336 checkState(newServerInfo.getDhcpServerIp4().isPresent(),
337 "IP of DHCP server not exists");
Yi Tseng4f2a0462017-08-31 11:21:00 -0700338
rsahot036b94dffc2018-02-26 15:01:37 -0500339 log.debug("DHCP server connect point: {}", newServerInfo.getDhcpServerConnectPoint().orElse(null));
340 log.debug("DHCP server IP: {}", newServerInfo.getDhcpServerIp4().orElse(null));
Yi Tseng919b2df2017-09-07 16:22:51 -0700341
rsahot036b94dffc2018-02-26 15:01:37 -0500342 Ip4Address serverIp = newServerInfo.getDhcpServerIp4().get();
343 Ip4Address ipToProbe;
344 if (newServerInfo.getDhcpGatewayIp4().isPresent()) {
345 ipToProbe = newServerInfo.getDhcpGatewayIp4().get();
346 } else {
347 ipToProbe = newServerInfo.getDhcpServerIp4().orElse(null);
348 }
349 log.info("Probe_IP {}", ipToProbe);
350 String hostToProbe = newServerInfo.getDhcpGatewayIp4()
351 .map(ip -> "gateway").orElse("server");
352
353 log.debug("Probing to resolve {} IP {}", hostToProbe, ipToProbe);
354 hostService.startMonitoringIp(ipToProbe);
355
356 Set<Host> hosts = hostService.getHostsByIp(ipToProbe);
357 if (!hosts.isEmpty()) {
358 Host host = hosts.iterator().next();
359 newServerInfo.setDhcpConnectVlan(host.vlan());
360 newServerInfo.setDhcpConnectMac(host.mac());
361 }
362
363 // Add new server info
364 synchronized (this) {
365 //serverInfoList.clear();
366 serverInfoList.add(newServerInfo);
367 }
368
369 requestDhcpPacket(serverIp);
Yi Tseng4f2a0462017-08-31 11:21:00 -0700370 }
Yi Tseng483ac6f2017-08-02 15:03:31 -0700371 }
372
Yi Tseng3df7f9d2017-08-17 13:08:31 -0700373 @Override
Yi Tseng51301292017-07-28 13:02:59 -0700374 public void processDhcpPacket(PacketContext context, BasePacket payload) {
375 checkNotNull(payload, "DHCP payload can't be null");
376 checkState(payload instanceof DHCP, "Payload is not a DHCP");
377 DHCP dhcpPayload = (DHCP) payload;
378 if (!configured()) {
Yi Tseng919b2df2017-09-07 16:22:51 -0700379 log.warn("Missing default DHCP relay server config. Abort packet processing");
Yi Tseng51301292017-07-28 13:02:59 -0700380 return;
381 }
382
383 ConnectPoint inPort = context.inPacket().receivedFrom();
Yi Tseng51301292017-07-28 13:02:59 -0700384 checkNotNull(dhcpPayload, "Can't find DHCP payload");
385 Ethernet packet = context.inPacket().parsed();
386 DHCP.MsgType incomingPacketType = dhcpPayload.getOptions().stream()
387 .filter(dhcpOption -> dhcpOption.getCode() == OptionCode_MessageType.getValue())
388 .map(DhcpOption::getData)
389 .map(data -> DHCP.MsgType.getType(data[0]))
390 .findFirst()
391 .orElse(null);
392 checkNotNull(incomingPacketType, "Can't get message type from DHCP payload {}", dhcpPayload);
rsahot036b94dffc2018-02-26 15:01:37 -0500393 Set<Interface> receivingInterfaces = interfaceService.getInterfacesByPort(inPort);
394 //ignore the packets if dhcp client interface is not configured on onos.
395 if (receivingInterfaces.isEmpty()) {
396 log.warn("Virtual interface is not configured on {}", inPort);
397 return;
398 }
Yi Tseng51301292017-07-28 13:02:59 -0700399 switch (incomingPacketType) {
400 case DHCPDISCOVER:
Yi Tsengdcef2c22017-08-05 20:34:06 -0700401 // Add the gateway IP as virtual interface IP for server to understand
Yi Tseng51301292017-07-28 13:02:59 -0700402 // the lease to be assigned and forward the packet to dhcp server.
rsahot036b94dffc2018-02-26 15:01:37 -0500403 List<InternalPacket> ethernetClientPacket =
404 processDhcpPacketFromClient(context, packet, receivingInterfaces);
405 for (InternalPacket internalPacket : ethernetClientPacket) {
406 log.debug("DHCPDISCOVER from {} Forward to server", inPort);
Yi Tseng51301292017-07-28 13:02:59 -0700407 writeRequestDhcpRecord(inPort, packet, dhcpPayload);
rsahot036b94dffc2018-02-26 15:01:37 -0500408 forwardPacket(internalPacket);
Yi Tseng51301292017-07-28 13:02:59 -0700409 }
410 break;
411 case DHCPOFFER:
412 //reply to dhcp client.
Taras Lemkin371ac5e2018-03-26 14:52:58 +0000413 InternalPacket ethernetPacketOffer = processDhcpPacketFromServer(context, packet);
Yi Tseng51301292017-07-28 13:02:59 -0700414 if (ethernetPacketOffer != null) {
Taras Lemkin371ac5e2018-03-26 14:52:58 +0000415 writeResponseDhcpRecord(ethernetPacketOffer.getPacket(), dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -0700416 sendResponseToClient(ethernetPacketOffer, dhcpPayload);
Yi Tseng51301292017-07-28 13:02:59 -0700417 }
418 break;
419 case DHCPREQUEST:
420 // add the gateway ip as virtual interface ip for server to understand
421 // the lease to be assigned and forward the packet to dhcp server.
rsahot036b94dffc2018-02-26 15:01:37 -0500422 List<InternalPacket> ethernetPacketRequest =
423 processDhcpPacketFromClient(context, packet, receivingInterfaces);
424 for (InternalPacket internalPacket : ethernetPacketRequest) {
425 log.debug("DHCPDISCOVER from {} Forward to server", inPort);
Yi Tseng51301292017-07-28 13:02:59 -0700426 writeRequestDhcpRecord(inPort, packet, dhcpPayload);
rsahot036b94dffc2018-02-26 15:01:37 -0500427 forwardPacket(internalPacket);
Yi Tseng51301292017-07-28 13:02:59 -0700428 }
429 break;
Charles Chand0dd7002017-10-08 23:53:36 -0400430 case DHCPDECLINE:
431 break;
Yi Tseng51301292017-07-28 13:02:59 -0700432 case DHCPACK:
433 // reply to dhcp client.
Taras Lemkin371ac5e2018-03-26 14:52:58 +0000434 InternalPacket ethernetPacketAck = processDhcpPacketFromServer(context, packet);
Yi Tseng51301292017-07-28 13:02:59 -0700435 if (ethernetPacketAck != null) {
Taras Lemkin371ac5e2018-03-26 14:52:58 +0000436 writeResponseDhcpRecord(ethernetPacketAck.getPacket(), dhcpPayload);
437 handleDhcpAck(ethernetPacketAck.getPacket(), dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -0700438 sendResponseToClient(ethernetPacketAck, dhcpPayload);
Yi Tseng51301292017-07-28 13:02:59 -0700439 }
440 break;
Charles Chand0dd7002017-10-08 23:53:36 -0400441 case DHCPNAK:
442 break;
Yi Tseng51301292017-07-28 13:02:59 -0700443 case DHCPRELEASE:
444 // TODO: release the ip address from client
445 break;
Charles Chand0dd7002017-10-08 23:53:36 -0400446 case DHCPINFORM:
447 break;
448 case DHCPFORCERENEW:
449 break;
450 case DHCPLEASEQUERY:
451 handleLeaseQueryMsg(context, packet, dhcpPayload);
452 break;
453 case DHCPLEASEACTIVE:
454 handleLeaseQueryActivateMsg(packet, dhcpPayload);
455 break;
456 case DHCPLEASEUNASSIGNED:
457 case DHCPLEASEUNKNOWN:
458 handleLeaseQueryUnknown(packet, dhcpPayload);
459 break;
Yi Tseng51301292017-07-28 13:02:59 -0700460 default:
461 break;
462 }
463 }
464
465 /**
466 * Checks if this app has been configured.
467 *
468 * @return true if all information we need have been initialized
469 */
Yi Tseng4f2a0462017-08-31 11:21:00 -0700470 private boolean configured() {
Yi Tseng919b2df2017-09-07 16:22:51 -0700471 return !defaultServerInfoList.isEmpty();
Yi Tseng51301292017-07-28 13:02:59 -0700472 }
473
474 /**
Yi Tsengdcef2c22017-08-05 20:34:06 -0700475 * Returns the first interface ip from interface.
Yi Tseng51301292017-07-28 13:02:59 -0700476 *
Yi Tsengdcef2c22017-08-05 20:34:06 -0700477 * @param iface interface of one connect point
Yi Tseng51301292017-07-28 13:02:59 -0700478 * @return the first interface IP; null if not exists an IP address in
479 * these interfaces
480 */
Yi Tseng3df7f9d2017-08-17 13:08:31 -0700481 private Ip4Address getFirstIpFromInterface(Interface iface) {
Yi Tsengdcef2c22017-08-05 20:34:06 -0700482 checkNotNull(iface, "Interface can't be null");
483 return iface.ipAddressesList().stream()
Yi Tseng51301292017-07-28 13:02:59 -0700484 .map(InterfaceIpAddress::ipAddress)
485 .filter(IpAddress::isIp4)
486 .map(IpAddress::getIp4Address)
487 .findFirst()
488 .orElse(null);
489 }
490
491 /**
Yi Tseng4f2a0462017-08-31 11:21:00 -0700492 * Gets Interface facing to the server for default host.
Yi Tsengdcef2c22017-08-05 20:34:06 -0700493 *
494 * @return the Interface facing to the server; null if not found
495 */
Yi Tseng919b2df2017-09-07 16:22:51 -0700496 private Interface getDefaultServerInterface() {
497 return getServerInterface(defaultServerInfoList);
Yi Tsengdcef2c22017-08-05 20:34:06 -0700498 }
499
500 /**
Yi Tseng4f2a0462017-08-31 11:21:00 -0700501 * Gets Interface facing to the server for indirect hosts.
502 * Use default server Interface if indirect server not configured.
503 *
504 * @return the Interface facing to the server; null if not found
505 */
506 private Interface getIndirectServerInterface() {
Yi Tseng919b2df2017-09-07 16:22:51 -0700507 return getServerInterface(indirectServerInfoList);
508 }
509
510 private Interface getServerInterface(List<DhcpServerInfo> serverInfos) {
Yi Tseng21a2dc82017-11-29 14:39:18 -0800511 return serverInfos.stream()
Yi Tseng4f2a0462017-08-31 11:21:00 -0700512 .findFirst()
Yi Tseng21a2dc82017-11-29 14:39:18 -0800513 .map(serverInfo -> {
514 ConnectPoint dhcpServerConnectPoint =
515 serverInfo.getDhcpServerConnectPoint().orElse(null);
516 VlanId dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
517 if (dhcpServerConnectPoint == null || dhcpConnectVlan == null) {
518 return null;
519 }
520 return interfaceService.getInterfacesByPort(dhcpServerConnectPoint)
521 .stream()
522 .filter(iface -> interfaceContainsVlan(iface, dhcpConnectVlan))
523 .findFirst()
524 .orElse(null);
525 })
Yi Tseng4f2a0462017-08-31 11:21:00 -0700526 .orElse(null);
527 }
528
529 /**
530 * Determind if an Interface contains a vlan id.
531 *
532 * @param iface the Interface
533 * @param vlanId the vlan id
534 * @return true if the Interface contains the vlan id
535 */
536 private boolean interfaceContainsVlan(Interface iface, VlanId vlanId) {
Yi Tseng4025a102017-09-30 11:35:42 +0800537 if (vlanId.equals(VlanId.NONE)) {
538 // untagged packet, check if vlan untagged or vlan native is not NONE
539 return !iface.vlanUntagged().equals(VlanId.NONE) ||
540 !iface.vlanNative().equals(VlanId.NONE);
541 }
542 // tagged packet, check if the interface contains the vlan
543 return iface.vlanTagged().contains(vlanId);
Yi Tseng4f2a0462017-08-31 11:21:00 -0700544 }
545
Charles Chand0dd7002017-10-08 23:53:36 -0400546 private void handleLeaseQueryActivateMsg(Ethernet packet, DHCP dhcpPayload) {
547 log.debug("LQ: Got DHCPLEASEACTIVE packet!");
548
Taras Lemkin371ac5e2018-03-26 14:52:58 +0000549 if (learnRouteFromLeasequery) {
550 // TODO: release the ip address from client
551 MacAddress clientMacAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
552 VlanId vlanId = VlanId.vlanId(packet.getVlanID());
553 HostId hostId = HostId.hostId(clientMacAddress, vlanId);
554 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
Charles Chand0dd7002017-10-08 23:53:36 -0400555
Taras Lemkin371ac5e2018-03-26 14:52:58 +0000556 if (record == null) {
557 log.warn("Can't find record for host {} when processing DHCPLEASEACTIVE", hostId);
558 return;
559 }
560
561 // need to update routes
562 log.debug("Lease Query for Client results in DHCPLEASEACTIVE - route needs to be modified");
563 // get current route
564 // find the ip of that client with the DhcpRelay store
565
566 Ip4Address clientIP = record.ip4Address().orElse(null);
567 log.debug("LQ: IP of host is " + clientIP.getIp4Address());
568
569 MacAddress nextHopMac = record.nextHop().orElse(null);
570 log.debug("LQ: MAC of resulting *OLD* NH for that host is " + nextHopMac.toString());
571
572 // find the new NH by looking at the src MAC of the dhcp request
573 // from the LQ store
574 MacAddress newNextHopMac = record.nextHopTemp().orElse(null);
575 log.debug("LQ: MAC of resulting *NEW* NH for that host is " + newNextHopMac.toString());
576
577 log.debug("LQ: updating dhcp relay record with new NH");
578 record.nextHop(newNextHopMac);
579
580 // find the next hop IP from its mac
581 HostId gwHostId = HostId.hostId(newNextHopMac, vlanId);
582 Host gwHost = hostService.getHost(gwHostId);
583
584 if (gwHost == null) {
585 log.warn("Can't find gateway for new NH host " + gwHostId);
586 return;
587 }
588
589 Ip4Address nextHopIp = gwHost.ipAddresses()
590 .stream()
591 .filter(IpAddress::isIp4)
592 .map(IpAddress::getIp4Address)
593 .findFirst()
594 .orElse(null);
595
596 if (nextHopIp == null) {
597 log.warn("Can't find IP address of gateway " + gwHost);
598 return;
599 }
600
601 log.debug("LQ: *NEW* NH IP for host is " + nextHopIp.getIp4Address());
602 Route route = new Route(Route.Source.DHCP, clientIP.toIpPrefix(), nextHopIp);
603 routeStore.updateRoute(route);
Charles Chand0dd7002017-10-08 23:53:36 -0400604 }
605
Charles Chand0dd7002017-10-08 23:53:36 -0400606 // and forward to client
Taras Lemkin371ac5e2018-03-26 14:52:58 +0000607 InternalPacket ethernetPacket = processLeaseQueryFromServer(packet);
Charles Chand0dd7002017-10-08 23:53:36 -0400608 if (ethernetPacket != null) {
609 sendResponseToClient(ethernetPacket, dhcpPayload);
610 }
611 }
612
Charles Chand0dd7002017-10-08 23:53:36 -0400613 private void handleLeaseQueryMsg(PacketContext context, Ethernet packet, DHCP dhcpPayload) {
Taras Lemkin371ac5e2018-03-26 14:52:58 +0000614 // If this flag is enabled we expect that DHCPLEASEQUERY-ies are sent from an access concentrator
615 // where queried client is connected to. Otherwise, DHCPLEASEQUERY source may be a separate connected agent
616 if (learnRouteFromLeasequery) {
617 log.debug("LQ: Got DHCPLEASEQUERY packet!");
618 MacAddress clientMacAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
619 log.debug("LQ: got DHCPLEASEQUERY with MAC " + clientMacAddress.toString());
620 // add the client mac (hostid) of this request to a store (the entry will be removed with
621 // the reply sent to the originator)
622 VlanId vlanId = VlanId.vlanId(packet.getVlanID());
623 HostId hId = HostId.hostId(clientMacAddress, vlanId);
624 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hId).orElse(null);
625 if (record != null) {
626 //new NH is to be taken from src mac of LQ packet
627 MacAddress newNextHop = packet.getSourceMAC();
628 record.nextHopTemp(newNextHop);
629 record.ip4Status(dhcpPayload.getPacketType());
630 record.updateLastSeen();
631
632 // do a basic routing of the packet (this is unicast routing
633 // not a relay operation like for other broadcast dhcp packets
634 List<InternalPacket> ethernetPacketRequest = processLeaseQueryFromAgent(context, packet);
635 // and forward to server
636 for (InternalPacket internalPacket : ethernetPacketRequest) {
637 log.debug("LeaseQueryMsg forward to server");
638 forwardPacket(internalPacket);
639 }
640 } else {
641 log.warn("LQ: Error! - DHCP relay record for that client not found - ignoring LQ!");
642 }
643 } else {
644 log.debug("LQ: Got DHCPLEASEQUERY packet!");
645
646 int giaddr = dhcpPayload.getGatewayIPAddress();
647
648 log.debug("DHCPLEASEQUERY giaddr: {} ({}). Originators connectPoint: {}", giaddr,
649 Ip4Address.valueOf(giaddr), context.inPacket().receivedFrom());
Charles Chand0dd7002017-10-08 23:53:36 -0400650
651 // do a basic routing of the packet (this is unicast routing
652 // not a relay operation like for other broadcast dhcp packets
rsahot036b94dffc2018-02-26 15:01:37 -0500653 List<InternalPacket> ethernetPacketRequest = processLeaseQueryFromAgent(context, packet);
Charles Chand0dd7002017-10-08 23:53:36 -0400654 // and forward to server
rsahot036b94dffc2018-02-26 15:01:37 -0500655 for (InternalPacket internalPacket : ethernetPacketRequest) {
Taras Lemkin371ac5e2018-03-26 14:52:58 +0000656 log.trace("LeaseQueryMsg forward to server connected to {}", internalPacket.getDestLocation());
rsahot036b94dffc2018-02-26 15:01:37 -0500657 forwardPacket(internalPacket);
658 }
Charles Chand0dd7002017-10-08 23:53:36 -0400659 }
660 }
661
662 private void handleLeaseQueryUnknown(Ethernet packet, DHCP dhcpPayload) {
663 log.debug("Lease Query for Client results in DHCPLEASEUNASSIGNED or " +
664 "DHCPLEASEUNKNOWN - removing route & forwarding reply to originator");
Taras Lemkin371ac5e2018-03-26 14:52:58 +0000665 if (learnRouteFromLeasequery) {
666 MacAddress clientMacAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
667 VlanId vlanId = VlanId.vlanId(packet.getVlanID());
668 HostId hostId = HostId.hostId(clientMacAddress, vlanId);
669 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
Charles Chand0dd7002017-10-08 23:53:36 -0400670
Taras Lemkin371ac5e2018-03-26 14:52:58 +0000671 if (record == null) {
672 log.warn("Can't find record for host {} when handling LQ UNKNOWN/UNASSIGNED message", hostId);
673 return;
674 }
675
676 Ip4Address clientIP = record.ip4Address().orElse(null);
677 log.debug("LQ: IP of host is " + clientIP.getIp4Address());
678
679 // find the new NH by looking at the src MAC of the dhcp request
680 // from the LQ store
681 MacAddress nextHopMac = record.nextHop().orElse(null);
682 log.debug("LQ: MAC of resulting *Existing* NH for that route is " + nextHopMac.toString());
683
684 // find the next hop IP from its mac
685 HostId gwHostId = HostId.hostId(nextHopMac, vlanId);
686 Host gwHost = hostService.getHost(gwHostId);
687
688 if (gwHost == null) {
689 log.warn("Can't find gateway for new NH host " + gwHostId);
690 return;
691 }
692
693 Ip4Address nextHopIp = gwHost.ipAddresses()
694 .stream()
695 .filter(IpAddress::isIp4)
696 .map(IpAddress::getIp4Address)
697 .findFirst()
698 .orElse(null);
699
700 if (nextHopIp == null) {
701 log.warn("Can't find IP address of gateway {}", gwHost);
702 return;
703 }
704
705 log.debug("LQ: *Existing* NH IP for host is " + nextHopIp.getIp4Address() + " removing route for it");
706 Route route = new Route(Route.Source.DHCP, clientIP.toIpPrefix(), nextHopIp);
707 routeStore.removeRoute(route);
708
709 // remove from temp store
710 dhcpRelayStore.removeDhcpRecord(hostId);
Charles Chand0dd7002017-10-08 23:53:36 -0400711 }
Charles Chand0dd7002017-10-08 23:53:36 -0400712 // and forward to client
Taras Lemkin371ac5e2018-03-26 14:52:58 +0000713 InternalPacket ethernetPacket = processLeaseQueryFromServer(packet);
Charles Chand0dd7002017-10-08 23:53:36 -0400714 if (ethernetPacket != null) {
715 sendResponseToClient(ethernetPacket, dhcpPayload);
716 }
717 }
718
Yi Tseng4f2a0462017-08-31 11:21:00 -0700719 /**
Yi Tseng51301292017-07-28 13:02:59 -0700720 * Build the DHCP discover/request packet with gateway IP(unicast packet).
721 *
722 * @param context the packet context
723 * @param ethernetPacket the ethernet payload to process
Yi Tseng51301292017-07-28 13:02:59 -0700724 * @return processed packet
725 */
rsahot036b94dffc2018-02-26 15:01:37 -0500726 private List<InternalPacket> processDhcpPacketFromClient(PacketContext context,
727 Ethernet ethernetPacket,
728 Set<Interface> clientInterfaces) {
Yi Tseng25bfe372017-11-03 16:27:32 -0700729 ConnectPoint receivedFrom = context.inPacket().receivedFrom();
730 DeviceId receivedFromDevice = receivedFrom.deviceId();
rsahot036b94dffc2018-02-26 15:01:37 -0500731 Ip4Address relayAgentIp = null;
Taras Lemkin371ac5e2018-03-26 14:52:58 +0000732 relayAgentIp = Dhcp4HandlerUtil.getRelayAgentIPv4Address(clientInterfaces);
rsahot036b94dffc2018-02-26 15:01:37 -0500733 MacAddress relayAgentMac = clientInterfaces.iterator().next().mac();
734 if (relayAgentIp == null || relayAgentMac == null) {
735 log.warn("Missing DHCP relay agent interface Ipv4 addr config for "
736 + "packet from client on port: {}. Aborting packet processing",
737 clientInterfaces.iterator().next().connectPoint());
Charles Chan3eaa6e52018-03-30 12:11:34 -0700738 return Lists.newArrayList();
rsahot036b94dffc2018-02-26 15:01:37 -0500739 }
740 log.debug("Multi DHCP V4 processDhcpPacketFromClient on port {}",
741 clientInterfaces.iterator().next().connectPoint());
Yi Tseng25bfe372017-11-03 16:27:32 -0700742
Yi Tseng4f2a0462017-08-31 11:21:00 -0700743 // get dhcp header.
rsahot036b94dffc2018-02-26 15:01:37 -0500744 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
Yi Tseng4f2a0462017-08-31 11:21:00 -0700745 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
746 UDP udpPacket = (UDP) ipv4Packet.getPayload();
747 DHCP dhcpPacket = (DHCP) udpPacket.getPayload();
748
Yi Tseng919b2df2017-09-07 16:22:51 -0700749
Yi Tsengdcef2c22017-08-05 20:34:06 -0700750 Ip4Address clientInterfaceIp =
751 interfaceService.getInterfacesByPort(context.inPacket().receivedFrom())
752 .stream()
753 .map(Interface::ipAddressesList)
754 .flatMap(Collection::stream)
755 .map(InterfaceIpAddress::ipAddress)
756 .filter(IpAddress::isIp4)
757 .map(IpAddress::getIp4Address)
758 .findFirst()
759 .orElse(null);
760 if (clientInterfaceIp == null) {
761 log.warn("Can't find interface IP for client interface for port {}",
rsahot036b94dffc2018-02-26 15:01:37 -0500762 context.inPacket().receivedFrom());
Charles Chan3eaa6e52018-03-30 12:11:34 -0700763 return Lists.newArrayList();
Yi Tsengdcef2c22017-08-05 20:34:06 -0700764 }
rsahot036b94dffc2018-02-26 15:01:37 -0500765
Yi Tseng4f2a0462017-08-31 11:21:00 -0700766 boolean isDirectlyConnected = directlyConnected(dhcpPacket);
rsahot036b94dffc2018-02-26 15:01:37 -0500767 boolean directConnFlag = directlyConnected(dhcpPacket);
768
769 // Multi DHCP Start
770 ConnectPoint clientConnectionPoint = context.inPacket().receivedFrom();
771 VlanId vlanIdInUse = VlanId.vlanId(ethernetPacket.getVlanID());
772 Interface clientInterface = interfaceService.getInterfacesByPort(clientConnectionPoint)
Taras Lemkin371ac5e2018-03-26 14:52:58 +0000773 .stream().filter(iface -> Dhcp4HandlerUtil.interfaceContainsVlan(iface, vlanIdInUse))
rsahot036b94dffc2018-02-26 15:01:37 -0500774 .findFirst()
775 .orElse(null);
776
777 List<InternalPacket> internalPackets = new ArrayList<>();
778 List<DhcpServerInfo> serverInfoList = findValidServerInfo(directConnFlag);
779 List<DhcpServerInfo> copyServerInfoList = new ArrayList<DhcpServerInfo>(serverInfoList);
780
781
782 for (DhcpServerInfo serverInfo : copyServerInfoList) {
783 etherReply = (Ethernet) ethernetPacket.clone();
Taras Lemkin371ac5e2018-03-26 14:52:58 +0000784 ipv4Packet = (IPv4) etherReply.getPayload();
785 udpPacket = (UDP) ipv4Packet.getPayload();
786 dhcpPacket = (DHCP) udpPacket.getPayload();
rsahot036b94dffc2018-02-26 15:01:37 -0500787 if (!checkDhcpServerConnPt(directConnFlag, serverInfo)) {
788 log.warn("Can't get server connect point, ignore");
789 continue;
790 }
791 DhcpServerInfo newServerInfo = getHostInfoForServerInfo(serverInfo, serverInfoList);
792 if (newServerInfo == null) {
793 log.warn("Can't get server interface with host info resolved, ignore");
794 continue;
795 }
796
797 Interface serverInterface = getServerInterface(newServerInfo);
Yi Tseng21a2dc82017-11-29 14:39:18 -0800798 if (serverInterface == null) {
rsahot036b94dffc2018-02-26 15:01:37 -0500799 log.warn("Can't get server interface, ignore");
800 continue;
Yi Tseng21a2dc82017-11-29 14:39:18 -0800801 }
Yi Tseng4f2a0462017-08-31 11:21:00 -0700802
rsahot036b94dffc2018-02-26 15:01:37 -0500803 Ip4Address ipFacingServer = getFirstIpFromInterface(serverInterface);
804 MacAddress macFacingServer = serverInterface.mac();
805 log.debug("Interfacing server {} Mac : {} ", ipFacingServer, macFacingServer);
806 if (ipFacingServer == null || macFacingServer == null) {
807 log.warn("No IP address for server Interface {}", serverInterface);
rsahot036b94dffc2018-02-26 15:01:37 -0500808 continue;
809 }
Yi Tseng51301292017-07-28 13:02:59 -0700810
Charles Chand0d1e332017-10-10 16:53:32 -0400811
rsahot036b94dffc2018-02-26 15:01:37 -0500812 etherReply.setSourceMACAddress(macFacingServer);
813 // set default info and replace with indirect if available later on.
814 if (newServerInfo.getDhcpConnectMac().isPresent()) {
815 etherReply.setDestinationMACAddress(newServerInfo.getDhcpConnectMac().get());
816 }
817 if (newServerInfo.getDhcpConnectVlan().isPresent()) {
818 etherReply.setVlanID(newServerInfo.getDhcpConnectVlan().get().toShort());
819 }
820 ipv4Packet.setSourceAddress(ipFacingServer.toInt());
821 ipv4Packet.setDestinationAddress(newServerInfo.getDhcpServerIp4().get().toInt());
Charles Chan0363d052018-03-02 18:27:59 -0800822 log.debug("Directly connected {}", isDirectlyConnected);
823 log.debug("DHCP server IP: {}", newServerInfo.getDhcpServerIp4().get());
rsahot036b94dffc2018-02-26 15:01:37 -0500824 if (isDirectlyConnected) {
Yi Tseng51301292017-07-28 13:02:59 -0700825
Charles Chan0363d052018-03-02 18:27:59 -0800826 log.debug("Default DHCP server IP: {}", newServerInfo.getDhcpServerIp4().get());
rsahot036b94dffc2018-02-26 15:01:37 -0500827 if (newServerInfo.getDhcpConnectMac().isPresent()) {
828 etherReply.setDestinationMACAddress(newServerInfo.getDhcpConnectMac().get());
Charles Chand0d1e332017-10-10 16:53:32 -0400829 }
rsahot036b94dffc2018-02-26 15:01:37 -0500830 if (newServerInfo.getDhcpConnectVlan().isPresent()) {
831 etherReply.setVlanID(newServerInfo.getDhcpConnectVlan().get().toShort());
832 }
833
834 ipv4Packet.setDestinationAddress(newServerInfo.getDhcpServerIp4().get().toInt());
835
836
837 ConnectPoint inPort = context.inPacket().receivedFrom();
838 VlanId vlanId = VlanId.vlanId(ethernetPacket.getVlanID());
839 // add connected in port and vlan
840 CircuitId cid = new CircuitId(inPort.toString(), vlanId);
841 byte[] circuitId = cid.serialize();
842 DhcpOption circuitIdSubOpt = new DhcpOption();
843 circuitIdSubOpt
844 .setCode(CIRCUIT_ID.getValue())
845 .setLength((byte) circuitId.length)
846 .setData(circuitId);
847
848 DhcpRelayAgentOption newRelayAgentOpt = new DhcpRelayAgentOption();
849 newRelayAgentOpt.setCode(OptionCode_CircuitID.getValue());
850 newRelayAgentOpt.addSubOption(circuitIdSubOpt);
851
852 // Removes END option first
853 List<DhcpOption> options = dhcpPacket.getOptions().stream()
854 .filter(opt -> opt.getCode() != OptionCode_END.getValue())
855 .collect(Collectors.toList());
856
857 // push relay agent option
858 options.add(newRelayAgentOpt);
859
860 // make sure option 255(End) is the last option
861 DhcpOption endOption = new DhcpOption();
862 endOption.setCode(OptionCode_END.getValue());
863 options.add(endOption);
864
865 dhcpPacket.setOptions(options);
866
867 relayAgentIp = serverInfo.getRelayAgentIp4(receivedFromDevice).orElse(null);
868
869 // Sets relay agent IP
870 int effectiveRelayAgentIp = relayAgentIp != null ?
871 relayAgentIp.toInt() : clientInterfaceIp.toInt();
872 dhcpPacket.setGatewayIPAddress(effectiveRelayAgentIp);
Charles Chan0363d052018-03-02 18:27:59 -0800873 log.debug("In Default, Relay Agent IP {}", effectiveRelayAgentIp);
Charles Chand0d1e332017-10-10 16:53:32 -0400874 } else {
rsahot036b94dffc2018-02-26 15:01:37 -0500875 if (!newServerInfo.getDhcpServerIp4().isPresent()) {
876 // do nothing
877 } else if (!newServerInfo.getDhcpConnectMac().isPresent()) {
878 continue;
879 } else {
880 relayAgentIp = newServerInfo.getRelayAgentIp4(receivedFromDevice).orElse(null);
881 // Sets relay agent IP
882 int effectiveRelayAgentIp = relayAgentIp != null ?
883 relayAgentIp.toInt() : clientInterfaceIp.toInt();
Mayank Tiwari9ff32f02018-10-19 12:12:44 -0400884 Ip4Address effectiveRealRealyAgentIP = relayAgentIp != null ?
885 relayAgentIp : clientInterfaceIp;
rsahot036b94dffc2018-02-26 15:01:37 -0500886 dhcpPacket.setGatewayIPAddress(effectiveRelayAgentIp);
Mayank Tiwari9ff32f02018-10-19 12:12:44 -0400887 ipv4Packet.setSourceAddress(effectiveRealRealyAgentIP.toInt());
888 log.debug("Source IP address set as relay agent IP with value: {}", effectiveRealRealyAgentIP);
Charles Chand0d1e332017-10-10 16:53:32 -0400889 }
Yi Tseng4f2a0462017-08-31 11:21:00 -0700890 }
Yi Tseng3df7f9d2017-08-17 13:08:31 -0700891
rsahot036b94dffc2018-02-26 15:01:37 -0500892 // Remove broadcast flag
893 dhcpPacket.setFlags((short) 0);
894
895 udpPacket.setPayload(dhcpPacket);
896 // As a DHCP relay, the source port should be server port( instead
897 // of client port.
898 udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
899 udpPacket.setDestinationPort(UDP.DHCP_SERVER_PORT);
900 ipv4Packet.setPayload(udpPacket);
901 ipv4Packet.setTtl((byte) 64);
902 etherReply.setPayload(ipv4Packet);
Taras Lemkin371ac5e2018-03-26 14:52:58 +0000903 InternalPacket internalPacket = InternalPacket.internalPacket(etherReply,
rsahot036b94dffc2018-02-26 15:01:37 -0500904 serverInfo.getDhcpServerConnectPoint().get());
Taras Lemkin371ac5e2018-03-26 14:52:58 +0000905
rsahot036b94dffc2018-02-26 15:01:37 -0500906 internalPackets.add(internalPacket);
907 }
908 return internalPackets;
Yi Tseng51301292017-07-28 13:02:59 -0700909 }
910
Charles Chand0dd7002017-10-08 23:53:36 -0400911
912 /**
913 * Do a basic routing for a packet from client (used for LQ processing).
914 *
915 * @param context the packet context
916 * @param ethernetPacket the ethernet payload to process
917 * @return processed packet
918 */
rsahot036b94dffc2018-02-26 15:01:37 -0500919 private List<InternalPacket> processLeaseQueryFromAgent(PacketContext context,
920 Ethernet ethernetPacket) {
921 ConnectPoint receivedFrom = context.inPacket().receivedFrom();
922 DeviceId receivedFromDevice = receivedFrom.deviceId();
923
Charles Chand0dd7002017-10-08 23:53:36 -0400924 // get dhcp header.
925 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
926 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
927 UDP udpPacket = (UDP) ipv4Packet.getPayload();
928 DHCP dhcpPacket = (DHCP) udpPacket.getPayload();
929
Charles Chan0363d052018-03-02 18:27:59 -0800930 Ip4Address relayAgentIp;
Charles Chand0dd7002017-10-08 23:53:36 -0400931
Charles Chand0dd7002017-10-08 23:53:36 -0400932 Ip4Address clientInterfaceIp =
933 interfaceService.getInterfacesByPort(context.inPacket().receivedFrom())
934 .stream()
935 .map(Interface::ipAddressesList)
936 .flatMap(Collection::stream)
937 .map(InterfaceIpAddress::ipAddress)
938 .filter(IpAddress::isIp4)
939 .map(IpAddress::getIp4Address)
940 .findFirst()
941 .orElse(null);
942 if (clientInterfaceIp == null) {
943 log.warn("Can't find interface IP for client interface for port {}",
rsahot036b94dffc2018-02-26 15:01:37 -0500944 context.inPacket().receivedFrom());
Charles Chand0dd7002017-10-08 23:53:36 -0400945 return null;
946 }
rsahot036b94dffc2018-02-26 15:01:37 -0500947
Charles Chand0dd7002017-10-08 23:53:36 -0400948 boolean isDirectlyConnected = directlyConnected(dhcpPacket);
rsahot036b94dffc2018-02-26 15:01:37 -0500949 boolean directConnFlag = directlyConnected(dhcpPacket);
950
951 // Multi DHCP Start
rsahot036b94dffc2018-02-26 15:01:37 -0500952 List<InternalPacket> internalPackets = new ArrayList<>();
953 List<DhcpServerInfo> serverInfoList = findValidServerInfo(directConnFlag);
Charles Chan0363d052018-03-02 18:27:59 -0800954 List<DhcpServerInfo> copyServerInfoList = new ArrayList<>(serverInfoList);
rsahot036b94dffc2018-02-26 15:01:37 -0500955
956 for (DhcpServerInfo serverInfo : copyServerInfoList) {
957 // get dhcp header.
958 etherReply = (Ethernet) ethernetPacket.clone();
959 ipv4Packet = (IPv4) etherReply.getPayload();
960 udpPacket = (UDP) ipv4Packet.getPayload();
961 dhcpPacket = (DHCP) udpPacket.getPayload();
962
963 if (!checkDhcpServerConnPt(directConnFlag, serverInfo)) {
964 log.warn("Can't get server connect point, ignore");
965 continue;
Yi Tseng21a2dc82017-11-29 14:39:18 -0800966 }
rsahot036b94dffc2018-02-26 15:01:37 -0500967 DhcpServerInfo newServerInfo = getHostInfoForServerInfo(serverInfo, serverInfoList);
968 if (newServerInfo == null) {
969 log.warn("Can't get server interface with host info resolved, ignore");
970 continue;
971 }
Charles Chand0dd7002017-10-08 23:53:36 -0400972
rsahot036b94dffc2018-02-26 15:01:37 -0500973 Interface serverInterface = getServerInterface(newServerInfo);
974 if (serverInterface == null) {
975 log.warn("Can't get server interface, ignore");
976 continue;
977 }
978 Ip4Address ipFacingServer = getFirstIpFromInterface(serverInterface);
979 MacAddress macFacingServer = serverInterface.mac();
980 if (ipFacingServer == null || macFacingServer == null) {
981 log.warn("No IP address for server Interface {}", serverInterface);
982 continue;
983 }
Charles Chand0dd7002017-10-08 23:53:36 -0400984
rsahot036b94dffc2018-02-26 15:01:37 -0500985 etherReply.setSourceMACAddress(macFacingServer);
Charles Chan0363d052018-03-02 18:27:59 -0800986 etherReply.setDestinationMACAddress(newServerInfo.getDhcpConnectMac().get());
987 etherReply.setVlanID(newServerInfo.getDhcpConnectVlan().get().toShort());
rsahot036b94dffc2018-02-26 15:01:37 -0500988 ipv4Packet.setSourceAddress(ipFacingServer.toInt());
Charles Chan0363d052018-03-02 18:27:59 -0800989 ipv4Packet.setDestinationAddress(newServerInfo.getDhcpServerIp4().get().toInt());
rsahot036b94dffc2018-02-26 15:01:37 -0500990 if (isDirectlyConnected) {
991 // set default info and replace with indirect if available later on.
992 if (newServerInfo.getDhcpConnectMac().isPresent()) {
993 etherReply.setDestinationMACAddress(newServerInfo.getDhcpConnectMac().get());
994 }
995 if (newServerInfo.getDhcpConnectVlan().isPresent()) {
996 etherReply.setVlanID(serverInfo.getDhcpConnectVlan().get().toShort());
997 }
Taras Lemkin371ac5e2018-03-26 14:52:58 +0000998 if (learnRouteFromLeasequery) {
rsahot036b94dffc2018-02-26 15:01:37 -0500999 relayAgentIp = newServerInfo.getRelayAgentIp4(receivedFromDevice).orElse(null);
1000 // Sets relay agent IP
1001 int effectiveRelayAgentIp = relayAgentIp != null ?
1002 relayAgentIp.toInt() : clientInterfaceIp.toInt();
1003 dhcpPacket.setGatewayIPAddress(effectiveRelayAgentIp);
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001004 }
1005 } else {
1006 if (!newServerInfo.getDhcpServerIp4().isPresent()) {
1007 //do nothing
1008 } else if (!newServerInfo.getDhcpConnectMac().isPresent()) {
1009 continue;
1010 } else if (learnRouteFromLeasequery) {
1011 relayAgentIp = newServerInfo.getRelayAgentIp4(receivedFromDevice).orElse(null);
1012 // Sets relay agent IP
1013 int effectiveRelayAgentIp = relayAgentIp != null ?
1014 relayAgentIp.toInt() : clientInterfaceIp.toInt();
rsahot036b94dffc2018-02-26 15:01:37 -05001015 dhcpPacket.setGatewayIPAddress(effectiveRelayAgentIp);
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001016 log.debug("Relay Agent IP {}", relayAgentIp);
rsahot036b94dffc2018-02-26 15:01:37 -05001017 }
1018
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001019 log.trace("Indirect");
rsahot036b94dffc2018-02-26 15:01:37 -05001020 }
1021
1022 // Remove broadcast flag
1023 dhcpPacket.setFlags((short) 0);
1024
1025 udpPacket.setPayload(dhcpPacket);
1026 // As a DHCP relay, the source port should be server port( instead
1027 // of client port.
1028 udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
1029 udpPacket.setDestinationPort(UDP.DHCP_SERVER_PORT);
1030 ipv4Packet.setPayload(udpPacket);
1031 ipv4Packet.setTtl((byte) 64);
1032 etherReply.setPayload(ipv4Packet);
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001033 udpPacket.resetChecksum();
rsahot036b94dffc2018-02-26 15:01:37 -05001034 ////return etherReply;
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001035 InternalPacket internalPacket = InternalPacket.internalPacket(etherReply,
rsahot036b94dffc2018-02-26 15:01:37 -05001036 newServerInfo.getDhcpServerConnectPoint().get());
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001037
rsahot036b94dffc2018-02-26 15:01:37 -05001038 internalPackets.add(internalPacket);
Charles Chand0dd7002017-10-08 23:53:36 -04001039 }
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001040 log.debug("num of processLeaseQueryFromAgent packets to send is: {}", internalPackets.size());
Charles Chand0dd7002017-10-08 23:53:36 -04001041
rsahot036b94dffc2018-02-26 15:01:37 -05001042 return internalPackets;
Charles Chand0dd7002017-10-08 23:53:36 -04001043 }
1044
1045
Yi Tseng51301292017-07-28 13:02:59 -07001046 /**
1047 * Writes DHCP record to the store according to the request DHCP packet (Discover, Request).
1048 *
1049 * @param location the location which DHCP packet comes from
1050 * @param ethernet the DHCP packet
1051 * @param dhcpPayload the DHCP payload
1052 */
1053 private void writeRequestDhcpRecord(ConnectPoint location,
1054 Ethernet ethernet,
1055 DHCP dhcpPayload) {
1056 VlanId vlanId = VlanId.vlanId(ethernet.getVlanID());
1057 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
1058 HostId hostId = HostId.hostId(macAddress, vlanId);
1059 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1060 if (record == null) {
1061 record = new DhcpRecord(HostId.hostId(macAddress, vlanId));
1062 } else {
1063 record = record.clone();
1064 }
1065 record.addLocation(new HostLocation(location, System.currentTimeMillis()));
1066 record.ip4Status(dhcpPayload.getPacketType());
1067 record.setDirectlyConnected(directlyConnected(dhcpPayload));
1068 if (!directlyConnected(dhcpPayload)) {
1069 // Update gateway mac address if the host is not directly connected
1070 record.nextHop(ethernet.getSourceMAC());
1071 }
1072 record.updateLastSeen();
1073 dhcpRelayStore.updateDhcpRecord(HostId.hostId(macAddress, vlanId), record);
1074 }
1075
1076 /**
1077 * Writes DHCP record to the store according to the response DHCP packet (Offer, Ack).
1078 *
1079 * @param ethernet the DHCP packet
1080 * @param dhcpPayload the DHCP payload
1081 */
1082 private void writeResponseDhcpRecord(Ethernet ethernet,
1083 DHCP dhcpPayload) {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001084 Optional<Interface> outInterface = getClientInterface(ethernet, dhcpPayload);
Yi Tseng51301292017-07-28 13:02:59 -07001085 if (!outInterface.isPresent()) {
1086 log.warn("Failed to determine where to send {}", dhcpPayload.getPacketType());
1087 return;
1088 }
1089
1090 Interface outIface = outInterface.get();
1091 ConnectPoint location = outIface.connectPoint();
Yi Tseng4f2a0462017-08-31 11:21:00 -07001092 VlanId vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -07001093 if (vlanId == null) {
1094 vlanId = outIface.vlan();
1095 }
Yi Tseng51301292017-07-28 13:02:59 -07001096 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
1097 HostId hostId = HostId.hostId(macAddress, vlanId);
1098 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1099 if (record == null) {
1100 record = new DhcpRecord(HostId.hostId(macAddress, vlanId));
1101 } else {
1102 record = record.clone();
1103 }
1104 record.addLocation(new HostLocation(location, System.currentTimeMillis()));
1105 if (dhcpPayload.getPacketType() == DHCP.MsgType.DHCPACK) {
1106 record.ip4Address(Ip4Address.valueOf(dhcpPayload.getYourIPAddress()));
1107 }
1108 record.ip4Status(dhcpPayload.getPacketType());
1109 record.setDirectlyConnected(directlyConnected(dhcpPayload));
1110 record.updateLastSeen();
1111 dhcpRelayStore.updateDhcpRecord(HostId.hostId(macAddress, vlanId), record);
1112 }
1113
1114 /**
1115 * Build the DHCP offer/ack with proper client port.
1116 *
1117 * @param ethernetPacket the original packet comes from server
1118 * @return new packet which will send to the client
1119 */
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001120 private InternalPacket processDhcpPacketFromServer(PacketContext context, Ethernet ethernetPacket) {
Yi Tseng51301292017-07-28 13:02:59 -07001121 // get dhcp header.
rsahot036b94dffc2018-02-26 15:01:37 -05001122 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
Yi Tseng51301292017-07-28 13:02:59 -07001123 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
1124 UDP udpPacket = (UDP) ipv4Packet.getPayload();
1125 DHCP dhcpPayload = (DHCP) udpPacket.getPayload();
1126
1127 // determine the vlanId of the client host - note that this vlan id
1128 // could be different from the vlan in the packet from the server
Yi Tsengdcef2c22017-08-05 20:34:06 -07001129 Interface clientInterface = getClientInterface(ethernetPacket, dhcpPayload).orElse(null);
Yi Tseng51301292017-07-28 13:02:59 -07001130
Yi Tsengdcef2c22017-08-05 20:34:06 -07001131 if (clientInterface == null) {
Yi Tseng51301292017-07-28 13:02:59 -07001132 log.warn("Cannot find the interface for the DHCP {}", dhcpPayload);
1133 return null;
1134 }
Yi Tsengdcef2c22017-08-05 20:34:06 -07001135 VlanId vlanId;
rsahot036b94dffc2018-02-26 15:01:37 -05001136 ConnectPoint inPort = context.inPacket().receivedFrom();
1137 boolean directConnFlag = directlyConnected(dhcpPayload);
1138 DhcpServerInfo foundServerInfo = findServerInfoFromServer(directConnFlag, inPort);
1139
1140 if (foundServerInfo == null) {
jayakumarthazhath1d6b7db2018-09-25 15:56:51 -04001141 log.warn("Cannot find server info for {} server, inPort {}",
1142 directConnFlag ? "direct" : "indirect", inPort);
rsahot036b94dffc2018-02-26 15:01:37 -05001143 return null;
1144 } else {
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001145 if (Dhcp4HandlerUtil.isServerIpEmpty(foundServerInfo)) {
rsahot036b94dffc2018-02-26 15:01:37 -05001146 log.warn("Cannot find server info's ipaddress");
1147 return null;
1148 }
1149 }
Yi Tsengdcef2c22017-08-05 20:34:06 -07001150 if (clientInterface.vlanTagged().isEmpty()) {
1151 vlanId = clientInterface.vlan();
1152 } else {
1153 // might be multiple vlan in same interface
Yi Tseng4f2a0462017-08-31 11:21:00 -07001154 vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -07001155 }
1156 if (vlanId == null) {
1157 vlanId = VlanId.NONE;
1158 }
1159 etherReply.setVlanID(vlanId.toShort());
1160 etherReply.setSourceMACAddress(clientInterface.mac());
Yi Tseng51301292017-07-28 13:02:59 -07001161
Yi Tsengdcef2c22017-08-05 20:34:06 -07001162 if (!directlyConnected(dhcpPayload)) {
1163 // if client is indirectly connected, try use next hop mac address
1164 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
1165 HostId hostId = HostId.hostId(macAddress, vlanId);
Daniel Ginsburg6aee8512018-01-29 11:40:22 -08001166 if (((int) dhcpPayload.getFlags() & 0x8000) == 0x0000) {
1167 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1168 if (record != null) {
1169 // if next hop can be found, use mac address of next hop
1170 record.nextHop().ifPresent(etherReply::setDestinationMACAddress);
1171 } else {
1172 // otherwise, discard the packet
1173 log.warn("Can't find record for host id {}, discard packet", hostId);
1174 return null;
1175 }
Yi Tsengdcef2c22017-08-05 20:34:06 -07001176 } else {
Daniel Ginsburg6aee8512018-01-29 11:40:22 -08001177 etherReply.setDestinationMACAddress(MacAddress.BROADCAST);
Yi Tsengdcef2c22017-08-05 20:34:06 -07001178 }
Yi Tseng1696f562017-08-17 17:43:38 -07001179 } else {
1180 etherReply.setDestinationMACAddress(dhcpPayload.getClientHardwareAddress());
Yi Tsengdcef2c22017-08-05 20:34:06 -07001181 }
1182
Yi Tseng3df7f9d2017-08-17 13:08:31 -07001183 Ip4Address ipFacingClient = getFirstIpFromInterface(clientInterface);
Mayank Tiwari05092822018-11-14 15:41:40 -05001184 if (directlyConnected(dhcpPayload)) {
1185 // we leave the srcMac from the original packet
1186 // figure out the relay agent IP corresponding to the original request
1187 if (ipFacingClient == null) {
1188 log.warn("Cannot determine relay agent interface Ipv4 addr for host {}/{}. "
1189 + "Aborting relay for dhcp packet from server {}",
1190 etherReply.getDestinationMAC(), clientInterface.vlan(),
1191 ethernetPacket);
1192 return null;
1193 }
1194 // SRC_IP: IP facing client
1195 ipv4Packet.setSourceAddress(ipFacingClient.toInt());
1196 } else {
1197 // Get the IP address of the relay agent
1198 Ip4Address relayAgentIp = foundServerInfo
1199 .getRelayAgentIp4(clientInterface.connectPoint().deviceId()).orElse(null);
1200 if (relayAgentIp == null) {
1201 if (ipFacingClient == null) {
1202 log.warn("Cannot determine relay agent interface Ipv4 addr for host {}/{}. "
1203 + "Aborting relay for dhcp packet from server for indirect host {}",
1204 etherReply.getDestinationMAC(), clientInterface.vlan(),
1205 ethernetPacket);
1206 return null;
1207 } else {
1208 // SRC_IP: IP facing client
1209 ipv4Packet.setSourceAddress(ipFacingClient.toInt());
1210 }
1211 } else {
1212 // SRC_IP: relay agent IP
1213 ipv4Packet.setSourceAddress(relayAgentIp.toInt());
1214 }
Yi Tseng51301292017-07-28 13:02:59 -07001215 }
Yi Tseng51301292017-07-28 13:02:59 -07001216 // DST_IP: offered IP
Daniel Ginsburg6aee8512018-01-29 11:40:22 -08001217 if (((int) dhcpPayload.getFlags() & 0x8000) == 0x0000) {
1218 ipv4Packet.setDestinationAddress(dhcpPayload.getYourIPAddress());
1219 } else {
1220 ipv4Packet.setDestinationAddress(BROADCAST_IP);
1221 }
Yi Tseng51301292017-07-28 13:02:59 -07001222 udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
1223 if (directlyConnected(dhcpPayload)) {
1224 udpPacket.setDestinationPort(UDP.DHCP_CLIENT_PORT);
1225 } else {
1226 // forward to another dhcp relay
Yi Tseng93ba53c2017-09-14 13:24:21 -07001227 // FIXME: Currently we assume the DHCP comes from a L2 relay with
1228 // Option 82, this might not work if DHCP message comes from
1229 // L3 relay.
1230 udpPacket.setDestinationPort(UDP.DHCP_CLIENT_PORT);
Yi Tseng51301292017-07-28 13:02:59 -07001231 }
1232
1233 udpPacket.setPayload(dhcpPayload);
1234 ipv4Packet.setPayload(udpPacket);
1235 etherReply.setPayload(ipv4Packet);
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001236 return InternalPacket.internalPacket(etherReply, clientInterface.connectPoint());
Yi Tseng51301292017-07-28 13:02:59 -07001237 }
1238
Yi Tsengdcef2c22017-08-05 20:34:06 -07001239 /**
Charles Chand0dd7002017-10-08 23:53:36 -04001240 * Build the DHCP offer/ack with proper client port.
1241 *
1242 * @param ethernetPacket the original packet comes from server
1243 * @return new packet which will send to the client
1244 */
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001245 private InternalPacket processLeaseQueryFromServer(Ethernet ethernetPacket) {
Charles Chand0dd7002017-10-08 23:53:36 -04001246 // get dhcp header.
1247 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
1248 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
1249 UDP udpPacket = (UDP) ipv4Packet.getPayload();
1250 DHCP dhcpPayload = (DHCP) udpPacket.getPayload();
1251
1252 // determine the vlanId of the client host - note that this vlan id
1253 // could be different from the vlan in the packet from the server
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001254 Interface clientInterface = null;
1255 MacAddress destinationMac = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
1256
1257 if (!learnRouteFromLeasequery) {
1258 int giaddr = ipv4Packet.getDestinationAddress();
1259 IpAddress destinationAddress = Ip4Address.valueOf(giaddr);
1260 log.debug("DHCPLEASEQUERYRESP giaddr: {}({})", giaddr, destinationAddress);
1261
1262 Host destinationHost = hostService.getHostsByIp(destinationAddress).stream().findFirst().orElse(null);
1263 if (destinationHost != null) {
1264 destinationMac = destinationHost.mac();
1265 log.trace("DHCPLEASEQUERYRESP destination mac is: {}", destinationMac);
1266 ConnectPoint destinationLocation = destinationHost.location();
1267 log.trace("Lookup for client interface by destination location {}", destinationLocation);
1268 clientInterface = interfaceService.getInterfacesByPort(destinationLocation)
1269 .stream()
1270 .filter(iface -> interfaceContainsVlan(iface, VlanId.vlanId(etherReply.getVlanID())))
1271 .findFirst()
1272 .orElse(null);
1273 log.trace("Found Host {} by ip {}", destinationHost, destinationAddress);
1274 log.debug("DHCPLEASEQUERYRESP Client interface: {}",
1275 (clientInterface != null ? clientInterface : "not resolved"));
1276
1277 }
1278 } else {
1279 clientInterface = getClientInterface(ethernetPacket, dhcpPayload).orElse(null);
1280 }
Charles Chand0dd7002017-10-08 23:53:36 -04001281
1282 if (clientInterface == null) {
1283 log.warn("Cannot find the interface for the DHCP {}", dhcpPayload);
1284 return null;
1285 }
1286 VlanId vlanId;
1287 if (clientInterface.vlanTagged().isEmpty()) {
1288 vlanId = clientInterface.vlan();
1289 } else {
1290 // might be multiple vlan in same interface
1291 vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
1292 }
1293 if (vlanId == null) {
1294 vlanId = VlanId.NONE;
1295 }
1296 etherReply.setVlanID(vlanId.toShort());
1297 etherReply.setSourceMACAddress(clientInterface.mac());
1298
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001299 if (!directlyConnected(dhcpPayload) && learnRouteFromLeasequery) {
Charles Chand0dd7002017-10-08 23:53:36 -04001300 // if client is indirectly connected, try use next hop mac address
1301 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
1302 HostId hostId = HostId.hostId(macAddress, vlanId);
1303 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1304 if (record != null) {
1305 // if next hop can be found, use mac address of next hop
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001306 Optional<MacAddress> nextHop = record.nextHopTemp();
1307 if (!nextHop.isPresent()) {
1308 nextHop = record.nextHop();
1309 }
1310 nextHop.ifPresent(etherReply::setDestinationMACAddress);
Charles Chand0dd7002017-10-08 23:53:36 -04001311 } else {
1312 // otherwise, discard the packet
1313 log.warn("Can't find record for host id {}, discard packet", hostId);
1314 return null;
1315 }
1316 } else {
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001317 etherReply.setDestinationMACAddress(destinationMac);
Charles Chand0dd7002017-10-08 23:53:36 -04001318 }
1319
Charles Chand0dd7002017-10-08 23:53:36 -04001320 udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001321 if (directlyConnected(dhcpPayload)) {
1322 udpPacket.setDestinationPort(UDP.DHCP_CLIENT_PORT);
1323 } else {
1324 udpPacket.setDestinationPort(UDP.DHCP_SERVER_PORT);
1325 }
Charles Chand0dd7002017-10-08 23:53:36 -04001326
1327 udpPacket.setPayload(dhcpPayload);
1328 ipv4Packet.setPayload(udpPacket);
1329 etherReply.setPayload(ipv4Packet);
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001330 udpPacket.resetChecksum();
1331
1332 return InternalPacket.internalPacket(etherReply, clientInterface.connectPoint());
Charles Chand0dd7002017-10-08 23:53:36 -04001333 }
1334 /**
Yi Tsengdcef2c22017-08-05 20:34:06 -07001335 * Extracts VLAN ID from relay agent option.
1336 *
1337 * @param dhcpPayload the DHCP payload
1338 * @return VLAN ID from DHCP payload; null if not exists
1339 */
Yi Tseng4f2a0462017-08-31 11:21:00 -07001340 private VlanId getVlanIdFromRelayAgentOption(DHCP dhcpPayload) {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001341 DhcpRelayAgentOption option = (DhcpRelayAgentOption) dhcpPayload.getOption(OptionCode_CircuitID);
1342 if (option == null) {
1343 return null;
1344 }
1345 DhcpOption circuitIdSubOption = option.getSubOption(CIRCUIT_ID.getValue());
1346 if (circuitIdSubOption == null) {
1347 return null;
1348 }
1349 try {
1350 CircuitId circuitId = CircuitId.deserialize(circuitIdSubOption.getData());
1351 return circuitId.vlanId();
1352 } catch (IllegalArgumentException e) {
1353 // can't deserialize the circuit ID
1354 return null;
1355 }
1356 }
1357
1358 /**
1359 * Removes DHCP relay agent information option (option 82) from DHCP payload.
1360 * Also reset giaddr to 0
1361 *
1362 * @param ethPacket the Ethernet packet to be processed
1363 * @return Ethernet packet processed
1364 */
1365 private Ethernet removeRelayAgentOption(Ethernet ethPacket) {
rsahot036b94dffc2018-02-26 15:01:37 -05001366 Ethernet ethernet = (Ethernet) ethPacket.duplicate();
Yi Tsengdcef2c22017-08-05 20:34:06 -07001367 IPv4 ipv4 = (IPv4) ethernet.getPayload();
1368 UDP udp = (UDP) ipv4.getPayload();
1369 DHCP dhcpPayload = (DHCP) udp.getPayload();
1370
1371 // removes relay agent information option
1372 List<DhcpOption> options = dhcpPayload.getOptions();
1373 options = options.stream()
1374 .filter(option -> option.getCode() != OptionCode_CircuitID.getValue())
1375 .collect(Collectors.toList());
1376 dhcpPayload.setOptions(options);
1377 dhcpPayload.setGatewayIPAddress(0);
1378
1379 udp.setPayload(dhcpPayload);
1380 ipv4.setPayload(udp);
1381 ethernet.setPayload(ipv4);
1382 return ethernet;
1383 }
1384
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001385 private boolean isDhcpPacketLeasequery(DHCP dhcpPacket) {
1386 switch (dhcpPacket.getPacketType()) {
1387 case DHCPLEASEACTIVE:
1388 case DHCPLEASEQUERY:
1389 case DHCPLEASEUNASSIGNED:
1390 case DHCPLEASEUNKNOWN:
1391 return true;
1392 default:
1393 return false;
1394 }
1395 }
Yi Tseng51301292017-07-28 13:02:59 -07001396
1397 /**
1398 * Check if the host is directly connected to the network or not.
1399 *
1400 * @param dhcpPayload the dhcp payload
1401 * @return true if the host is directly connected to the network; false otherwise
1402 */
1403 private boolean directlyConnected(DHCP dhcpPayload) {
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001404 // leasequery is always indirect
1405 if (isDhcpPacketLeasequery(dhcpPayload)) {
1406 return false;
1407 }
1408
Yi Tseng440e2b72017-08-24 14:47:34 -07001409 DhcpRelayAgentOption relayAgentOption =
1410 (DhcpRelayAgentOption) dhcpPayload.getOption(OptionCode_CircuitID);
Yi Tseng51301292017-07-28 13:02:59 -07001411
1412 // Doesn't contains relay option
1413 if (relayAgentOption == null) {
1414 return true;
1415 }
1416
Yi Tseng440e2b72017-08-24 14:47:34 -07001417 // check circuit id, if circuit id is invalid, we say it is an indirect host
1418 DhcpOption circuitIdOpt = relayAgentOption.getSubOption(CIRCUIT_ID.getValue());
Yi Tseng51301292017-07-28 13:02:59 -07001419
Yi Tseng440e2b72017-08-24 14:47:34 -07001420 try {
1421 CircuitId.deserialize(circuitIdOpt.getData());
Yi Tseng51301292017-07-28 13:02:59 -07001422 return true;
Yi Tseng440e2b72017-08-24 14:47:34 -07001423 } catch (Exception e) {
1424 // invalid circuit id
1425 return false;
Yi Tseng51301292017-07-28 13:02:59 -07001426 }
Yi Tseng51301292017-07-28 13:02:59 -07001427 }
1428
1429
1430 /**
1431 * Send the DHCP ack to the requester host.
1432 * Modify Host or Route store according to the type of DHCP.
1433 *
1434 * @param ethernetPacketAck the packet
1435 * @param dhcpPayload the DHCP data
1436 */
1437 private void handleDhcpAck(Ethernet ethernetPacketAck, DHCP dhcpPayload) {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001438 Optional<Interface> outInterface = getClientInterface(ethernetPacketAck, dhcpPayload);
Yi Tseng51301292017-07-28 13:02:59 -07001439 if (!outInterface.isPresent()) {
1440 log.warn("Can't find output interface for dhcp: {}", dhcpPayload);
1441 return;
1442 }
1443
1444 Interface outIface = outInterface.get();
1445 HostLocation hostLocation = new HostLocation(outIface.connectPoint(), System.currentTimeMillis());
1446 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
Yi Tseng4f2a0462017-08-31 11:21:00 -07001447 VlanId vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -07001448 if (vlanId == null) {
1449 vlanId = outIface.vlan();
1450 }
Yi Tseng51301292017-07-28 13:02:59 -07001451 HostId hostId = HostId.hostId(macAddress, vlanId);
1452 Ip4Address ip = Ip4Address.valueOf(dhcpPayload.getYourIPAddress());
1453
1454 if (directlyConnected(dhcpPayload)) {
1455 // Add to host store if it connect to network directly
1456 Set<IpAddress> ips = Sets.newHashSet(ip);
Yi Tsengaa417a62017-09-08 17:22:51 -07001457 Host host = hostService.getHost(hostId);
Yi Tseng51301292017-07-28 13:02:59 -07001458
Yi Tsengaa417a62017-09-08 17:22:51 -07001459 Set<HostLocation> hostLocations = Sets.newHashSet(hostLocation);
1460 if (host != null) {
1461 // Dual homing support:
1462 // if host exists, use old locations and new location
1463 hostLocations.addAll(host.locations());
1464 }
1465 HostDescription desc = new DefaultHostDescription(macAddress, vlanId,
1466 hostLocations, ips, false);
1467 // Add IP address when dhcp server give the host new ip address
1468 providerService.hostDetected(hostId, desc, false);
Yi Tseng51301292017-07-28 13:02:59 -07001469 } else {
1470 // Add to route store if it does not connect to network directly
1471 // Get gateway host IP according to host mac address
Yi Tsengdcef2c22017-08-05 20:34:06 -07001472 // TODO: remove relay store here
Yi Tseng51301292017-07-28 13:02:59 -07001473 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1474
1475 if (record == null) {
1476 log.warn("Can't find DHCP record of host {}", hostId);
1477 return;
1478 }
1479
1480 MacAddress gwMac = record.nextHop().orElse(null);
1481 if (gwMac == null) {
1482 log.warn("Can't find gateway mac address from record {}", record);
1483 return;
1484 }
1485
1486 HostId gwHostId = HostId.hostId(gwMac, record.vlanId());
1487 Host gwHost = hostService.getHost(gwHostId);
1488
1489 if (gwHost == null) {
1490 log.warn("Can't find gateway host {}", gwHostId);
1491 return;
1492 }
1493
1494 Ip4Address nextHopIp = gwHost.ipAddresses()
1495 .stream()
1496 .filter(IpAddress::isIp4)
1497 .map(IpAddress::getIp4Address)
1498 .findFirst()
1499 .orElse(null);
1500
1501 if (nextHopIp == null) {
1502 log.warn("Can't find IP address of gateway {}", gwHost);
1503 return;
1504 }
1505
Charles Chanbe4deaf2018-04-04 11:43:54 -07001506 Route route = new Route(Route.Source.DHCP, ip.toIpPrefix(), nextHopIp);
Daniel Ginsburgc27fa8592018-06-09 01:43:59 +03001507 routeStore.replaceRoute(route);
Yi Tseng51301292017-07-28 13:02:59 -07001508 }
Yi Tseng51301292017-07-28 13:02:59 -07001509 }
1510
1511 /**
Yi Tseng51301292017-07-28 13:02:59 -07001512 * Gets output interface of a dhcp packet.
1513 * If option 82 exists in the dhcp packet and the option was sent by
Yi Tseng4f2a0462017-08-31 11:21:00 -07001514 * ONOS (circuit format is correct), use the connect
Yi Tseng51301292017-07-28 13:02:59 -07001515 * point and vlan id from circuit id; otherwise, find host by destination
1516 * address and use vlan id from sender (dhcp server).
1517 *
1518 * @param ethPacket the ethernet packet
1519 * @param dhcpPayload the dhcp packet
1520 * @return an interface represent the output port and vlan; empty value
1521 * if the host or circuit id not found
1522 */
Yi Tsengdcef2c22017-08-05 20:34:06 -07001523 private Optional<Interface> getClientInterface(Ethernet ethPacket, DHCP dhcpPayload) {
Yi Tseng51301292017-07-28 13:02:59 -07001524 VlanId originalPacketVlanId = VlanId.vlanId(ethPacket.getVlanID());
Yi Tseng51301292017-07-28 13:02:59 -07001525 DhcpRelayAgentOption option = (DhcpRelayAgentOption) dhcpPayload.getOption(OptionCode_CircuitID);
1526
Yi Tseng4f2a0462017-08-31 11:21:00 -07001527 DhcpOption circuitIdSubOption = option.getSubOption(CIRCUIT_ID.getValue());
1528 try {
1529 CircuitId circuitId = CircuitId.deserialize(circuitIdSubOption.getData());
1530 ConnectPoint connectPoint = ConnectPoint.deviceConnectPoint(circuitId.connectPoint());
1531 VlanId vlanId = circuitId.vlanId();
1532 return interfaceService.getInterfacesByPort(connectPoint)
1533 .stream()
1534 .filter(iface -> interfaceContainsVlan(iface, vlanId))
1535 .findFirst();
1536 } catch (IllegalArgumentException ex) {
1537 // invalid circuit format, didn't sent by ONOS
1538 log.debug("Invalid circuit {}, use information from dhcp payload",
1539 circuitIdSubOption.getData());
Yi Tseng51301292017-07-28 13:02:59 -07001540 }
Yi Tseng51301292017-07-28 13:02:59 -07001541 // Use Vlan Id from DHCP server if DHCP relay circuit id was not
1542 // sent by ONOS or circuit Id can't be parsed
Yi Tsengdcef2c22017-08-05 20:34:06 -07001543 // TODO: remove relay store from this method
Yi Tseng51301292017-07-28 13:02:59 -07001544 MacAddress dstMac = valueOf(dhcpPayload.getClientHardwareAddress());
jayakumarthazhath1d6b7db2018-09-25 15:56:51 -04001545 VlanId filteredVlanId = getVlanIdFromDhcpRecord(dstMac, originalPacketVlanId);
1546 // Get the vlan from the dhcp record
1547 if (filteredVlanId == null) {
1548 log.debug("not find the matching DHCP record for mac: {} and vlan: {}", dstMac, originalPacketVlanId);
1549 return Optional.empty();
1550 }
jayakumarthazhath1d6b7db2018-09-25 15:56:51 -04001551 Optional<DhcpRecord> dhcpRecord = dhcpRelayStore.getDhcpRecord(HostId.hostId(dstMac, filteredVlanId));
Yi Tsengdcef2c22017-08-05 20:34:06 -07001552 ConnectPoint clientConnectPoint = dhcpRecord
Yi Tseng51301292017-07-28 13:02:59 -07001553 .map(DhcpRecord::locations)
1554 .orElse(Collections.emptySet())
1555 .stream()
1556 .reduce((hl1, hl2) -> {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001557 // find latest host connect point
Yi Tseng51301292017-07-28 13:02:59 -07001558 if (hl1 == null || hl2 == null) {
1559 return hl1 == null ? hl2 : hl1;
1560 }
1561 return hl1.time() > hl2.time() ? hl1 : hl2;
1562 })
Yi Tsengdcef2c22017-08-05 20:34:06 -07001563 .orElse(null);
Yi Tseng51301292017-07-28 13:02:59 -07001564
Yi Tsengdcef2c22017-08-05 20:34:06 -07001565 if (clientConnectPoint != null) {
1566 return interfaceService.getInterfacesByPort(clientConnectPoint)
1567 .stream()
jayakumarthazhath1d6b7db2018-09-25 15:56:51 -04001568 .filter(iface -> interfaceContainsVlan(iface, filteredVlanId))
Yi Tsengdcef2c22017-08-05 20:34:06 -07001569 .findFirst();
1570 }
1571 return Optional.empty();
Yi Tseng51301292017-07-28 13:02:59 -07001572 }
1573
1574 /**
jayakumarthazhath1d6b7db2018-09-25 15:56:51 -04001575 * Get the required vlanId in case the DCHP record has more than one vlanId for a given MAC.
1576 *
1577 * @param mac MAC address of the DHCP client
1578 * @param vlan Expected vlan of the DHCP client
1579 */
1580 private VlanId getVlanIdFromDhcpRecord(MacAddress mac, VlanId vlan) {
1581 // Get all the DHCP records matching with the mac address
1582 // If only one entry is present then pick the vlan of that entry
1583 // If more then one entry is present then look for an entry with matching vlan
1584 // else return null
1585 Collection<DhcpRecord> records = dhcpRelayStore.getDhcpRecords();
1586 List<DhcpRecord> filteredRecords = new ArrayList<>();
1587 for (DhcpRecord e: records) {
1588 if (e.macAddress().equals(mac)) {
1589 filteredRecords.add(e);
1590 }
1591 }
1592 log.debug("getVlanIdFromDhcpRecord mac: {} vlan: {}", mac, vlan);
1593 log.debug("filteredRecords are: {}", filteredRecords);
1594 if (filteredRecords.size() == 1) {
1595 log.debug("Only one DHCP record entry. Returning back the vlan of that DHCP record: {}", filteredRecords);
1596 return filteredRecords.get(0).vlanId();
1597 }
1598 // Check in the DHCP filtered record for matching vlan
1599 for (DhcpRecord e: filteredRecords) {
1600 if (e.vlanId().equals(vlan)) {
1601 log.debug("Found a matching vlan entry in the DHCP record:{}", e);
1602 return vlan;
1603 }
1604 }
1605 // Found nothing return null
1606 log.debug("Returning null as no matching or more than one matching entry found");
1607 return null;
1608
1609 }
1610
jayakumarthazhath1d6b7db2018-09-25 15:56:51 -04001611 /**
Yi Tseng51301292017-07-28 13:02:59 -07001612 * Send the response DHCP to the requester host.
1613 *
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001614 * @param thePacket the packet
Yi Tseng51301292017-07-28 13:02:59 -07001615 * @param dhcpPayload the DHCP data
1616 */
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001617 private void sendResponseToClient(InternalPacket thePacket, DHCP dhcpPayload) {
1618 checkNotNull(thePacket, "Nothing to send");
1619 checkNotNull(thePacket.getPacket(), "Packet to send must not be empty");
1620 checkNotNull(thePacket.getDestLocation(), "Packet destination not be empty");
1621
1622 Ethernet ethPacket = thePacket.getPacket();
Yi Tsengdcef2c22017-08-05 20:34:06 -07001623 if (directlyConnected(dhcpPayload)) {
1624 ethPacket = removeRelayAgentOption(ethPacket);
1625 }
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001626
Yi Tsengdcef2c22017-08-05 20:34:06 -07001627 TrafficTreatment treatment = DefaultTrafficTreatment.builder()
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001628 .setOutput(thePacket.getDestLocation().port())
Yi Tsengdcef2c22017-08-05 20:34:06 -07001629 .build();
1630 OutboundPacket o = new DefaultOutboundPacket(
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001631 thePacket.getDestLocation().deviceId(),
Yi Tsengdcef2c22017-08-05 20:34:06 -07001632 treatment,
1633 ByteBuffer.wrap(ethPacket.serialize()));
1634 if (log.isTraceEnabled()) {
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001635 log.trace("Relaying packet to DHCP client {} via {}",
Yi Tsengdcef2c22017-08-05 20:34:06 -07001636 ethPacket,
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001637 thePacket.getDestLocation());
Yi Tsengdcef2c22017-08-05 20:34:06 -07001638 }
1639 packetService.emit(o);
Yi Tseng51301292017-07-28 13:02:59 -07001640 }
Yi Tseng483ac6f2017-08-02 15:03:31 -07001641
Yi Tsengaa417a62017-09-08 17:22:51 -07001642 @Override
1643 public void triggerProbe(Host host) {
1644 // Do nothing here
1645 }
1646
1647 @Override
1648 public ProviderId id() {
Charles Chand988c282017-09-12 17:09:32 -07001649 return PROVIDER_ID;
Yi Tsengaa417a62017-09-08 17:22:51 -07001650 }
1651
Yi Tseng483ac6f2017-08-02 15:03:31 -07001652 class InternalHostListener implements HostListener {
1653 @Override
1654 public void event(HostEvent event) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001655 if (!configured()) {
1656 return;
1657 }
Yi Tseng483ac6f2017-08-02 15:03:31 -07001658 switch (event.type()) {
1659 case HOST_ADDED:
1660 case HOST_UPDATED:
Charles Chan768e8b82018-08-13 10:32:03 -07001661 case HOST_MOVED:
Jordan Halterman15e3b1e2018-04-10 13:34:50 -04001662 log.trace("Scheduled host event {}", event);
1663 hostEventExecutor.execute(() -> hostUpdated(event.subject()));
Yi Tseng483ac6f2017-08-02 15:03:31 -07001664 break;
1665 case HOST_REMOVED:
Jordan Halterman15e3b1e2018-04-10 13:34:50 -04001666 log.trace("Scheduled host event {}", event);
1667 hostEventExecutor.execute(() -> hostRemoved(event.subject()));
Yi Tseng483ac6f2017-08-02 15:03:31 -07001668 break;
Yi Tseng483ac6f2017-08-02 15:03:31 -07001669 default:
1670 break;
1671 }
1672 }
1673 }
1674
1675 /**
Yi Tseng483ac6f2017-08-02 15:03:31 -07001676 * Handle host updated.
1677 * If the host is DHCP server or gateway, update connect mac and vlan.
1678 *
1679 * @param host the host
1680 */
1681 private void hostUpdated(Host host) {
Yi Tseng525ff402017-10-23 19:39:39 -07001682 hostUpdated(host, defaultServerInfoList);
1683 hostUpdated(host, indirectServerInfoList);
Yi Tseng483ac6f2017-08-02 15:03:31 -07001684 }
1685
Yi Tseng525ff402017-10-23 19:39:39 -07001686 private void hostUpdated(Host host, List<DhcpServerInfo> srverInfoList) {
jjosep004c7fe51462018-08-21 09:01:10 -04001687 srverInfoList.stream().forEach(serverInfo -> {
1688 Ip4Address targetIp = serverInfo.getDhcpGatewayIp4().orElse(null);
Yi Tseng525ff402017-10-23 19:39:39 -07001689 Ip4Address serverIp = serverInfo.getDhcpServerIp4().orElse(null);
Yi Tseng525ff402017-10-23 19:39:39 -07001690 if (targetIp == null) {
1691 targetIp = serverIp;
1692 }
Yi Tseng525ff402017-10-23 19:39:39 -07001693 if (targetIp != null) {
1694 if (host.ipAddresses().contains(targetIp)) {
1695 serverInfo.setDhcpConnectMac(host.mac());
1696 serverInfo.setDhcpConnectVlan(host.vlan());
1697 requestDhcpPacket(serverIp);
1698 }
1699 }
jjosep004c7fe51462018-08-21 09:01:10 -04001700 });
Yi Tseng525ff402017-10-23 19:39:39 -07001701 }
1702
1703
Yi Tseng483ac6f2017-08-02 15:03:31 -07001704 /**
1705 * Handle host removed.
1706 * If the host is DHCP server or gateway, unset connect mac and vlan.
1707 *
1708 * @param host the host
1709 */
1710 private void hostRemoved(Host host) {
Yi Tseng525ff402017-10-23 19:39:39 -07001711 hostRemoved(host, defaultServerInfoList);
1712 hostRemoved(host, indirectServerInfoList);
1713 }
1714
1715 private void hostRemoved(Host host, List<DhcpServerInfo> serverInfoList) {
jjosep004c7fe51462018-08-21 09:01:10 -04001716 serverInfoList.stream().forEach(serverInfo -> {
1717 Ip4Address targetIp = serverInfo.getDhcpGatewayIp4().orElse(null);
Yi Tseng525ff402017-10-23 19:39:39 -07001718 Ip4Address serverIp = serverInfo.getDhcpServerIp4().orElse(null);
Yi Tseng525ff402017-10-23 19:39:39 -07001719 if (targetIp == null) {
1720 targetIp = serverIp;
Yi Tseng919b2df2017-09-07 16:22:51 -07001721 }
Yi Tseng525ff402017-10-23 19:39:39 -07001722
1723 if (targetIp != null) {
1724 if (host.ipAddresses().contains(targetIp)) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001725 serverInfo.setDhcpConnectVlan(null);
1726 serverInfo.setDhcpConnectMac(null);
Yi Tseng525ff402017-10-23 19:39:39 -07001727 cancelDhcpPacket(serverIp);
Yi Tseng919b2df2017-09-07 16:22:51 -07001728 }
Yi Tseng483ac6f2017-08-02 15:03:31 -07001729 }
jjosep004c7fe51462018-08-21 09:01:10 -04001730 });
Yi Tseng525ff402017-10-23 19:39:39 -07001731 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001732
Yi Tseng525ff402017-10-23 19:39:39 -07001733 private void requestDhcpPacket(Ip4Address serverIp) {
1734 requestServerDhcpPacket(serverIp);
1735 requestClientDhcpPacket(serverIp);
1736 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001737
Yi Tseng525ff402017-10-23 19:39:39 -07001738 private void cancelDhcpPacket(Ip4Address serverIp) {
1739 cancelServerDhcpPacket(serverIp);
1740 cancelClientDhcpPacket(serverIp);
1741 }
1742
1743 private void cancelServerDhcpPacket(Ip4Address serverIp) {
1744 TrafficSelector serverSelector =
1745 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1746 .matchIPSrc(serverIp.toIpPrefix())
1747 .build();
1748 packetService.cancelPackets(serverSelector,
1749 PacketPriority.CONTROL,
1750 appId);
1751 }
1752
1753 private void requestServerDhcpPacket(Ip4Address serverIp) {
1754 TrafficSelector serverSelector =
1755 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1756 .matchIPSrc(serverIp.toIpPrefix())
1757 .build();
1758 packetService.requestPackets(serverSelector,
1759 PacketPriority.CONTROL,
1760 appId);
1761 }
1762
1763 private void cancelClientDhcpPacket(Ip4Address serverIp) {
1764 // Packet comes from relay
1765 TrafficSelector indirectClientSelector =
1766 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1767 .matchIPDst(serverIp.toIpPrefix())
1768 .build();
1769 packetService.cancelPackets(indirectClientSelector,
1770 PacketPriority.CONTROL,
1771 appId);
1772
1773 // Packet comes from client
1774 packetService.cancelPackets(CLIENT_SERVER_SELECTOR,
1775 PacketPriority.CONTROL,
1776 appId);
1777 }
1778
1779 private void requestClientDhcpPacket(Ip4Address serverIp) {
1780 // Packet comes from relay
1781 TrafficSelector indirectClientSelector =
1782 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1783 .matchIPDst(serverIp.toIpPrefix())
1784 .build();
1785 packetService.requestPackets(indirectClientSelector,
1786 PacketPriority.CONTROL,
1787 appId);
1788
1789 // Packet comes from client
1790 packetService.requestPackets(CLIENT_SERVER_SELECTOR,
1791 PacketPriority.CONTROL,
1792 appId);
1793 }
1794
1795 /**
1796 * Process the ignore rules.
1797 *
1798 * @param deviceId the device id
1799 * @param vlanId the vlan to be ignored
1800 * @param op the operation, ADD to install; REMOVE to uninstall rules
1801 */
1802 private void processIgnoreVlanRule(DeviceId deviceId, VlanId vlanId, Objective.Operation op) {
Yi Tseng525ff402017-10-23 19:39:39 -07001803 AtomicInteger installedCount = new AtomicInteger(DHCP_SELECTORS.size());
1804 DHCP_SELECTORS.forEach(trafficSelector -> {
1805 TrafficSelector selector = DefaultTrafficSelector.builder(trafficSelector)
1806 .matchVlanId(vlanId)
1807 .build();
1808
1809 ForwardingObjective.Builder builder = DefaultForwardingObjective.builder()
1810 .withFlag(ForwardingObjective.Flag.VERSATILE)
1811 .withSelector(selector)
1812 .withPriority(IGNORE_CONTROL_PRIORITY)
Yi Tsengf4311972017-11-29 10:49:20 -08001813 .withTreatment(DefaultTrafficTreatment.emptyTreatment())
Yi Tseng525ff402017-10-23 19:39:39 -07001814 .fromApp(appId);
1815
1816
1817 ObjectiveContext objectiveContext = new ObjectiveContext() {
1818 @Override
1819 public void onSuccess(Objective objective) {
1820 log.info("Ignore rule {} (Vlan id {}, device {}, selector {})",
1821 op, vlanId, deviceId, selector);
1822 int countDown = installedCount.decrementAndGet();
1823 if (countDown != 0) {
1824 return;
1825 }
1826 switch (op) {
1827 case ADD:
1828 ignoredVlans.put(deviceId, vlanId);
1829 break;
1830 case REMOVE:
1831 ignoredVlans.remove(deviceId, vlanId);
1832 break;
1833 default:
1834 log.warn("Unsupported objective operation {}", op);
1835 break;
1836 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001837 }
Yi Tseng525ff402017-10-23 19:39:39 -07001838
1839 @Override
1840 public void onError(Objective objective, ObjectiveError error) {
1841 log.warn("Can't {} ignore rule (vlan id {}, selector {}, device {}) due to {}",
1842 op, vlanId, selector, deviceId, error);
Yi Tseng919b2df2017-09-07 16:22:51 -07001843 }
Yi Tseng525ff402017-10-23 19:39:39 -07001844 };
1845
1846 ForwardingObjective fwd;
1847 switch (op) {
1848 case ADD:
1849 fwd = builder.add(objectiveContext);
1850 break;
1851 case REMOVE:
1852 fwd = builder.remove(objectiveContext);
1853 break;
1854 default:
1855 log.warn("Unsupported objective operation {}", op);
1856 return;
Yi Tseng4f2a0462017-08-31 11:21:00 -07001857 }
Yi Tseng525ff402017-10-23 19:39:39 -07001858
1859 Device device = deviceService.getDevice(deviceId);
1860 if (device == null || !device.is(Pipeliner.class)) {
1861 log.warn("Device {} is not available now, wait until device is available", deviceId);
1862 return;
1863 }
1864 flowObjectiveService.apply(deviceId, fwd);
1865 });
Yi Tseng483ac6f2017-08-02 15:03:31 -07001866 }
Kalhee Kimba366062017-11-07 16:32:09 +00001867
1868 @Override
1869 public void setDhcpFpmEnabled(Boolean enabled) {
1870 // v4 does not use fpm. Do nothing.
1871 }
rsahot036b94dffc2018-02-26 15:01:37 -05001872 private List<DhcpServerInfo> findValidServerInfo(boolean directConnFlag) {
1873 List<DhcpServerInfo> validServerInfo;
1874
1875 if (directConnFlag || indirectServerInfoList.isEmpty()) {
1876 validServerInfo = new ArrayList<DhcpServerInfo>(defaultServerInfoList);
1877 } else {
1878 validServerInfo = new ArrayList<DhcpServerInfo>(indirectServerInfoList);
1879 }
1880 return validServerInfo;
1881 }
1882
rsahot036b94dffc2018-02-26 15:01:37 -05001883 private boolean checkDhcpServerConnPt(boolean directConnFlag,
1884 DhcpServerInfo serverInfo) {
1885 if (serverInfo.getDhcpServerConnectPoint() == null) {
1886 log.warn("DHCP4 server connect point for {} connPt {}",
1887 directConnFlag ? "direct" : "indirect", serverInfo.getDhcpServerConnectPoint());
1888 return false;
1889 }
1890 return true;
1891 }
1892
1893 /**
1894 * Checks if serverInfo's host info (mac and vlan) is filled in; if not, fills in.
1895 *
1896 * @param serverInfo server information
1897 * @return newServerInfo if host info can be either found or filled in.
1898 */
1899 private DhcpServerInfo getHostInfoForServerInfo(DhcpServerInfo serverInfo, List<DhcpServerInfo> sererInfoList) {
1900 DhcpServerInfo newServerInfo = null;
1901 MacAddress dhcpServerConnectMac = serverInfo.getDhcpConnectMac().orElse(null);
1902 VlanId dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1903 ConnectPoint dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1904
1905 if (dhcpServerConnectMac != null && dhcpConnectVlan != null) {
1906 newServerInfo = serverInfo;
Charles Chan0363d052018-03-02 18:27:59 -08001907 log.debug("DHCP server {} host info found. ConnectPt{} Mac {} vlan {}", serverInfo.getDhcpServerIp4(),
rsahot036b94dffc2018-02-26 15:01:37 -05001908 dhcpServerConnectPoint, dhcpServerConnectMac, dhcpConnectVlan);
1909 } else {
1910 log.warn("DHCP server {} not resolve yet connectPt {} mac {} vlan {}", serverInfo.getDhcpServerIp4(),
1911 dhcpServerConnectPoint, dhcpServerConnectMac, dhcpConnectVlan);
1912
1913 Ip4Address ipToProbe;
1914 if (serverInfo.getDhcpGatewayIp4().isPresent()) {
1915 ipToProbe = serverInfo.getDhcpGatewayIp4().get();
1916 } else {
1917 ipToProbe = serverInfo.getDhcpServerIp4().orElse(null);
1918 }
1919 String hostToProbe = serverInfo.getDhcpGatewayIp6()
1920 .map(ip -> "gateway").orElse("server");
1921
1922 log.warn("Dynamically probing to resolve {} IP {}", hostToProbe, ipToProbe);
1923 hostService.startMonitoringIp(ipToProbe);
1924
1925 Set<Host> hosts = hostService.getHostsByIp(ipToProbe);
1926 if (!hosts.isEmpty()) {
1927 int serverInfoIndex = sererInfoList.indexOf(serverInfo);
1928 Host host = hosts.iterator().next();
1929 serverInfo.setDhcpConnectVlan(host.vlan());
1930 serverInfo.setDhcpConnectMac(host.mac());
1931 // replace the serverInfo in the list
1932 sererInfoList.set(serverInfoIndex, serverInfo);
1933 newServerInfo = serverInfo;
1934 log.warn("Dynamically host found host {}", host);
1935 } else {
1936 log.warn("No host found host ip {} dynamically", ipToProbe);
1937 }
1938 }
1939 return newServerInfo;
1940 }
1941
1942 /**
1943 * Gets Interface facing to the server for default host.
1944 *
1945 * @param serverInfo server information
1946 * @return the Interface facing to the server; null if not found
1947 */
1948 private Interface getServerInterface(DhcpServerInfo serverInfo) {
1949 Interface serverInterface = null;
1950
1951 ConnectPoint dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1952 VlanId dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1953
1954 if (dhcpServerConnectPoint != null && dhcpConnectVlan != null) {
1955 serverInterface = interfaceService.getInterfacesByPort(dhcpServerConnectPoint)
1956 .stream()
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001957 .filter(iface -> Dhcp4HandlerUtil.interfaceContainsVlan(iface, dhcpConnectVlan))
rsahot036b94dffc2018-02-26 15:01:37 -05001958 .findFirst()
1959 .orElse(null);
1960 } else {
1961 log.warn("DHCP server {} not resolve yet connectPoint {} vlan {}", serverInfo.getDhcpServerIp6(),
1962 dhcpServerConnectPoint, dhcpConnectVlan);
1963 }
1964
1965 return serverInterface;
1966 }
1967
1968 //forward the packet to ConnectPoint where the DHCP server is attached.
1969 private void forwardPacket(InternalPacket packet) {
1970 //send Packetout to dhcp server connectpoint.
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001971 if (packet.getDestLocation() != null) {
rsahot036b94dffc2018-02-26 15:01:37 -05001972 TrafficTreatment t = DefaultTrafficTreatment.builder()
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001973 .setOutput(packet.getDestLocation().port()).build();
rsahot036b94dffc2018-02-26 15:01:37 -05001974 OutboundPacket o = new DefaultOutboundPacket(
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001975 packet.getDestLocation().deviceId(), t, ByteBuffer.wrap(packet.getPacket().serialize()));
rsahot036b94dffc2018-02-26 15:01:37 -05001976 if (log.isTraceEnabled()) {
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001977 log.trace("Relaying packet to destination {}", packet.getDestLocation());
rsahot036b94dffc2018-02-26 15:01:37 -05001978 }
Taras Lemkin371ac5e2018-03-26 14:52:58 +00001979 log.debug("packetService.emit(o) to port {}", packet.getDestLocation());
rsahot036b94dffc2018-02-26 15:01:37 -05001980 packetService.emit(o);
1981 }
1982 }
1983
rsahot036b94dffc2018-02-26 15:01:37 -05001984 private DhcpServerInfo findServerInfoFromServer(boolean directConnFlag, ConnectPoint inPort) {
1985 List<DhcpServerInfo> validServerInfoList = findValidServerInfo(directConnFlag);
1986 DhcpServerInfo foundServerInfo = null;
1987 for (DhcpServerInfo serverInfo : validServerInfoList) {
1988 if (inPort.equals(serverInfo.getDhcpServerConnectPoint().get())) {
1989 foundServerInfo = serverInfo;
Charles Chan0363d052018-03-02 18:27:59 -08001990 log.debug("ServerInfo found for Rcv port {} Server Connect Point {} for {}",
rsahot036b94dffc2018-02-26 15:01:37 -05001991 inPort, serverInfo.getDhcpServerConnectPoint(), directConnFlag ? "direct" : "indirect");
1992 break;
rsahot036b94dffc2018-02-26 15:01:37 -05001993 }
1994 }
1995 return foundServerInfo;
1996 }
Yi Tseng51301292017-07-28 13:02:59 -07001997}