blob: 781a0e25c506cba21b581386abca6c8e4b10b61d [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;
Yi Tseng919b2df2017-09-07 16:22:51 -070022import com.google.common.collect.Lists;
Yi Tseng525ff402017-10-23 19:39:39 -070023import com.google.common.collect.Multimap;
Yi Tseng51301292017-07-28 13:02:59 -070024import com.google.common.collect.Sets;
Yi Tseng483ac6f2017-08-02 15:03:31 -070025import org.apache.felix.scr.annotations.Activate;
Yi Tseng51301292017-07-28 13:02:59 -070026import org.apache.felix.scr.annotations.Component;
Yi Tseng483ac6f2017-08-02 15:03:31 -070027import org.apache.felix.scr.annotations.Deactivate;
Yi Tseng51301292017-07-28 13:02:59 -070028import org.apache.felix.scr.annotations.Property;
29import org.apache.felix.scr.annotations.Reference;
30import org.apache.felix.scr.annotations.ReferenceCardinality;
31import org.apache.felix.scr.annotations.Service;
32import org.onlab.packet.BasePacket;
33import org.onlab.packet.DHCP;
34import org.onlab.packet.Ethernet;
35import org.onlab.packet.IPv4;
36import org.onlab.packet.Ip4Address;
37import org.onlab.packet.IpAddress;
38import org.onlab.packet.MacAddress;
Yi Tseng525ff402017-10-23 19:39:39 -070039import org.onlab.packet.TpPort;
Yi Tseng51301292017-07-28 13:02:59 -070040import org.onlab.packet.UDP;
41import org.onlab.packet.VlanId;
42import org.onlab.packet.dhcp.CircuitId;
43import org.onlab.packet.dhcp.DhcpOption;
44import org.onlab.packet.dhcp.DhcpRelayAgentOption;
Yi Tseng525ff402017-10-23 19:39:39 -070045import org.onosproject.core.ApplicationId;
46import org.onosproject.core.CoreService;
Yi Tseng51301292017-07-28 13:02:59 -070047import org.onosproject.dhcprelay.api.DhcpHandler;
Yi Tseng919b2df2017-09-07 16:22:51 -070048import org.onosproject.dhcprelay.api.DhcpServerInfo;
Yi Tseng483ac6f2017-08-02 15:03:31 -070049import org.onosproject.dhcprelay.config.DhcpServerConfig;
Yi Tseng525ff402017-10-23 19:39:39 -070050import org.onosproject.dhcprelay.config.IgnoreDhcpConfig;
Yi Tseng51301292017-07-28 13:02:59 -070051import org.onosproject.dhcprelay.store.DhcpRecord;
52import org.onosproject.dhcprelay.store.DhcpRelayStore;
Yi Tseng525ff402017-10-23 19:39:39 -070053import org.onosproject.net.Device;
54import org.onosproject.net.DeviceId;
55import org.onosproject.net.behaviour.Pipeliner;
56import org.onosproject.net.device.DeviceService;
57import org.onosproject.net.flow.DefaultTrafficSelector;
58import org.onosproject.net.flow.TrafficSelector;
59import org.onosproject.net.flowobjective.DefaultForwardingObjective;
60import org.onosproject.net.flowobjective.FlowObjectiveService;
61import org.onosproject.net.flowobjective.ForwardingObjective;
62import org.onosproject.net.flowobjective.Objective;
63import org.onosproject.net.flowobjective.ObjectiveContext;
64import org.onosproject.net.flowobjective.ObjectiveError;
Yi Tseng483ac6f2017-08-02 15:03:31 -070065import org.onosproject.net.host.HostEvent;
66import org.onosproject.net.host.HostListener;
Yi Tsengaa417a62017-09-08 17:22:51 -070067import org.onosproject.net.host.HostProvider;
68import org.onosproject.net.host.HostProviderRegistry;
69import org.onosproject.net.host.HostProviderService;
Ray Milkeyfacf2862017-08-03 11:58:29 -070070import org.onosproject.net.intf.Interface;
71import org.onosproject.net.intf.InterfaceService;
Yi Tseng525ff402017-10-23 19:39:39 -070072import org.onosproject.net.packet.PacketPriority;
Yi Tsengaa417a62017-09-08 17:22:51 -070073import org.onosproject.net.provider.ProviderId;
Ray Milkey69ec8712017-08-08 13:00:43 -070074import org.onosproject.routeservice.Route;
75import org.onosproject.routeservice.RouteStore;
Yi Tseng51301292017-07-28 13:02:59 -070076import org.onosproject.net.ConnectPoint;
77import org.onosproject.net.Host;
78import org.onosproject.net.HostId;
79import org.onosproject.net.HostLocation;
80import org.onosproject.net.flow.DefaultTrafficTreatment;
81import org.onosproject.net.flow.TrafficTreatment;
82import org.onosproject.net.host.DefaultHostDescription;
83import org.onosproject.net.host.HostDescription;
84import org.onosproject.net.host.HostService;
Yi Tseng51301292017-07-28 13:02:59 -070085import org.onosproject.net.host.InterfaceIpAddress;
86import org.onosproject.net.packet.DefaultOutboundPacket;
87import org.onosproject.net.packet.OutboundPacket;
88import org.onosproject.net.packet.PacketContext;
89import org.onosproject.net.packet.PacketService;
90import org.slf4j.Logger;
91import org.slf4j.LoggerFactory;
92
93import java.nio.ByteBuffer;
Yi Tsengdcef2c22017-08-05 20:34:06 -070094import java.util.Collection;
Yi Tseng51301292017-07-28 13:02:59 -070095import java.util.Collections;
96import java.util.List;
rsahot036620655b2018-02-26 15:01:37 -050097import java.util.ArrayList;
Yi Tseng51301292017-07-28 13:02:59 -070098import java.util.Optional;
99import java.util.Set;
Yi Tseng525ff402017-10-23 19:39:39 -0700100import java.util.concurrent.atomic.AtomicInteger;
Yi Tseng51301292017-07-28 13:02:59 -0700101import java.util.stream.Collectors;
102
103import static com.google.common.base.Preconditions.checkNotNull;
104import static com.google.common.base.Preconditions.checkState;
105import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_CircuitID;
106import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_END;
107import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_MessageType;
108import static org.onlab.packet.MacAddress.valueOf;
109import static org.onlab.packet.dhcp.DhcpRelayAgentOption.RelayAgentInfoOptions.CIRCUIT_ID;
Yi Tseng525ff402017-10-23 19:39:39 -0700110import static org.onosproject.net.flowobjective.Objective.Operation.ADD;
111import static org.onosproject.net.flowobjective.Objective.Operation.REMOVE;
Yi Tseng51301292017-07-28 13:02:59 -0700112
rsahot036620655b2018-02-26 15:01:37 -0500113import org.onosproject.dhcprelay.Dhcp4HandlerUtil.InternalPacket;
114
Yi Tseng51301292017-07-28 13:02:59 -0700115@Component
116@Service
117@Property(name = "version", value = "4")
Yi Tsengaa417a62017-09-08 17:22:51 -0700118public class Dhcp4HandlerImpl implements DhcpHandler, HostProvider {
Charles Chand988c282017-09-12 17:09:32 -0700119 public static final String DHCP_V4_RELAY_APP = "org.onosproject.Dhcp4HandlerImpl";
120 public static final ProviderId PROVIDER_ID = new ProviderId("dhcp4", DHCP_V4_RELAY_APP);
Yi Tseng525ff402017-10-23 19:39:39 -0700121 private static final String BROADCAST_IP = "255.255.255.255";
122 private static final int IGNORE_CONTROL_PRIORITY = PacketPriority.CONTROL.priorityValue() + 1000;
123
124 private static final TrafficSelector CLIENT_SERVER_SELECTOR = DefaultTrafficSelector.builder()
125 .matchEthType(Ethernet.TYPE_IPV4)
126 .matchIPProtocol(IPv4.PROTOCOL_UDP)
127 .matchIPSrc(Ip4Address.ZERO.toIpPrefix())
128 .matchIPDst(Ip4Address.valueOf(BROADCAST_IP).toIpPrefix())
129 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_CLIENT_PORT))
130 .matchUdpDst(TpPort.tpPort(UDP.DHCP_SERVER_PORT))
131 .build();
132 private static final TrafficSelector SERVER_RELAY_SELECTOR = DefaultTrafficSelector.builder()
133 .matchEthType(Ethernet.TYPE_IPV4)
134 .matchIPProtocol(IPv4.PROTOCOL_UDP)
135 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_SERVER_PORT))
136 .matchUdpDst(TpPort.tpPort(UDP.DHCP_SERVER_PORT))
137 .build();
138 static final Set<TrafficSelector> DHCP_SELECTORS = ImmutableSet.of(
139 CLIENT_SERVER_SELECTOR,
140 SERVER_RELAY_SELECTOR
141 );
Yi Tseng51301292017-07-28 13:02:59 -0700142 private static Logger log = LoggerFactory.getLogger(Dhcp4HandlerImpl.class);
143
144 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
145 protected DhcpRelayStore dhcpRelayStore;
146
147 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
148 protected PacketService packetService;
149
150 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yi Tseng51301292017-07-28 13:02:59 -0700151 protected RouteStore routeStore;
152
153 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
154 protected InterfaceService interfaceService;
155
156 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
157 protected HostService hostService;
158
Yi Tsengaa417a62017-09-08 17:22:51 -0700159 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
160 protected HostProviderRegistry providerRegistry;
161
Yi Tseng525ff402017-10-23 19:39:39 -0700162 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
163 protected CoreService coreService;
164
165 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
166 protected DeviceService deviceService;
167
168 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
169 protected FlowObjectiveService flowObjectiveService;
170
Yi Tsengaa417a62017-09-08 17:22:51 -0700171 protected HostProviderService providerService;
Yi Tseng525ff402017-10-23 19:39:39 -0700172 protected ApplicationId appId;
173 protected Multimap<DeviceId, VlanId> ignoredVlans = HashMultimap.create();
Yi Tseng483ac6f2017-08-02 15:03:31 -0700174 private InternalHostListener hostListener = new InternalHostListener();
175
Yi Tseng919b2df2017-09-07 16:22:51 -0700176 private List<DhcpServerInfo> defaultServerInfoList = Lists.newArrayList();
177 private List<DhcpServerInfo> indirectServerInfoList = Lists.newArrayList();
rsahot036620655b2018-02-26 15:01:37 -0500178 private Dhcp4HandlerUtil dhcp4HandlerUtil = new Dhcp4HandlerUtil();
Yi Tseng4f2a0462017-08-31 11:21:00 -0700179
Yi Tseng483ac6f2017-08-02 15:03:31 -0700180 @Activate
181 protected void activate() {
Yi Tseng525ff402017-10-23 19:39:39 -0700182 appId = coreService.registerApplication(DHCP_V4_RELAY_APP);
Yi Tseng483ac6f2017-08-02 15:03:31 -0700183 hostService.addListener(hostListener);
Yi Tsengaa417a62017-09-08 17:22:51 -0700184 providerService = providerRegistry.register(this);
Yi Tseng483ac6f2017-08-02 15:03:31 -0700185 }
186
187 @Deactivate
188 protected void deactivate() {
Yi Tsengaa417a62017-09-08 17:22:51 -0700189 providerRegistry.unregister(this);
190 hostService.removeListener(hostListener);
Yi Tseng919b2df2017-09-07 16:22:51 -0700191 defaultServerInfoList.forEach(this::stopMonitoringIps);
192 defaultServerInfoList.clear();
193 indirectServerInfoList.forEach(this::stopMonitoringIps);
194 indirectServerInfoList.clear();
Yi Tseng483ac6f2017-08-02 15:03:31 -0700195 }
196
Yi Tseng919b2df2017-09-07 16:22:51 -0700197 private void stopMonitoringIps(DhcpServerInfo serverInfo) {
198 serverInfo.getDhcpGatewayIp4().ifPresent(gatewayIp -> {
199 hostService.stopMonitoringIp(gatewayIp);
200 });
201 serverInfo.getDhcpServerIp4().ifPresent(serverIp -> {
202 hostService.stopMonitoringIp(serverIp);
203 });
Yi Tseng51301292017-07-28 13:02:59 -0700204 }
205
206 @Override
Yi Tseng483ac6f2017-08-02 15:03:31 -0700207 public void setDefaultDhcpServerConfigs(Collection<DhcpServerConfig> configs) {
Yi Tseng919b2df2017-09-07 16:22:51 -0700208 setDhcpServerConfigs(configs, defaultServerInfoList);
209 }
210
211 @Override
212 public void setIndirectDhcpServerConfigs(Collection<DhcpServerConfig> configs) {
213 setDhcpServerConfigs(configs, indirectServerInfoList);
214 }
215
216 @Override
217 public List<DhcpServerInfo> getDefaultDhcpServerInfoList() {
218 return defaultServerInfoList;
219 }
220
221 @Override
222 public List<DhcpServerInfo> getIndirectDhcpServerInfoList() {
223 return indirectServerInfoList;
224 }
225
Yi Tseng525ff402017-10-23 19:39:39 -0700226 @Override
227 public void updateIgnoreVlanConfig(IgnoreDhcpConfig config) {
228 if (config == null) {
229 ignoredVlans.forEach(((deviceId, vlanId) -> {
230 processIgnoreVlanRule(deviceId, vlanId, REMOVE);
231 }));
232 return;
233 }
234 config.ignoredVlans().forEach((deviceId, vlanId) -> {
235 if (ignoredVlans.get(deviceId).contains(vlanId)) {
236 // don't need to process if it already ignored
237 return;
238 }
239 processIgnoreVlanRule(deviceId, vlanId, ADD);
240 });
241
242 ignoredVlans.forEach((deviceId, vlanId) -> {
243 if (!config.ignoredVlans().get(deviceId).contains(vlanId)) {
244 // not contains in new config, remove it
245 processIgnoreVlanRule(deviceId, vlanId, REMOVE);
246 }
247 });
248 }
249
Saurav Dasb805f1a2017-12-13 16:19:35 -0800250 @Override
251 public void removeIgnoreVlanState(IgnoreDhcpConfig config) {
252 if (config == null) {
253 ignoredVlans.clear();
254 return;
255 }
256 config.ignoredVlans().forEach((deviceId, vlanId) -> {
257 ignoredVlans.remove(deviceId, vlanId);
258 });
259 }
260
Yi Tseng919b2df2017-09-07 16:22:51 -0700261 public void setDhcpServerConfigs(Collection<DhcpServerConfig> configs, List<DhcpServerInfo> serverInfoList) {
Yi Tseng483ac6f2017-08-02 15:03:31 -0700262 if (configs.size() == 0) {
263 // no config to update
264 return;
265 }
266
rsahot036620655b2018-02-26 15:01:37 -0500267 Boolean isConfigValid = false;
268 for (DhcpServerConfig serverConfig : configs) {
269 if (serverConfig.getDhcpServerIp4().isPresent()) {
270 isConfigValid = true;
271 break;
272 }
Yi Tseng483ac6f2017-08-02 15:03:31 -0700273 }
rsahot036620655b2018-02-26 15:01:37 -0500274 if (!isConfigValid) {
275 log.warn("No IP V4 server address found.");
276 return; // No IP V6 address found
277 }
278 // if (!serverInfoList.isEmpty()) {
279 for (DhcpServerInfo oldServerInfo : serverInfoList) {
280 log.info("In for (DhcpServerInfo oldServerInfo : serverInfoList) {");
Yi Tseng919b2df2017-09-07 16:22:51 -0700281 // remove old server info
rsahot036620655b2018-02-26 15:01:37 -0500282 //DhcpServerInfo oldServerInfo = serverInfoList.remove(0);
Yi Tseng483ac6f2017-08-02 15:03:31 -0700283
Yi Tseng919b2df2017-09-07 16:22:51 -0700284 // stop monitoring gateway or server
285 oldServerInfo.getDhcpGatewayIp4().ifPresent(gatewayIp -> {
286 hostService.stopMonitoringIp(gatewayIp);
287 });
288 oldServerInfo.getDhcpServerIp4().ifPresent(serverIp -> {
289 hostService.stopMonitoringIp(serverIp);
Yi Tseng525ff402017-10-23 19:39:39 -0700290 cancelDhcpPacket(serverIp);
Yi Tseng919b2df2017-09-07 16:22:51 -0700291 });
Yi Tseng483ac6f2017-08-02 15:03:31 -0700292 }
Yi Tseng3df7f9d2017-08-17 13:08:31 -0700293
Yi Tseng919b2df2017-09-07 16:22:51 -0700294 // Create new server info according to the config
rsahot036620655b2018-02-26 15:01:37 -0500295 serverInfoList.clear();
296 for (DhcpServerConfig serverConfig : configs) {
297 log.info("// Create new server info according to the config");
298 DhcpServerInfo newServerInfo = new DhcpServerInfo(serverConfig,
299 DhcpServerInfo.Version.DHCP_V4);
300 checkState(newServerInfo.getDhcpServerConnectPoint().isPresent(),
301 "Connect point not exists");
302 checkState(newServerInfo.getDhcpServerIp4().isPresent(),
303 "IP of DHCP server not exists");
Yi Tseng4f2a0462017-08-31 11:21:00 -0700304
rsahot036620655b2018-02-26 15:01:37 -0500305 log.debug("DHCP server connect point: {}", newServerInfo.getDhcpServerConnectPoint().orElse(null));
306 log.debug("DHCP server IP: {}", newServerInfo.getDhcpServerIp4().orElse(null));
Yi Tseng919b2df2017-09-07 16:22:51 -0700307
rsahot036620655b2018-02-26 15:01:37 -0500308 Ip4Address serverIp = newServerInfo.getDhcpServerIp4().get();
309 Ip4Address ipToProbe;
310 if (newServerInfo.getDhcpGatewayIp4().isPresent()) {
311 ipToProbe = newServerInfo.getDhcpGatewayIp4().get();
312 } else {
313 ipToProbe = newServerInfo.getDhcpServerIp4().orElse(null);
314 }
315 log.info("Probe_IP {}", ipToProbe);
316 String hostToProbe = newServerInfo.getDhcpGatewayIp4()
317 .map(ip -> "gateway").orElse("server");
318
319 log.debug("Probing to resolve {} IP {}", hostToProbe, ipToProbe);
320 hostService.startMonitoringIp(ipToProbe);
321
322 Set<Host> hosts = hostService.getHostsByIp(ipToProbe);
323 if (!hosts.isEmpty()) {
324 Host host = hosts.iterator().next();
325 newServerInfo.setDhcpConnectVlan(host.vlan());
326 newServerInfo.setDhcpConnectMac(host.mac());
327 }
328
329 // Add new server info
330 synchronized (this) {
331 //serverInfoList.clear();
332 serverInfoList.add(newServerInfo);
333 }
334
335 requestDhcpPacket(serverIp);
Yi Tseng4f2a0462017-08-31 11:21:00 -0700336 }
Yi Tseng483ac6f2017-08-02 15:03:31 -0700337 }
338
Yi Tseng3df7f9d2017-08-17 13:08:31 -0700339 @Override
Yi Tseng51301292017-07-28 13:02:59 -0700340 public void processDhcpPacket(PacketContext context, BasePacket payload) {
341 checkNotNull(payload, "DHCP payload can't be null");
342 checkState(payload instanceof DHCP, "Payload is not a DHCP");
343 DHCP dhcpPayload = (DHCP) payload;
344 if (!configured()) {
Yi Tseng919b2df2017-09-07 16:22:51 -0700345 log.warn("Missing default DHCP relay server config. Abort packet processing");
Yi Tseng51301292017-07-28 13:02:59 -0700346 return;
347 }
348
349 ConnectPoint inPort = context.inPacket().receivedFrom();
Yi Tseng51301292017-07-28 13:02:59 -0700350 checkNotNull(dhcpPayload, "Can't find DHCP payload");
351 Ethernet packet = context.inPacket().parsed();
352 DHCP.MsgType incomingPacketType = dhcpPayload.getOptions().stream()
353 .filter(dhcpOption -> dhcpOption.getCode() == OptionCode_MessageType.getValue())
354 .map(DhcpOption::getData)
355 .map(data -> DHCP.MsgType.getType(data[0]))
356 .findFirst()
357 .orElse(null);
358 checkNotNull(incomingPacketType, "Can't get message type from DHCP payload {}", dhcpPayload);
rsahot036620655b2018-02-26 15:01:37 -0500359 Set<Interface> receivingInterfaces = interfaceService.getInterfacesByPort(inPort);
360 //ignore the packets if dhcp client interface is not configured on onos.
361 if (receivingInterfaces.isEmpty()) {
362 log.warn("Virtual interface is not configured on {}", inPort);
363 return;
364 }
Yi Tseng51301292017-07-28 13:02:59 -0700365 switch (incomingPacketType) {
366 case DHCPDISCOVER:
Yi Tsengdcef2c22017-08-05 20:34:06 -0700367 // Add the gateway IP as virtual interface IP for server to understand
Yi Tseng51301292017-07-28 13:02:59 -0700368 // the lease to be assigned and forward the packet to dhcp server.
rsahot036620655b2018-02-26 15:01:37 -0500369 List<InternalPacket> ethernetClientPacket =
370 processDhcpPacketFromClient(context, packet, receivingInterfaces);
371 for (InternalPacket internalPacket : ethernetClientPacket) {
372 log.debug("DHCPDISCOVER from {} Forward to server", inPort);
Yi Tseng51301292017-07-28 13:02:59 -0700373 writeRequestDhcpRecord(inPort, packet, dhcpPayload);
rsahot036620655b2018-02-26 15:01:37 -0500374 forwardPacket(internalPacket);
Yi Tseng51301292017-07-28 13:02:59 -0700375 }
376 break;
377 case DHCPOFFER:
378 //reply to dhcp client.
rsahot036620655b2018-02-26 15:01:37 -0500379 Ethernet ethernetPacketOffer = processDhcpPacketFromServer(context, packet);
Yi Tseng51301292017-07-28 13:02:59 -0700380 if (ethernetPacketOffer != null) {
381 writeResponseDhcpRecord(ethernetPacketOffer, dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -0700382 sendResponseToClient(ethernetPacketOffer, dhcpPayload);
Yi Tseng51301292017-07-28 13:02:59 -0700383 }
384 break;
385 case DHCPREQUEST:
386 // add the gateway ip as virtual interface ip for server to understand
387 // the lease to be assigned and forward the packet to dhcp server.
rsahot036620655b2018-02-26 15:01:37 -0500388 List<InternalPacket> ethernetPacketRequest =
389 processDhcpPacketFromClient(context, packet, receivingInterfaces);
390 for (InternalPacket internalPacket : ethernetPacketRequest) {
391 log.debug("DHCPDISCOVER from {} Forward to server", inPort);
Yi Tseng51301292017-07-28 13:02:59 -0700392 writeRequestDhcpRecord(inPort, packet, dhcpPayload);
rsahot036620655b2018-02-26 15:01:37 -0500393 forwardPacket(internalPacket);
Yi Tseng51301292017-07-28 13:02:59 -0700394 }
395 break;
Charles Chand0dd7002017-10-08 23:53:36 -0400396 case DHCPDECLINE:
397 break;
Yi Tseng51301292017-07-28 13:02:59 -0700398 case DHCPACK:
399 // reply to dhcp client.
rsahot036620655b2018-02-26 15:01:37 -0500400 Ethernet ethernetPacketAck = processDhcpPacketFromServer(context, packet);
Yi Tseng51301292017-07-28 13:02:59 -0700401 if (ethernetPacketAck != null) {
402 writeResponseDhcpRecord(ethernetPacketAck, dhcpPayload);
403 handleDhcpAck(ethernetPacketAck, dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -0700404 sendResponseToClient(ethernetPacketAck, dhcpPayload);
Yi Tseng51301292017-07-28 13:02:59 -0700405 }
406 break;
Charles Chand0dd7002017-10-08 23:53:36 -0400407 case DHCPNAK:
408 break;
Yi Tseng51301292017-07-28 13:02:59 -0700409 case DHCPRELEASE:
410 // TODO: release the ip address from client
411 break;
Charles Chand0dd7002017-10-08 23:53:36 -0400412 case DHCPINFORM:
413 break;
414 case DHCPFORCERENEW:
415 break;
416 case DHCPLEASEQUERY:
417 handleLeaseQueryMsg(context, packet, dhcpPayload);
418 break;
419 case DHCPLEASEACTIVE:
420 handleLeaseQueryActivateMsg(packet, dhcpPayload);
421 break;
422 case DHCPLEASEUNASSIGNED:
423 case DHCPLEASEUNKNOWN:
424 handleLeaseQueryUnknown(packet, dhcpPayload);
425 break;
Yi Tseng51301292017-07-28 13:02:59 -0700426 default:
427 break;
428 }
429 }
430
431 /**
432 * Checks if this app has been configured.
433 *
434 * @return true if all information we need have been initialized
435 */
Yi Tseng4f2a0462017-08-31 11:21:00 -0700436 private boolean configured() {
Yi Tseng919b2df2017-09-07 16:22:51 -0700437 return !defaultServerInfoList.isEmpty();
Yi Tseng51301292017-07-28 13:02:59 -0700438 }
439
440 /**
Yi Tsengdcef2c22017-08-05 20:34:06 -0700441 * Returns the first interface ip from interface.
Yi Tseng51301292017-07-28 13:02:59 -0700442 *
Yi Tsengdcef2c22017-08-05 20:34:06 -0700443 * @param iface interface of one connect point
Yi Tseng51301292017-07-28 13:02:59 -0700444 * @return the first interface IP; null if not exists an IP address in
445 * these interfaces
446 */
Yi Tseng3df7f9d2017-08-17 13:08:31 -0700447 private Ip4Address getFirstIpFromInterface(Interface iface) {
Yi Tsengdcef2c22017-08-05 20:34:06 -0700448 checkNotNull(iface, "Interface can't be null");
449 return iface.ipAddressesList().stream()
Yi Tseng51301292017-07-28 13:02:59 -0700450 .map(InterfaceIpAddress::ipAddress)
451 .filter(IpAddress::isIp4)
452 .map(IpAddress::getIp4Address)
453 .findFirst()
454 .orElse(null);
455 }
456
457 /**
Yi Tseng4f2a0462017-08-31 11:21:00 -0700458 * Gets Interface facing to the server for default host.
Yi Tsengdcef2c22017-08-05 20:34:06 -0700459 *
460 * @return the Interface facing to the server; null if not found
461 */
Yi Tseng919b2df2017-09-07 16:22:51 -0700462 private Interface getDefaultServerInterface() {
463 return getServerInterface(defaultServerInfoList);
Yi Tsengdcef2c22017-08-05 20:34:06 -0700464 }
465
466 /**
Yi Tseng4f2a0462017-08-31 11:21:00 -0700467 * Gets Interface facing to the server for indirect hosts.
468 * Use default server Interface if indirect server not configured.
469 *
470 * @return the Interface facing to the server; null if not found
471 */
472 private Interface getIndirectServerInterface() {
Yi Tseng919b2df2017-09-07 16:22:51 -0700473 return getServerInterface(indirectServerInfoList);
474 }
475
476 private Interface getServerInterface(List<DhcpServerInfo> serverInfos) {
Yi Tseng3bd57ac2017-11-29 14:39:18 -0800477 return serverInfos.stream()
Yi Tseng4f2a0462017-08-31 11:21:00 -0700478 .findFirst()
Yi Tseng3bd57ac2017-11-29 14:39:18 -0800479 .map(serverInfo -> {
480 ConnectPoint dhcpServerConnectPoint =
481 serverInfo.getDhcpServerConnectPoint().orElse(null);
482 VlanId dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
483 if (dhcpServerConnectPoint == null || dhcpConnectVlan == null) {
484 return null;
485 }
486 return interfaceService.getInterfacesByPort(dhcpServerConnectPoint)
487 .stream()
488 .filter(iface -> interfaceContainsVlan(iface, dhcpConnectVlan))
489 .findFirst()
490 .orElse(null);
491 })
Yi Tseng4f2a0462017-08-31 11:21:00 -0700492 .orElse(null);
493 }
494
495 /**
496 * Determind if an Interface contains a vlan id.
497 *
498 * @param iface the Interface
499 * @param vlanId the vlan id
500 * @return true if the Interface contains the vlan id
501 */
502 private boolean interfaceContainsVlan(Interface iface, VlanId vlanId) {
Yi Tseng4025a102017-09-30 11:35:42 +0800503 if (vlanId.equals(VlanId.NONE)) {
504 // untagged packet, check if vlan untagged or vlan native is not NONE
505 return !iface.vlanUntagged().equals(VlanId.NONE) ||
506 !iface.vlanNative().equals(VlanId.NONE);
507 }
508 // tagged packet, check if the interface contains the vlan
509 return iface.vlanTagged().contains(vlanId);
Yi Tseng4f2a0462017-08-31 11:21:00 -0700510 }
511
Charles Chand0dd7002017-10-08 23:53:36 -0400512 private void handleLeaseQueryActivateMsg(Ethernet packet, DHCP dhcpPayload) {
513 log.debug("LQ: Got DHCPLEASEACTIVE packet!");
514
515 // TODO: release the ip address from client
516 MacAddress clientMacAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
517 VlanId vlanId = VlanId.vlanId(packet.getVlanID());
518 HostId hostId = HostId.hostId(clientMacAddress, vlanId);
519 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
520
521 if (record == null) {
522 log.warn("Can't find record for host {} when processing DHCPLEASEACTIVE", hostId);
523 return;
524 }
525
526 // need to update routes
527 log.debug("Lease Query for Client results in DHCPLEASEACTIVE - route needs to be modified");
528 // get current route
529 // find the ip of that client with the DhcpRelay store
530
531 Ip4Address clientIP = record.ip4Address().orElse(null);
532 log.debug("LQ: IP of host is " + clientIP.getIp4Address());
533
534 MacAddress nextHopMac = record.nextHop().orElse(null);
535 log.debug("LQ: MAC of resulting *OLD* NH for that host is " + nextHopMac.toString());
536
537 // find the new NH by looking at the src MAC of the dhcp request
538 // from the LQ store
539 MacAddress newNextHopMac = record.nextHopTemp().orElse(null);
540 log.debug("LQ: MAC of resulting *NEW* NH for that host is " + newNextHopMac.toString());
541
542 log.debug("LQ: updating dhcp relay record with new NH");
543 record.nextHop(newNextHopMac);
544
545 // find the next hop IP from its mac
546 HostId gwHostId = HostId.hostId(newNextHopMac, vlanId);
547 Host gwHost = hostService.getHost(gwHostId);
548
549 if (gwHost == null) {
550 log.warn("Can't find gateway for new NH host " + gwHostId);
551 return;
552 }
553
554 Ip4Address nextHopIp = gwHost.ipAddresses()
555 .stream()
556 .filter(IpAddress::isIp4)
557 .map(IpAddress::getIp4Address)
558 .findFirst()
559 .orElse(null);
560
561 if (nextHopIp == null) {
562 log.warn("Can't find IP address of gateway " + gwHost);
563 return;
564 }
565
566 log.debug("LQ: *NEW* NH IP for host is " + nextHopIp.getIp4Address());
567 Route route = new Route(Route.Source.STATIC, clientIP.toIpPrefix(), nextHopIp);
568 routeStore.updateRoute(route);
569
570 // and forward to client
571 Ethernet ethernetPacket = processLeaseQueryFromServer(packet);
572 if (ethernetPacket != null) {
573 sendResponseToClient(ethernetPacket, dhcpPayload);
574 }
575 }
576
577 /**
578 *
579 */
580 private void handleLeaseQueryMsg(PacketContext context, Ethernet packet, DHCP dhcpPayload) {
581 log.debug("LQ: Got DHCPLEASEQUERY packet!");
582 MacAddress clientMacAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
583 log.debug("LQ: got DHCPLEASEQUERY with MAC " + clientMacAddress.toString());
584 // add the client mac (hostid) of this request to a store (the entry will be removed with
585 // the reply sent to the originator)
586 VlanId vlanId = VlanId.vlanId(packet.getVlanID());
587 HostId hId = HostId.hostId(clientMacAddress, vlanId);
588 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hId).orElse(null);
589 if (record != null) {
590 //new NH is to be taken from src mac of LQ packet
591 MacAddress newNextHop = packet.getSourceMAC();
592 record.nextHopTemp(newNextHop);
593 record.ip4Status(dhcpPayload.getPacketType());
594 record.updateLastSeen();
595
596 // do a basic routing of the packet (this is unicast routing
597 // not a relay operation like for other broadcast dhcp packets
rsahot036620655b2018-02-26 15:01:37 -0500598 List<InternalPacket> ethernetPacketRequest = processLeaseQueryFromAgent(context, packet);
Charles Chand0dd7002017-10-08 23:53:36 -0400599 // and forward to server
rsahot036620655b2018-02-26 15:01:37 -0500600 for (InternalPacket internalPacket : ethernetPacketRequest) {
601 log.debug("LeaseQueryMsg forward to server");
602 forwardPacket(internalPacket);
603 }
Charles Chand0dd7002017-10-08 23:53:36 -0400604 } else {
605 log.warn("LQ: Error! - DHCP relay record for that client not found - ignoring LQ!");
606 }
607 }
608
609 private void handleLeaseQueryUnknown(Ethernet packet, DHCP dhcpPayload) {
610 log.debug("Lease Query for Client results in DHCPLEASEUNASSIGNED or " +
611 "DHCPLEASEUNKNOWN - removing route & forwarding reply to originator");
612 MacAddress clientMacAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
613 VlanId vlanId = VlanId.vlanId(packet.getVlanID());
614 HostId hostId = HostId.hostId(clientMacAddress, vlanId);
615 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
616
617 if (record == null) {
618 log.warn("Can't find record for host {} when handling LQ UNKNOWN/UNASSIGNED message", hostId);
619 return;
620 }
621
622 Ip4Address clientIP = record.ip4Address().orElse(null);
623 log.debug("LQ: IP of host is " + clientIP.getIp4Address());
624
625 // find the new NH by looking at the src MAC of the dhcp request
626 // from the LQ store
627 MacAddress nextHopMac = record.nextHop().orElse(null);
628 log.debug("LQ: MAC of resulting *Existing* NH for that route is " + nextHopMac.toString());
629
630 // find the next hop IP from its mac
631 HostId gwHostId = HostId.hostId(nextHopMac, vlanId);
632 Host gwHost = hostService.getHost(gwHostId);
633
634 if (gwHost == null) {
635 log.warn("Can't find gateway for new NH host " + gwHostId);
636 return;
637 }
638
639 Ip4Address nextHopIp = gwHost.ipAddresses()
640 .stream()
641 .filter(IpAddress::isIp4)
642 .map(IpAddress::getIp4Address)
643 .findFirst()
644 .orElse(null);
645
646 if (nextHopIp == null) {
647 log.warn("Can't find IP address of gateway {}", gwHost);
648 return;
649 }
650
651 log.debug("LQ: *Existing* NH IP for host is " + nextHopIp.getIp4Address() + " removing route for it");
652 Route route = new Route(Route.Source.STATIC, clientIP.toIpPrefix(), nextHopIp);
653 routeStore.removeRoute(route);
654
655 // remove from temp store
656 dhcpRelayStore.removeDhcpRecord(hostId);
657
658 // and forward to client
659 Ethernet ethernetPacket = processLeaseQueryFromServer(packet);
660 if (ethernetPacket != null) {
661 sendResponseToClient(ethernetPacket, dhcpPayload);
662 }
663 }
664
Yi Tseng4f2a0462017-08-31 11:21:00 -0700665 /**
Yi Tseng51301292017-07-28 13:02:59 -0700666 * Build the DHCP discover/request packet with gateway IP(unicast packet).
667 *
668 * @param context the packet context
669 * @param ethernetPacket the ethernet payload to process
Yi Tseng51301292017-07-28 13:02:59 -0700670 * @return processed packet
671 */
rsahot036620655b2018-02-26 15:01:37 -0500672 private List<InternalPacket> processDhcpPacketFromClient(PacketContext context,
673 Ethernet ethernetPacket,
674 Set<Interface> clientInterfaces) {
Yi Tseng25bfe372017-11-03 16:27:32 -0700675 ConnectPoint receivedFrom = context.inPacket().receivedFrom();
676 DeviceId receivedFromDevice = receivedFrom.deviceId();
rsahot036620655b2018-02-26 15:01:37 -0500677 Ip4Address relayAgentIp = null;
678 relayAgentIp = dhcp4HandlerUtil.getRelayAgentIPv4Address(clientInterfaces);
679 MacAddress relayAgentMac = clientInterfaces.iterator().next().mac();
680 if (relayAgentIp == null || relayAgentMac == null) {
681 log.warn("Missing DHCP relay agent interface Ipv4 addr config for "
682 + "packet from client on port: {}. Aborting packet processing",
683 clientInterfaces.iterator().next().connectPoint());
684 return null;
685 }
686 log.debug("Multi DHCP V4 processDhcpPacketFromClient on port {}",
687 clientInterfaces.iterator().next().connectPoint());
Yi Tseng25bfe372017-11-03 16:27:32 -0700688
Yi Tseng4f2a0462017-08-31 11:21:00 -0700689 // get dhcp header.
rsahot036620655b2018-02-26 15:01:37 -0500690 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
Yi Tseng4f2a0462017-08-31 11:21:00 -0700691 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
692 UDP udpPacket = (UDP) ipv4Packet.getPayload();
693 DHCP dhcpPacket = (DHCP) udpPacket.getPayload();
694
Yi Tseng919b2df2017-09-07 16:22:51 -0700695
Yi Tsengdcef2c22017-08-05 20:34:06 -0700696 Ip4Address clientInterfaceIp =
697 interfaceService.getInterfacesByPort(context.inPacket().receivedFrom())
698 .stream()
699 .map(Interface::ipAddressesList)
700 .flatMap(Collection::stream)
701 .map(InterfaceIpAddress::ipAddress)
702 .filter(IpAddress::isIp4)
703 .map(IpAddress::getIp4Address)
704 .findFirst()
705 .orElse(null);
706 if (clientInterfaceIp == null) {
707 log.warn("Can't find interface IP for client interface for port {}",
rsahot036620655b2018-02-26 15:01:37 -0500708 context.inPacket().receivedFrom());
Yi Tsengdcef2c22017-08-05 20:34:06 -0700709 return null;
710 }
rsahot036620655b2018-02-26 15:01:37 -0500711
Yi Tseng4f2a0462017-08-31 11:21:00 -0700712 boolean isDirectlyConnected = directlyConnected(dhcpPacket);
rsahot036620655b2018-02-26 15:01:37 -0500713 boolean directConnFlag = directlyConnected(dhcpPacket);
714
715 // Multi DHCP Start
716 ConnectPoint clientConnectionPoint = context.inPacket().receivedFrom();
717 VlanId vlanIdInUse = VlanId.vlanId(ethernetPacket.getVlanID());
718 Interface clientInterface = interfaceService.getInterfacesByPort(clientConnectionPoint)
719 .stream().filter(iface -> dhcp4HandlerUtil.interfaceContainsVlan(iface, vlanIdInUse))
720 .findFirst()
721 .orElse(null);
722
723 List<InternalPacket> internalPackets = new ArrayList<>();
724 List<DhcpServerInfo> serverInfoList = findValidServerInfo(directConnFlag);
725 List<DhcpServerInfo> copyServerInfoList = new ArrayList<DhcpServerInfo>(serverInfoList);
726
727
728 for (DhcpServerInfo serverInfo : copyServerInfoList) {
729 etherReply = (Ethernet) ethernetPacket.clone();
730 ipv4Packet = (IPv4) etherReply.getPayload();
731 udpPacket = (UDP) ipv4Packet.getPayload();
732 dhcpPacket = (DHCP) udpPacket.getPayload();
733 if (!checkDhcpServerConnPt(directConnFlag, serverInfo)) {
734 log.warn("Can't get server connect point, ignore");
735 continue;
736 }
737 DhcpServerInfo newServerInfo = getHostInfoForServerInfo(serverInfo, serverInfoList);
738 if (newServerInfo == null) {
739 log.warn("Can't get server interface with host info resolved, ignore");
740 continue;
741 }
742
743 Interface serverInterface = getServerInterface(newServerInfo);
Yi Tseng3bd57ac2017-11-29 14:39:18 -0800744 if (serverInterface == null) {
rsahot036620655b2018-02-26 15:01:37 -0500745 log.warn("Can't get server interface, ignore");
746 continue;
Yi Tseng3bd57ac2017-11-29 14:39:18 -0800747 }
Yi Tseng4f2a0462017-08-31 11:21:00 -0700748
rsahot036620655b2018-02-26 15:01:37 -0500749 Ip4Address ipFacingServer = getFirstIpFromInterface(serverInterface);
750 MacAddress macFacingServer = serverInterface.mac();
751 log.debug("Interfacing server {} Mac : {} ", ipFacingServer, macFacingServer);
752 if (ipFacingServer == null || macFacingServer == null) {
753 log.warn("No IP address for server Interface {}", serverInterface);
754 //return null;
755 continue;
756 }
Yi Tseng51301292017-07-28 13:02:59 -0700757
Charles Chand0d1e332017-10-10 16:53:32 -0400758
rsahot036620655b2018-02-26 15:01:37 -0500759 etherReply.setSourceMACAddress(macFacingServer);
760 // set default info and replace with indirect if available later on.
761 if (newServerInfo.getDhcpConnectMac().isPresent()) {
762 etherReply.setDestinationMACAddress(newServerInfo.getDhcpConnectMac().get());
763 }
764 if (newServerInfo.getDhcpConnectVlan().isPresent()) {
765 etherReply.setVlanID(newServerInfo.getDhcpConnectVlan().get().toShort());
766 }
767 ipv4Packet.setSourceAddress(ipFacingServer.toInt());
768 ipv4Packet.setDestinationAddress(newServerInfo.getDhcpServerIp4().get().toInt());
769 log.info("Directly connected {}", isDirectlyConnected);
770 log.info("Dhcp Server IP: {}", newServerInfo.getDhcpServerIp4().get());
771 if (isDirectlyConnected) {
Yi Tseng51301292017-07-28 13:02:59 -0700772
rsahot036620655b2018-02-26 15:01:37 -0500773 log.info("**Default****Dhcp Server IP: {}", newServerInfo.getDhcpServerIp4().get());
774 if (newServerInfo.getDhcpConnectMac().isPresent()) {
775 etherReply.setDestinationMACAddress(newServerInfo.getDhcpConnectMac().get());
Charles Chand0d1e332017-10-10 16:53:32 -0400776 }
rsahot036620655b2018-02-26 15:01:37 -0500777 if (newServerInfo.getDhcpConnectVlan().isPresent()) {
778 etherReply.setVlanID(newServerInfo.getDhcpConnectVlan().get().toShort());
779 }
780
781 ipv4Packet.setDestinationAddress(newServerInfo.getDhcpServerIp4().get().toInt());
782
783
784 ConnectPoint inPort = context.inPacket().receivedFrom();
785 VlanId vlanId = VlanId.vlanId(ethernetPacket.getVlanID());
786 // add connected in port and vlan
787 CircuitId cid = new CircuitId(inPort.toString(), vlanId);
788 byte[] circuitId = cid.serialize();
789 DhcpOption circuitIdSubOpt = new DhcpOption();
790 circuitIdSubOpt
791 .setCode(CIRCUIT_ID.getValue())
792 .setLength((byte) circuitId.length)
793 .setData(circuitId);
794
795 DhcpRelayAgentOption newRelayAgentOpt = new DhcpRelayAgentOption();
796 newRelayAgentOpt.setCode(OptionCode_CircuitID.getValue());
797 newRelayAgentOpt.addSubOption(circuitIdSubOpt);
798
799 // Removes END option first
800 List<DhcpOption> options = dhcpPacket.getOptions().stream()
801 .filter(opt -> opt.getCode() != OptionCode_END.getValue())
802 .collect(Collectors.toList());
803
804 // push relay agent option
805 options.add(newRelayAgentOpt);
806
807 // make sure option 255(End) is the last option
808 DhcpOption endOption = new DhcpOption();
809 endOption.setCode(OptionCode_END.getValue());
810 options.add(endOption);
811
812 dhcpPacket.setOptions(options);
813
814 relayAgentIp = serverInfo.getRelayAgentIp4(receivedFromDevice).orElse(null);
815
816 // Sets relay agent IP
817 int effectiveRelayAgentIp = relayAgentIp != null ?
818 relayAgentIp.toInt() : clientInterfaceIp.toInt();
819 dhcpPacket.setGatewayIPAddress(effectiveRelayAgentIp);
820 log.info("In Default, Relay Agent IP {}", effectiveRelayAgentIp);
Charles Chand0d1e332017-10-10 16:53:32 -0400821 } else {
rsahot036620655b2018-02-26 15:01:37 -0500822 if (!newServerInfo.getDhcpServerIp4().isPresent()) {
823 // do nothing
824 } else if (!newServerInfo.getDhcpConnectMac().isPresent()) {
825 continue;
826 } else {
827 relayAgentIp = newServerInfo.getRelayAgentIp4(receivedFromDevice).orElse(null);
828 // Sets relay agent IP
829 int effectiveRelayAgentIp = relayAgentIp != null ?
830 relayAgentIp.toInt() : clientInterfaceIp.toInt();
831 dhcpPacket.setGatewayIPAddress(effectiveRelayAgentIp);
Charles Chand0d1e332017-10-10 16:53:32 -0400832 }
Yi Tseng4f2a0462017-08-31 11:21:00 -0700833 }
Yi Tseng3df7f9d2017-08-17 13:08:31 -0700834
rsahot036620655b2018-02-26 15:01:37 -0500835 // Remove broadcast flag
836 dhcpPacket.setFlags((short) 0);
837
838 udpPacket.setPayload(dhcpPacket);
839 // As a DHCP relay, the source port should be server port( instead
840 // of client port.
841 udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
842 udpPacket.setDestinationPort(UDP.DHCP_SERVER_PORT);
843 ipv4Packet.setPayload(udpPacket);
844 ipv4Packet.setTtl((byte) 64);
845 etherReply.setPayload(ipv4Packet);
846 InternalPacket internalPacket = new Dhcp4HandlerUtil().new InternalPacket(etherReply,
847 serverInfo.getDhcpServerConnectPoint().get());
848 internalPackets.add(internalPacket);
849 }
850 return internalPackets;
Yi Tseng51301292017-07-28 13:02:59 -0700851 }
852
Charles Chand0dd7002017-10-08 23:53:36 -0400853
854 /**
855 * Do a basic routing for a packet from client (used for LQ processing).
856 *
857 * @param context the packet context
858 * @param ethernetPacket the ethernet payload to process
859 * @return processed packet
860 */
rsahot036620655b2018-02-26 15:01:37 -0500861 private List<InternalPacket> processLeaseQueryFromAgent(PacketContext context,
862 Ethernet ethernetPacket) {
863 ConnectPoint receivedFrom = context.inPacket().receivedFrom();
864 DeviceId receivedFromDevice = receivedFrom.deviceId();
865
Charles Chand0dd7002017-10-08 23:53:36 -0400866 // get dhcp header.
867 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
868 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
869 UDP udpPacket = (UDP) ipv4Packet.getPayload();
870 DHCP dhcpPacket = (DHCP) udpPacket.getPayload();
871
rsahot036620655b2018-02-26 15:01:37 -0500872 Ip4Address relayAgentIp = null;
873
874
Charles Chand0dd7002017-10-08 23:53:36 -0400875 VlanId dhcpConnectVlan = null;
876 MacAddress dhcpConnectMac = null;
877 Ip4Address dhcpServerIp = null;
878
879 VlanId indirectDhcpConnectVlan = null;
880 MacAddress indirectDhcpConnectMac = null;
881 Ip4Address indirectDhcpServerIp = null;
882
Charles Chand0dd7002017-10-08 23:53:36 -0400883 Ip4Address clientInterfaceIp =
884 interfaceService.getInterfacesByPort(context.inPacket().receivedFrom())
885 .stream()
886 .map(Interface::ipAddressesList)
887 .flatMap(Collection::stream)
888 .map(InterfaceIpAddress::ipAddress)
889 .filter(IpAddress::isIp4)
890 .map(IpAddress::getIp4Address)
891 .findFirst()
892 .orElse(null);
893 if (clientInterfaceIp == null) {
894 log.warn("Can't find interface IP for client interface for port {}",
rsahot036620655b2018-02-26 15:01:37 -0500895 context.inPacket().receivedFrom());
Charles Chand0dd7002017-10-08 23:53:36 -0400896 return null;
897 }
rsahot036620655b2018-02-26 15:01:37 -0500898
Charles Chand0dd7002017-10-08 23:53:36 -0400899 boolean isDirectlyConnected = directlyConnected(dhcpPacket);
rsahot036620655b2018-02-26 15:01:37 -0500900 boolean directConnFlag = directlyConnected(dhcpPacket);
901
902 // Multi DHCP Start
903 ConnectPoint clientConnectionPoint = context.inPacket().receivedFrom();
904 VlanId vlanIdInUse = VlanId.vlanId(ethernetPacket.getVlanID());
905 Interface clientInterface = interfaceService.getInterfacesByPort(clientConnectionPoint)
906 .stream().filter(iface -> dhcp4HandlerUtil.interfaceContainsVlan(iface, vlanIdInUse))
907 .findFirst()
908 .orElse(null);
909
910 List<InternalPacket> internalPackets = new ArrayList<>();
911 List<DhcpServerInfo> serverInfoList = findValidServerInfo(directConnFlag);
912 List<DhcpServerInfo> copyServerInfoList = new ArrayList<DhcpServerInfo>(serverInfoList);
913
914 for (DhcpServerInfo serverInfo : copyServerInfoList) {
915 // get dhcp header.
916 etherReply = (Ethernet) ethernetPacket.clone();
917 ipv4Packet = (IPv4) etherReply.getPayload();
918 udpPacket = (UDP) ipv4Packet.getPayload();
919 dhcpPacket = (DHCP) udpPacket.getPayload();
920
921 if (!checkDhcpServerConnPt(directConnFlag, serverInfo)) {
922 log.warn("Can't get server connect point, ignore");
923 continue;
Yi Tseng3bd57ac2017-11-29 14:39:18 -0800924 }
rsahot036620655b2018-02-26 15:01:37 -0500925 DhcpServerInfo newServerInfo = getHostInfoForServerInfo(serverInfo, serverInfoList);
926 if (newServerInfo == null) {
927 log.warn("Can't get server interface with host info resolved, ignore");
928 continue;
929 }
Charles Chand0dd7002017-10-08 23:53:36 -0400930
rsahot036620655b2018-02-26 15:01:37 -0500931 Interface serverInterface = getServerInterface(newServerInfo);
932 if (serverInterface == null) {
933 log.warn("Can't get server interface, ignore");
934 continue;
935 }
936 Ip4Address ipFacingServer = getFirstIpFromInterface(serverInterface);
937 MacAddress macFacingServer = serverInterface.mac();
938 if (ipFacingServer == null || macFacingServer == null) {
939 log.warn("No IP address for server Interface {}", serverInterface);
940 continue;
941 }
Charles Chand0dd7002017-10-08 23:53:36 -0400942
rsahot036620655b2018-02-26 15:01:37 -0500943 etherReply.setSourceMACAddress(macFacingServer);
944 etherReply.setDestinationMACAddress(dhcpConnectMac);
945 etherReply.setVlanID(dhcpConnectVlan.toShort());
946 ipv4Packet.setSourceAddress(ipFacingServer.toInt());
947 ipv4Packet.setDestinationAddress(dhcpServerIp.toInt());
948 if (isDirectlyConnected) {
949 // set default info and replace with indirect if available later on.
950 if (newServerInfo.getDhcpConnectMac().isPresent()) {
951 etherReply.setDestinationMACAddress(newServerInfo.getDhcpConnectMac().get());
952 }
953 if (newServerInfo.getDhcpConnectVlan().isPresent()) {
954 etherReply.setVlanID(serverInfo.getDhcpConnectVlan().get().toShort());
955 }
956 relayAgentIp = newServerInfo.getRelayAgentIp4(receivedFromDevice).orElse(null);
957 // Sets relay agent IP
958 int effectiveRelayAgentIp = relayAgentIp != null ?
959 relayAgentIp.toInt() : clientInterfaceIp.toInt();
960 dhcpPacket.setGatewayIPAddress(effectiveRelayAgentIp);
961 } else {
962 if (!newServerInfo.getDhcpServerIp4().isPresent()) {
963 //do nothing
964 } else if (!newServerInfo.getDhcpConnectMac().isPresent()) {
965 continue;
966 } else {
967 relayAgentIp = newServerInfo.getRelayAgentIp4(receivedFromDevice).orElse(null);
968 // Sets relay agent IP
969 int effectiveRelayAgentIp = relayAgentIp != null ?
970 relayAgentIp.toInt() : clientInterfaceIp.toInt();
971 dhcpPacket.setGatewayIPAddress(effectiveRelayAgentIp);
972 dhcpPacket.setGatewayIPAddress(effectiveRelayAgentIp);
973 log.info("Relay Agent IP {}", relayAgentIp);
974 }
975
976 log.info("In Direct");
977 }
978
979 // Remove broadcast flag
980 dhcpPacket.setFlags((short) 0);
981
982 udpPacket.setPayload(dhcpPacket);
983 // As a DHCP relay, the source port should be server port( instead
984 // of client port.
985 udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
986 udpPacket.setDestinationPort(UDP.DHCP_SERVER_PORT);
987 ipv4Packet.setPayload(udpPacket);
988 ipv4Packet.setTtl((byte) 64);
989 etherReply.setPayload(ipv4Packet);
990 ////return etherReply;
991 Dhcp4HandlerUtil.InternalPacket internalPacket = new Dhcp4HandlerUtil().new InternalPacket(etherReply,
992 newServerInfo.getDhcpServerConnectPoint().get());
993 internalPackets.add(internalPacket);
Charles Chand0dd7002017-10-08 23:53:36 -0400994 }
rsahot036620655b2018-02-26 15:01:37 -0500995 log.warn("num of processLeaseQueryFromAgent packets to send is{}", internalPackets.size());
Charles Chand0dd7002017-10-08 23:53:36 -0400996
rsahot036620655b2018-02-26 15:01:37 -0500997 return internalPackets;
Charles Chand0dd7002017-10-08 23:53:36 -0400998 }
999
1000
Yi Tseng51301292017-07-28 13:02:59 -07001001 /**
1002 * Writes DHCP record to the store according to the request DHCP packet (Discover, Request).
1003 *
1004 * @param location the location which DHCP packet comes from
1005 * @param ethernet the DHCP packet
1006 * @param dhcpPayload the DHCP payload
1007 */
1008 private void writeRequestDhcpRecord(ConnectPoint location,
1009 Ethernet ethernet,
1010 DHCP dhcpPayload) {
1011 VlanId vlanId = VlanId.vlanId(ethernet.getVlanID());
1012 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
1013 HostId hostId = HostId.hostId(macAddress, vlanId);
1014 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1015 if (record == null) {
1016 record = new DhcpRecord(HostId.hostId(macAddress, vlanId));
1017 } else {
1018 record = record.clone();
1019 }
1020 record.addLocation(new HostLocation(location, System.currentTimeMillis()));
1021 record.ip4Status(dhcpPayload.getPacketType());
1022 record.setDirectlyConnected(directlyConnected(dhcpPayload));
1023 if (!directlyConnected(dhcpPayload)) {
1024 // Update gateway mac address if the host is not directly connected
1025 record.nextHop(ethernet.getSourceMAC());
1026 }
1027 record.updateLastSeen();
1028 dhcpRelayStore.updateDhcpRecord(HostId.hostId(macAddress, vlanId), record);
1029 }
1030
1031 /**
1032 * Writes DHCP record to the store according to the response DHCP packet (Offer, Ack).
1033 *
1034 * @param ethernet the DHCP packet
1035 * @param dhcpPayload the DHCP payload
1036 */
1037 private void writeResponseDhcpRecord(Ethernet ethernet,
1038 DHCP dhcpPayload) {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001039 Optional<Interface> outInterface = getClientInterface(ethernet, dhcpPayload);
Yi Tseng51301292017-07-28 13:02:59 -07001040 if (!outInterface.isPresent()) {
1041 log.warn("Failed to determine where to send {}", dhcpPayload.getPacketType());
1042 return;
1043 }
1044
1045 Interface outIface = outInterface.get();
1046 ConnectPoint location = outIface.connectPoint();
Yi Tseng4f2a0462017-08-31 11:21:00 -07001047 VlanId vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -07001048 if (vlanId == null) {
1049 vlanId = outIface.vlan();
1050 }
Yi Tseng51301292017-07-28 13:02:59 -07001051 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
1052 HostId hostId = HostId.hostId(macAddress, vlanId);
1053 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1054 if (record == null) {
1055 record = new DhcpRecord(HostId.hostId(macAddress, vlanId));
1056 } else {
1057 record = record.clone();
1058 }
1059 record.addLocation(new HostLocation(location, System.currentTimeMillis()));
1060 if (dhcpPayload.getPacketType() == DHCP.MsgType.DHCPACK) {
1061 record.ip4Address(Ip4Address.valueOf(dhcpPayload.getYourIPAddress()));
1062 }
1063 record.ip4Status(dhcpPayload.getPacketType());
1064 record.setDirectlyConnected(directlyConnected(dhcpPayload));
1065 record.updateLastSeen();
1066 dhcpRelayStore.updateDhcpRecord(HostId.hostId(macAddress, vlanId), record);
1067 }
1068
1069 /**
1070 * Build the DHCP offer/ack with proper client port.
1071 *
1072 * @param ethernetPacket the original packet comes from server
1073 * @return new packet which will send to the client
1074 */
rsahot036620655b2018-02-26 15:01:37 -05001075 private Ethernet processDhcpPacketFromServer(PacketContext context, Ethernet ethernetPacket) {
Yi Tseng51301292017-07-28 13:02:59 -07001076 // get dhcp header.
rsahot036620655b2018-02-26 15:01:37 -05001077 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
Yi Tseng51301292017-07-28 13:02:59 -07001078 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
1079 UDP udpPacket = (UDP) ipv4Packet.getPayload();
1080 DHCP dhcpPayload = (DHCP) udpPacket.getPayload();
1081
1082 // determine the vlanId of the client host - note that this vlan id
1083 // could be different from the vlan in the packet from the server
Yi Tsengdcef2c22017-08-05 20:34:06 -07001084 Interface clientInterface = getClientInterface(ethernetPacket, dhcpPayload).orElse(null);
Yi Tseng51301292017-07-28 13:02:59 -07001085
Yi Tsengdcef2c22017-08-05 20:34:06 -07001086 if (clientInterface == null) {
Yi Tseng51301292017-07-28 13:02:59 -07001087 log.warn("Cannot find the interface for the DHCP {}", dhcpPayload);
1088 return null;
1089 }
Yi Tsengdcef2c22017-08-05 20:34:06 -07001090 VlanId vlanId;
rsahot036620655b2018-02-26 15:01:37 -05001091 ConnectPoint inPort = context.inPacket().receivedFrom();
1092 boolean directConnFlag = directlyConnected(dhcpPayload);
1093 DhcpServerInfo foundServerInfo = findServerInfoFromServer(directConnFlag, inPort);
1094
1095 if (foundServerInfo == null) {
1096 log.warn("Cannot find server info");
1097 return null;
1098 } else {
1099 if (dhcp4HandlerUtil.isServerIpEmpty(foundServerInfo)) {
1100 log.warn("Cannot find server info's ipaddress");
1101 return null;
1102 }
1103 }
Yi Tsengdcef2c22017-08-05 20:34:06 -07001104 if (clientInterface.vlanTagged().isEmpty()) {
1105 vlanId = clientInterface.vlan();
1106 } else {
1107 // might be multiple vlan in same interface
Yi Tseng4f2a0462017-08-31 11:21:00 -07001108 vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -07001109 }
1110 if (vlanId == null) {
1111 vlanId = VlanId.NONE;
1112 }
1113 etherReply.setVlanID(vlanId.toShort());
1114 etherReply.setSourceMACAddress(clientInterface.mac());
Yi Tseng51301292017-07-28 13:02:59 -07001115
Yi Tsengdcef2c22017-08-05 20:34:06 -07001116 if (!directlyConnected(dhcpPayload)) {
1117 // if client is indirectly connected, try use next hop mac address
1118 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
1119 HostId hostId = HostId.hostId(macAddress, vlanId);
Daniel Ginsburgb1dec912018-01-29 11:40:22 -08001120 if (((int) dhcpPayload.getFlags() & 0x8000) == 0x0000) {
1121 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1122 if (record != null) {
1123 // if next hop can be found, use mac address of next hop
1124 record.nextHop().ifPresent(etherReply::setDestinationMACAddress);
1125 } else {
1126 // otherwise, discard the packet
1127 log.warn("Can't find record for host id {}, discard packet", hostId);
1128 return null;
1129 }
Yi Tsengdcef2c22017-08-05 20:34:06 -07001130 } else {
Daniel Ginsburgb1dec912018-01-29 11:40:22 -08001131 etherReply.setDestinationMACAddress(MacAddress.BROADCAST);
Yi Tsengdcef2c22017-08-05 20:34:06 -07001132 }
Yi Tseng1696f562017-08-17 17:43:38 -07001133 } else {
1134 etherReply.setDestinationMACAddress(dhcpPayload.getClientHardwareAddress());
Yi Tsengdcef2c22017-08-05 20:34:06 -07001135 }
1136
Yi Tseng51301292017-07-28 13:02:59 -07001137 // we leave the srcMac from the original packet
Yi Tseng51301292017-07-28 13:02:59 -07001138 // figure out the relay agent IP corresponding to the original request
Yi Tseng3df7f9d2017-08-17 13:08:31 -07001139 Ip4Address ipFacingClient = getFirstIpFromInterface(clientInterface);
1140 if (ipFacingClient == null) {
Yi Tseng51301292017-07-28 13:02:59 -07001141 log.warn("Cannot determine relay agent interface Ipv4 addr for host {}/{}. "
1142 + "Aborting relay for dhcp packet from server {}",
Yi Tsengdcef2c22017-08-05 20:34:06 -07001143 etherReply.getDestinationMAC(), clientInterface.vlan(),
Yi Tseng51301292017-07-28 13:02:59 -07001144 ethernetPacket);
1145 return null;
1146 }
1147 // SRC_IP: relay agent IP
1148 // DST_IP: offered IP
Yi Tseng3df7f9d2017-08-17 13:08:31 -07001149 ipv4Packet.setSourceAddress(ipFacingClient.toInt());
Daniel Ginsburgb1dec912018-01-29 11:40:22 -08001150 if (((int) dhcpPayload.getFlags() & 0x8000) == 0x0000) {
1151 ipv4Packet.setDestinationAddress(dhcpPayload.getYourIPAddress());
1152 } else {
1153 ipv4Packet.setDestinationAddress(BROADCAST_IP);
1154 }
Yi Tseng51301292017-07-28 13:02:59 -07001155 udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
1156 if (directlyConnected(dhcpPayload)) {
1157 udpPacket.setDestinationPort(UDP.DHCP_CLIENT_PORT);
1158 } else {
1159 // forward to another dhcp relay
Yi Tseng93ba53c2017-09-14 13:24:21 -07001160 // FIXME: Currently we assume the DHCP comes from a L2 relay with
1161 // Option 82, this might not work if DHCP message comes from
1162 // L3 relay.
1163 udpPacket.setDestinationPort(UDP.DHCP_CLIENT_PORT);
Yi Tseng51301292017-07-28 13:02:59 -07001164 }
1165
1166 udpPacket.setPayload(dhcpPayload);
1167 ipv4Packet.setPayload(udpPacket);
1168 etherReply.setPayload(ipv4Packet);
1169 return etherReply;
1170 }
1171
Yi Tsengdcef2c22017-08-05 20:34:06 -07001172 /**
Charles Chand0dd7002017-10-08 23:53:36 -04001173 * Build the DHCP offer/ack with proper client port.
1174 *
1175 * @param ethernetPacket the original packet comes from server
1176 * @return new packet which will send to the client
1177 */
1178 private Ethernet processLeaseQueryFromServer(Ethernet ethernetPacket) {
1179 // get dhcp header.
1180 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
1181 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
1182 UDP udpPacket = (UDP) ipv4Packet.getPayload();
1183 DHCP dhcpPayload = (DHCP) udpPacket.getPayload();
1184
1185 // determine the vlanId of the client host - note that this vlan id
1186 // could be different from the vlan in the packet from the server
1187 Interface clientInterface = getClientInterface(ethernetPacket, dhcpPayload).orElse(null);
1188
1189 if (clientInterface == null) {
1190 log.warn("Cannot find the interface for the DHCP {}", dhcpPayload);
1191 return null;
1192 }
1193 VlanId vlanId;
1194 if (clientInterface.vlanTagged().isEmpty()) {
1195 vlanId = clientInterface.vlan();
1196 } else {
1197 // might be multiple vlan in same interface
1198 vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
1199 }
1200 if (vlanId == null) {
1201 vlanId = VlanId.NONE;
1202 }
1203 etherReply.setVlanID(vlanId.toShort());
1204 etherReply.setSourceMACAddress(clientInterface.mac());
1205
1206 if (!directlyConnected(dhcpPayload)) {
1207 // if client is indirectly connected, try use next hop mac address
1208 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
1209 HostId hostId = HostId.hostId(macAddress, vlanId);
1210 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1211 if (record != null) {
1212 // if next hop can be found, use mac address of next hop
1213 record.nextHop().ifPresent(etherReply::setDestinationMACAddress);
1214 } else {
1215 // otherwise, discard the packet
1216 log.warn("Can't find record for host id {}, discard packet", hostId);
1217 return null;
1218 }
1219 } else {
1220 etherReply.setDestinationMACAddress(dhcpPayload.getClientHardwareAddress());
1221 }
1222
1223 // default is client port
1224 udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
1225 udpPacket.setDestinationPort(UDP.DHCP_CLIENT_PORT);
1226
1227 udpPacket.setPayload(dhcpPayload);
1228 ipv4Packet.setPayload(udpPacket);
1229 etherReply.setPayload(ipv4Packet);
1230 return etherReply;
1231 }
1232 /**
Yi Tsengdcef2c22017-08-05 20:34:06 -07001233 * Extracts VLAN ID from relay agent option.
1234 *
1235 * @param dhcpPayload the DHCP payload
1236 * @return VLAN ID from DHCP payload; null if not exists
1237 */
Yi Tseng4f2a0462017-08-31 11:21:00 -07001238 private VlanId getVlanIdFromRelayAgentOption(DHCP dhcpPayload) {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001239 DhcpRelayAgentOption option = (DhcpRelayAgentOption) dhcpPayload.getOption(OptionCode_CircuitID);
1240 if (option == null) {
1241 return null;
1242 }
1243 DhcpOption circuitIdSubOption = option.getSubOption(CIRCUIT_ID.getValue());
1244 if (circuitIdSubOption == null) {
1245 return null;
1246 }
1247 try {
1248 CircuitId circuitId = CircuitId.deserialize(circuitIdSubOption.getData());
1249 return circuitId.vlanId();
1250 } catch (IllegalArgumentException e) {
1251 // can't deserialize the circuit ID
1252 return null;
1253 }
1254 }
1255
1256 /**
1257 * Removes DHCP relay agent information option (option 82) from DHCP payload.
1258 * Also reset giaddr to 0
1259 *
1260 * @param ethPacket the Ethernet packet to be processed
1261 * @return Ethernet packet processed
1262 */
1263 private Ethernet removeRelayAgentOption(Ethernet ethPacket) {
rsahot036620655b2018-02-26 15:01:37 -05001264 Ethernet ethernet = (Ethernet) ethPacket.duplicate();
Yi Tsengdcef2c22017-08-05 20:34:06 -07001265 IPv4 ipv4 = (IPv4) ethernet.getPayload();
1266 UDP udp = (UDP) ipv4.getPayload();
1267 DHCP dhcpPayload = (DHCP) udp.getPayload();
1268
1269 // removes relay agent information option
1270 List<DhcpOption> options = dhcpPayload.getOptions();
1271 options = options.stream()
1272 .filter(option -> option.getCode() != OptionCode_CircuitID.getValue())
1273 .collect(Collectors.toList());
1274 dhcpPayload.setOptions(options);
1275 dhcpPayload.setGatewayIPAddress(0);
1276
1277 udp.setPayload(dhcpPayload);
1278 ipv4.setPayload(udp);
1279 ethernet.setPayload(ipv4);
1280 return ethernet;
1281 }
1282
Yi Tseng51301292017-07-28 13:02:59 -07001283
1284 /**
1285 * Check if the host is directly connected to the network or not.
1286 *
1287 * @param dhcpPayload the dhcp payload
1288 * @return true if the host is directly connected to the network; false otherwise
1289 */
1290 private boolean directlyConnected(DHCP dhcpPayload) {
Yi Tseng440e2b72017-08-24 14:47:34 -07001291 DhcpRelayAgentOption relayAgentOption =
1292 (DhcpRelayAgentOption) dhcpPayload.getOption(OptionCode_CircuitID);
Yi Tseng51301292017-07-28 13:02:59 -07001293
1294 // Doesn't contains relay option
1295 if (relayAgentOption == null) {
1296 return true;
1297 }
1298
Yi Tseng440e2b72017-08-24 14:47:34 -07001299 // check circuit id, if circuit id is invalid, we say it is an indirect host
1300 DhcpOption circuitIdOpt = relayAgentOption.getSubOption(CIRCUIT_ID.getValue());
Yi Tseng51301292017-07-28 13:02:59 -07001301
Yi Tseng440e2b72017-08-24 14:47:34 -07001302 try {
1303 CircuitId.deserialize(circuitIdOpt.getData());
Yi Tseng51301292017-07-28 13:02:59 -07001304 return true;
Yi Tseng440e2b72017-08-24 14:47:34 -07001305 } catch (Exception e) {
1306 // invalid circuit id
1307 return false;
Yi Tseng51301292017-07-28 13:02:59 -07001308 }
Yi Tseng51301292017-07-28 13:02:59 -07001309 }
1310
1311
1312 /**
1313 * Send the DHCP ack to the requester host.
1314 * Modify Host or Route store according to the type of DHCP.
1315 *
1316 * @param ethernetPacketAck the packet
1317 * @param dhcpPayload the DHCP data
1318 */
1319 private void handleDhcpAck(Ethernet ethernetPacketAck, DHCP dhcpPayload) {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001320 Optional<Interface> outInterface = getClientInterface(ethernetPacketAck, dhcpPayload);
Yi Tseng51301292017-07-28 13:02:59 -07001321 if (!outInterface.isPresent()) {
1322 log.warn("Can't find output interface for dhcp: {}", dhcpPayload);
1323 return;
1324 }
1325
1326 Interface outIface = outInterface.get();
1327 HostLocation hostLocation = new HostLocation(outIface.connectPoint(), System.currentTimeMillis());
1328 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
Yi Tseng4f2a0462017-08-31 11:21:00 -07001329 VlanId vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -07001330 if (vlanId == null) {
1331 vlanId = outIface.vlan();
1332 }
Yi Tseng51301292017-07-28 13:02:59 -07001333 HostId hostId = HostId.hostId(macAddress, vlanId);
1334 Ip4Address ip = Ip4Address.valueOf(dhcpPayload.getYourIPAddress());
1335
1336 if (directlyConnected(dhcpPayload)) {
1337 // Add to host store if it connect to network directly
1338 Set<IpAddress> ips = Sets.newHashSet(ip);
Yi Tsengaa417a62017-09-08 17:22:51 -07001339 Host host = hostService.getHost(hostId);
Yi Tseng51301292017-07-28 13:02:59 -07001340
Yi Tsengaa417a62017-09-08 17:22:51 -07001341 Set<HostLocation> hostLocations = Sets.newHashSet(hostLocation);
1342 if (host != null) {
1343 // Dual homing support:
1344 // if host exists, use old locations and new location
1345 hostLocations.addAll(host.locations());
1346 }
1347 HostDescription desc = new DefaultHostDescription(macAddress, vlanId,
1348 hostLocations, ips, false);
1349 // Add IP address when dhcp server give the host new ip address
1350 providerService.hostDetected(hostId, desc, false);
Yi Tseng51301292017-07-28 13:02:59 -07001351 } else {
1352 // Add to route store if it does not connect to network directly
1353 // Get gateway host IP according to host mac address
Yi Tsengdcef2c22017-08-05 20:34:06 -07001354 // TODO: remove relay store here
Yi Tseng51301292017-07-28 13:02:59 -07001355 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1356
1357 if (record == null) {
1358 log.warn("Can't find DHCP record of host {}", hostId);
1359 return;
1360 }
1361
1362 MacAddress gwMac = record.nextHop().orElse(null);
1363 if (gwMac == null) {
1364 log.warn("Can't find gateway mac address from record {}", record);
1365 return;
1366 }
1367
1368 HostId gwHostId = HostId.hostId(gwMac, record.vlanId());
1369 Host gwHost = hostService.getHost(gwHostId);
1370
1371 if (gwHost == null) {
1372 log.warn("Can't find gateway host {}", gwHostId);
1373 return;
1374 }
1375
1376 Ip4Address nextHopIp = gwHost.ipAddresses()
1377 .stream()
1378 .filter(IpAddress::isIp4)
1379 .map(IpAddress::getIp4Address)
1380 .findFirst()
1381 .orElse(null);
1382
1383 if (nextHopIp == null) {
1384 log.warn("Can't find IP address of gateway {}", gwHost);
1385 return;
1386 }
1387
1388 Route route = new Route(Route.Source.STATIC, ip.toIpPrefix(), nextHopIp);
1389 routeStore.updateRoute(route);
1390 }
Yi Tseng51301292017-07-28 13:02:59 -07001391 }
1392
1393 /**
Yi Tseng51301292017-07-28 13:02:59 -07001394 * Gets output interface of a dhcp packet.
1395 * If option 82 exists in the dhcp packet and the option was sent by
Yi Tseng4f2a0462017-08-31 11:21:00 -07001396 * ONOS (circuit format is correct), use the connect
Yi Tseng51301292017-07-28 13:02:59 -07001397 * point and vlan id from circuit id; otherwise, find host by destination
1398 * address and use vlan id from sender (dhcp server).
1399 *
1400 * @param ethPacket the ethernet packet
1401 * @param dhcpPayload the dhcp packet
1402 * @return an interface represent the output port and vlan; empty value
1403 * if the host or circuit id not found
1404 */
Yi Tsengdcef2c22017-08-05 20:34:06 -07001405 private Optional<Interface> getClientInterface(Ethernet ethPacket, DHCP dhcpPayload) {
Yi Tseng51301292017-07-28 13:02:59 -07001406 VlanId originalPacketVlanId = VlanId.vlanId(ethPacket.getVlanID());
Yi Tseng51301292017-07-28 13:02:59 -07001407 DhcpRelayAgentOption option = (DhcpRelayAgentOption) dhcpPayload.getOption(OptionCode_CircuitID);
1408
Yi Tseng4f2a0462017-08-31 11:21:00 -07001409 DhcpOption circuitIdSubOption = option.getSubOption(CIRCUIT_ID.getValue());
1410 try {
1411 CircuitId circuitId = CircuitId.deserialize(circuitIdSubOption.getData());
1412 ConnectPoint connectPoint = ConnectPoint.deviceConnectPoint(circuitId.connectPoint());
1413 VlanId vlanId = circuitId.vlanId();
1414 return interfaceService.getInterfacesByPort(connectPoint)
1415 .stream()
1416 .filter(iface -> interfaceContainsVlan(iface, vlanId))
1417 .findFirst();
1418 } catch (IllegalArgumentException ex) {
1419 // invalid circuit format, didn't sent by ONOS
1420 log.debug("Invalid circuit {}, use information from dhcp payload",
1421 circuitIdSubOption.getData());
Yi Tseng51301292017-07-28 13:02:59 -07001422 }
1423
1424 // Use Vlan Id from DHCP server if DHCP relay circuit id was not
1425 // sent by ONOS or circuit Id can't be parsed
Yi Tsengdcef2c22017-08-05 20:34:06 -07001426 // TODO: remove relay store from this method
Yi Tseng51301292017-07-28 13:02:59 -07001427 MacAddress dstMac = valueOf(dhcpPayload.getClientHardwareAddress());
1428 Optional<DhcpRecord> dhcpRecord = dhcpRelayStore.getDhcpRecord(HostId.hostId(dstMac, originalPacketVlanId));
Yi Tsengdcef2c22017-08-05 20:34:06 -07001429 ConnectPoint clientConnectPoint = dhcpRecord
Yi Tseng51301292017-07-28 13:02:59 -07001430 .map(DhcpRecord::locations)
1431 .orElse(Collections.emptySet())
1432 .stream()
1433 .reduce((hl1, hl2) -> {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001434 // find latest host connect point
Yi Tseng51301292017-07-28 13:02:59 -07001435 if (hl1 == null || hl2 == null) {
1436 return hl1 == null ? hl2 : hl1;
1437 }
1438 return hl1.time() > hl2.time() ? hl1 : hl2;
1439 })
Yi Tsengdcef2c22017-08-05 20:34:06 -07001440 .orElse(null);
Yi Tseng51301292017-07-28 13:02:59 -07001441
Yi Tsengdcef2c22017-08-05 20:34:06 -07001442 if (clientConnectPoint != null) {
1443 return interfaceService.getInterfacesByPort(clientConnectPoint)
1444 .stream()
Yi Tseng4f2a0462017-08-31 11:21:00 -07001445 .filter(iface -> interfaceContainsVlan(iface, originalPacketVlanId))
Yi Tsengdcef2c22017-08-05 20:34:06 -07001446 .findFirst();
1447 }
1448 return Optional.empty();
Yi Tseng51301292017-07-28 13:02:59 -07001449 }
1450
1451 /**
1452 * Send the response DHCP to the requester host.
1453 *
1454 * @param ethPacket the packet
1455 * @param dhcpPayload the DHCP data
1456 */
1457 private void sendResponseToClient(Ethernet ethPacket, DHCP dhcpPayload) {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001458 Optional<Interface> outInterface = getClientInterface(ethPacket, dhcpPayload);
1459 if (directlyConnected(dhcpPayload)) {
1460 ethPacket = removeRelayAgentOption(ethPacket);
1461 }
1462 if (!outInterface.isPresent()) {
1463 log.warn("Can't find output interface for client, ignore");
1464 return;
1465 }
1466 Interface outIface = outInterface.get();
1467 TrafficTreatment treatment = DefaultTrafficTreatment.builder()
1468 .setOutput(outIface.connectPoint().port())
1469 .build();
1470 OutboundPacket o = new DefaultOutboundPacket(
1471 outIface.connectPoint().deviceId(),
1472 treatment,
1473 ByteBuffer.wrap(ethPacket.serialize()));
1474 if (log.isTraceEnabled()) {
1475 log.trace("Relaying packet to DHCP client {} via {}, vlan {}",
1476 ethPacket,
1477 outIface.connectPoint(),
1478 outIface.vlan());
1479 }
1480 packetService.emit(o);
Yi Tseng51301292017-07-28 13:02:59 -07001481 }
Yi Tseng483ac6f2017-08-02 15:03:31 -07001482
Yi Tsengaa417a62017-09-08 17:22:51 -07001483 @Override
1484 public void triggerProbe(Host host) {
1485 // Do nothing here
1486 }
1487
1488 @Override
1489 public ProviderId id() {
Charles Chand988c282017-09-12 17:09:32 -07001490 return PROVIDER_ID;
Yi Tsengaa417a62017-09-08 17:22:51 -07001491 }
1492
Yi Tseng483ac6f2017-08-02 15:03:31 -07001493 class InternalHostListener implements HostListener {
1494 @Override
1495 public void event(HostEvent event) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001496 if (!configured()) {
1497 return;
1498 }
Yi Tseng483ac6f2017-08-02 15:03:31 -07001499 switch (event.type()) {
1500 case HOST_ADDED:
1501 case HOST_UPDATED:
1502 hostUpdated(event.subject());
1503 break;
1504 case HOST_REMOVED:
1505 hostRemoved(event.subject());
1506 break;
Yi Tseng483ac6f2017-08-02 15:03:31 -07001507 default:
1508 break;
1509 }
1510 }
1511 }
1512
1513 /**
Yi Tseng483ac6f2017-08-02 15:03:31 -07001514 * Handle host updated.
1515 * If the host is DHCP server or gateway, update connect mac and vlan.
1516 *
1517 * @param host the host
1518 */
1519 private void hostUpdated(Host host) {
Yi Tseng525ff402017-10-23 19:39:39 -07001520 hostUpdated(host, defaultServerInfoList);
1521 hostUpdated(host, indirectServerInfoList);
Yi Tseng483ac6f2017-08-02 15:03:31 -07001522 }
1523
Yi Tseng525ff402017-10-23 19:39:39 -07001524 private void hostUpdated(Host host, List<DhcpServerInfo> srverInfoList) {
1525 DhcpServerInfo serverInfo;
1526 Ip4Address targetIp;
1527 if (!srverInfoList.isEmpty()) {
1528 serverInfo = srverInfoList.get(0);
1529 targetIp = serverInfo.getDhcpGatewayIp4().orElse(null);
1530 Ip4Address serverIp = serverInfo.getDhcpServerIp4().orElse(null);
1531
1532 if (targetIp == null) {
1533 targetIp = serverIp;
1534 }
1535
1536 if (targetIp != null) {
1537 if (host.ipAddresses().contains(targetIp)) {
1538 serverInfo.setDhcpConnectMac(host.mac());
1539 serverInfo.setDhcpConnectVlan(host.vlan());
1540 requestDhcpPacket(serverIp);
1541 }
1542 }
1543 }
1544 }
1545
1546
Yi Tseng483ac6f2017-08-02 15:03:31 -07001547 /**
1548 * Handle host removed.
1549 * If the host is DHCP server or gateway, unset connect mac and vlan.
1550 *
1551 * @param host the host
1552 */
1553 private void hostRemoved(Host host) {
Yi Tseng525ff402017-10-23 19:39:39 -07001554 hostRemoved(host, defaultServerInfoList);
1555 hostRemoved(host, indirectServerInfoList);
1556 }
1557
1558 private void hostRemoved(Host host, List<DhcpServerInfo> serverInfoList) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001559 DhcpServerInfo serverInfo;
Yi Tseng525ff402017-10-23 19:39:39 -07001560 Ip4Address targetIp;
1561 if (!serverInfoList.isEmpty()) {
1562 serverInfo = serverInfoList.get(0);
1563 Ip4Address serverIp = serverInfo.getDhcpServerIp4().orElse(null);
1564 targetIp = serverInfo.getDhcpGatewayIp4().orElse(null);
Yi Tseng919b2df2017-09-07 16:22:51 -07001565
Yi Tseng525ff402017-10-23 19:39:39 -07001566 if (targetIp == null) {
1567 targetIp = serverIp;
Yi Tseng919b2df2017-09-07 16:22:51 -07001568 }
Yi Tseng525ff402017-10-23 19:39:39 -07001569
1570 if (targetIp != null) {
1571 if (host.ipAddresses().contains(targetIp)) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001572 serverInfo.setDhcpConnectVlan(null);
1573 serverInfo.setDhcpConnectMac(null);
Yi Tseng525ff402017-10-23 19:39:39 -07001574 cancelDhcpPacket(serverIp);
Yi Tseng919b2df2017-09-07 16:22:51 -07001575 }
Yi Tseng483ac6f2017-08-02 15:03:31 -07001576 }
Yi Tseng483ac6f2017-08-02 15:03:31 -07001577 }
Yi Tseng525ff402017-10-23 19:39:39 -07001578 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001579
Yi Tseng525ff402017-10-23 19:39:39 -07001580 private void requestDhcpPacket(Ip4Address serverIp) {
1581 requestServerDhcpPacket(serverIp);
1582 requestClientDhcpPacket(serverIp);
1583 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001584
Yi Tseng525ff402017-10-23 19:39:39 -07001585 private void cancelDhcpPacket(Ip4Address serverIp) {
1586 cancelServerDhcpPacket(serverIp);
1587 cancelClientDhcpPacket(serverIp);
1588 }
1589
1590 private void cancelServerDhcpPacket(Ip4Address serverIp) {
1591 TrafficSelector serverSelector =
1592 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1593 .matchIPSrc(serverIp.toIpPrefix())
1594 .build();
1595 packetService.cancelPackets(serverSelector,
1596 PacketPriority.CONTROL,
1597 appId);
1598 }
1599
1600 private void requestServerDhcpPacket(Ip4Address serverIp) {
1601 TrafficSelector serverSelector =
1602 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1603 .matchIPSrc(serverIp.toIpPrefix())
1604 .build();
1605 packetService.requestPackets(serverSelector,
1606 PacketPriority.CONTROL,
1607 appId);
1608 }
1609
1610 private void cancelClientDhcpPacket(Ip4Address serverIp) {
1611 // Packet comes from relay
1612 TrafficSelector indirectClientSelector =
1613 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1614 .matchIPDst(serverIp.toIpPrefix())
1615 .build();
1616 packetService.cancelPackets(indirectClientSelector,
1617 PacketPriority.CONTROL,
1618 appId);
1619
1620 // Packet comes from client
1621 packetService.cancelPackets(CLIENT_SERVER_SELECTOR,
1622 PacketPriority.CONTROL,
1623 appId);
1624 }
1625
1626 private void requestClientDhcpPacket(Ip4Address serverIp) {
1627 // Packet comes from relay
1628 TrafficSelector indirectClientSelector =
1629 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1630 .matchIPDst(serverIp.toIpPrefix())
1631 .build();
1632 packetService.requestPackets(indirectClientSelector,
1633 PacketPriority.CONTROL,
1634 appId);
1635
1636 // Packet comes from client
1637 packetService.requestPackets(CLIENT_SERVER_SELECTOR,
1638 PacketPriority.CONTROL,
1639 appId);
1640 }
1641
1642 /**
1643 * Process the ignore rules.
1644 *
1645 * @param deviceId the device id
1646 * @param vlanId the vlan to be ignored
1647 * @param op the operation, ADD to install; REMOVE to uninstall rules
1648 */
1649 private void processIgnoreVlanRule(DeviceId deviceId, VlanId vlanId, Objective.Operation op) {
Yi Tseng525ff402017-10-23 19:39:39 -07001650 AtomicInteger installedCount = new AtomicInteger(DHCP_SELECTORS.size());
1651 DHCP_SELECTORS.forEach(trafficSelector -> {
1652 TrafficSelector selector = DefaultTrafficSelector.builder(trafficSelector)
1653 .matchVlanId(vlanId)
1654 .build();
1655
1656 ForwardingObjective.Builder builder = DefaultForwardingObjective.builder()
1657 .withFlag(ForwardingObjective.Flag.VERSATILE)
1658 .withSelector(selector)
1659 .withPriority(IGNORE_CONTROL_PRIORITY)
Yi Tsengdbabeed2017-11-29 10:49:20 -08001660 .withTreatment(DefaultTrafficTreatment.emptyTreatment())
Yi Tseng525ff402017-10-23 19:39:39 -07001661 .fromApp(appId);
1662
1663
1664 ObjectiveContext objectiveContext = new ObjectiveContext() {
1665 @Override
1666 public void onSuccess(Objective objective) {
1667 log.info("Ignore rule {} (Vlan id {}, device {}, selector {})",
1668 op, vlanId, deviceId, selector);
1669 int countDown = installedCount.decrementAndGet();
1670 if (countDown != 0) {
1671 return;
1672 }
1673 switch (op) {
1674 case ADD:
1675 ignoredVlans.put(deviceId, vlanId);
1676 break;
1677 case REMOVE:
1678 ignoredVlans.remove(deviceId, vlanId);
1679 break;
1680 default:
1681 log.warn("Unsupported objective operation {}", op);
1682 break;
1683 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001684 }
Yi Tseng525ff402017-10-23 19:39:39 -07001685
1686 @Override
1687 public void onError(Objective objective, ObjectiveError error) {
1688 log.warn("Can't {} ignore rule (vlan id {}, selector {}, device {}) due to {}",
1689 op, vlanId, selector, deviceId, error);
Yi Tseng919b2df2017-09-07 16:22:51 -07001690 }
Yi Tseng525ff402017-10-23 19:39:39 -07001691 };
1692
1693 ForwardingObjective fwd;
1694 switch (op) {
1695 case ADD:
1696 fwd = builder.add(objectiveContext);
1697 break;
1698 case REMOVE:
1699 fwd = builder.remove(objectiveContext);
1700 break;
1701 default:
1702 log.warn("Unsupported objective operation {}", op);
1703 return;
Yi Tseng4f2a0462017-08-31 11:21:00 -07001704 }
Yi Tseng525ff402017-10-23 19:39:39 -07001705
1706 Device device = deviceService.getDevice(deviceId);
1707 if (device == null || !device.is(Pipeliner.class)) {
1708 log.warn("Device {} is not available now, wait until device is available", deviceId);
1709 return;
1710 }
1711 flowObjectiveService.apply(deviceId, fwd);
1712 });
Yi Tseng483ac6f2017-08-02 15:03:31 -07001713 }
Kalhee Kimba366062017-11-07 16:32:09 +00001714
1715 @Override
1716 public void setDhcpFpmEnabled(Boolean enabled) {
1717 // v4 does not use fpm. Do nothing.
1718 }
rsahot036620655b2018-02-26 15:01:37 -05001719 private List<DhcpServerInfo> findValidServerInfo(boolean directConnFlag) {
1720 List<DhcpServerInfo> validServerInfo;
1721
1722 if (directConnFlag || indirectServerInfoList.isEmpty()) {
1723 validServerInfo = new ArrayList<DhcpServerInfo>(defaultServerInfoList);
1724 } else {
1725 validServerInfo = new ArrayList<DhcpServerInfo>(indirectServerInfoList);
1726 }
1727 return validServerInfo;
1728 }
1729
1730
1731 private boolean checkDhcpServerConnPt(boolean directConnFlag,
1732 DhcpServerInfo serverInfo) {
1733 if (serverInfo.getDhcpServerConnectPoint() == null) {
1734 log.warn("DHCP4 server connect point for {} connPt {}",
1735 directConnFlag ? "direct" : "indirect", serverInfo.getDhcpServerConnectPoint());
1736 return false;
1737 }
1738 return true;
1739 }
1740
1741 /**
1742 * Checks if serverInfo's host info (mac and vlan) is filled in; if not, fills in.
1743 *
1744 * @param serverInfo server information
1745 * @return newServerInfo if host info can be either found or filled in.
1746 */
1747 private DhcpServerInfo getHostInfoForServerInfo(DhcpServerInfo serverInfo, List<DhcpServerInfo> sererInfoList) {
1748 DhcpServerInfo newServerInfo = null;
1749 MacAddress dhcpServerConnectMac = serverInfo.getDhcpConnectMac().orElse(null);
1750 VlanId dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1751 ConnectPoint dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1752
1753 if (dhcpServerConnectMac != null && dhcpConnectVlan != null) {
1754 newServerInfo = serverInfo;
1755 log.warn("DHCP server {} host info found. ConnectPt{} Mac {} vlan {}", serverInfo.getDhcpServerIp4(),
1756 dhcpServerConnectPoint, dhcpServerConnectMac, dhcpConnectVlan);
1757 } else {
1758 log.warn("DHCP server {} not resolve yet connectPt {} mac {} vlan {}", serverInfo.getDhcpServerIp4(),
1759 dhcpServerConnectPoint, dhcpServerConnectMac, dhcpConnectVlan);
1760
1761 Ip4Address ipToProbe;
1762 if (serverInfo.getDhcpGatewayIp4().isPresent()) {
1763 ipToProbe = serverInfo.getDhcpGatewayIp4().get();
1764 } else {
1765 ipToProbe = serverInfo.getDhcpServerIp4().orElse(null);
1766 }
1767 String hostToProbe = serverInfo.getDhcpGatewayIp6()
1768 .map(ip -> "gateway").orElse("server");
1769
1770 log.warn("Dynamically probing to resolve {} IP {}", hostToProbe, ipToProbe);
1771 hostService.startMonitoringIp(ipToProbe);
1772
1773 Set<Host> hosts = hostService.getHostsByIp(ipToProbe);
1774 if (!hosts.isEmpty()) {
1775 int serverInfoIndex = sererInfoList.indexOf(serverInfo);
1776 Host host = hosts.iterator().next();
1777 serverInfo.setDhcpConnectVlan(host.vlan());
1778 serverInfo.setDhcpConnectMac(host.mac());
1779 // replace the serverInfo in the list
1780 sererInfoList.set(serverInfoIndex, serverInfo);
1781 newServerInfo = serverInfo;
1782 log.warn("Dynamically host found host {}", host);
1783 } else {
1784 log.warn("No host found host ip {} dynamically", ipToProbe);
1785 }
1786 }
1787 return newServerInfo;
1788 }
1789
1790 /**
1791 * Gets Interface facing to the server for default host.
1792 *
1793 * @param serverInfo server information
1794 * @return the Interface facing to the server; null if not found
1795 */
1796 private Interface getServerInterface(DhcpServerInfo serverInfo) {
1797 Interface serverInterface = null;
1798
1799 ConnectPoint dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1800 VlanId dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1801
1802 if (dhcpServerConnectPoint != null && dhcpConnectVlan != null) {
1803 serverInterface = interfaceService.getInterfacesByPort(dhcpServerConnectPoint)
1804 .stream()
1805 .filter(iface -> dhcp4HandlerUtil.interfaceContainsVlan(iface, dhcpConnectVlan))
1806 .findFirst()
1807 .orElse(null);
1808 } else {
1809 log.warn("DHCP server {} not resolve yet connectPoint {} vlan {}", serverInfo.getDhcpServerIp6(),
1810 dhcpServerConnectPoint, dhcpConnectVlan);
1811 }
1812
1813 return serverInterface;
1814 }
1815
1816 //forward the packet to ConnectPoint where the DHCP server is attached.
1817 private void forwardPacket(InternalPacket packet) {
1818 //send Packetout to dhcp server connectpoint.
1819 if (packet.destLocation != null) {
1820 TrafficTreatment t = DefaultTrafficTreatment.builder()
1821 .setOutput(packet.destLocation.port()).build();
1822 OutboundPacket o = new DefaultOutboundPacket(
1823 packet.destLocation.deviceId(), t, ByteBuffer.wrap(packet.packet.serialize()));
1824 if (log.isTraceEnabled()) {
1825 log.trace("Relaying packet to destination {}", packet.destLocation);
1826 }
1827 log.info("DHCP RELAY: packetService.emit(o) to port {}", packet.destLocation);
1828 packetService.emit(o);
1829 }
1830 }
1831
1832
1833 private DhcpServerInfo findServerInfoFromServer(boolean directConnFlag, ConnectPoint inPort) {
1834 List<DhcpServerInfo> validServerInfoList = findValidServerInfo(directConnFlag);
1835 DhcpServerInfo foundServerInfo = null;
1836 for (DhcpServerInfo serverInfo : validServerInfoList) {
1837 if (inPort.equals(serverInfo.getDhcpServerConnectPoint().get())) {
1838 foundServerInfo = serverInfo;
1839 log.warn("ServerInfo found for Rcv port {} Server Connect Point {} for {}",
1840 inPort, serverInfo.getDhcpServerConnectPoint(), directConnFlag ? "direct" : "indirect");
1841 break;
1842 } else {
1843 log.warn("Rcv port {} not the same as Server Connect Point {} for {}",
1844 inPort, serverInfo.getDhcpServerConnectPoint(), directConnFlag ? "direct" : "indirect");
1845 }
1846 }
1847 return foundServerInfo;
1848 }
1849
Yi Tseng51301292017-07-28 13:02:59 -07001850}