blob: d0a8214dd4f8bf9810ffca8e6ce63d4f6a13c63a [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 Tseng7da339e2017-10-23 19:39:39 -070020import com.google.common.collect.HashMultimap;
21import com.google.common.collect.ImmutableSet;
Yi Tseng2fe8f3f2017-09-07 16:22:51 -070022import com.google.common.collect.Lists;
Yi Tseng7da339e2017-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 Tsenge72fbb52017-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 Tsenge72fbb52017-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 Tseng7da339e2017-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 Tseng7da339e2017-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 Tseng2fe8f3f2017-09-07 16:22:51 -070048import org.onosproject.dhcprelay.api.DhcpServerInfo;
Yi Tsenge72fbb52017-08-02 15:03:31 -070049import org.onosproject.dhcprelay.config.DhcpServerConfig;
Yi Tseng7da339e2017-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 Tseng7da339e2017-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 Tsenge72fbb52017-08-02 15:03:31 -070065import org.onosproject.net.host.HostEvent;
66import org.onosproject.net.host.HostListener;
Yi Tseng4b013202017-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 Tseng7da339e2017-10-23 19:39:39 -070072import org.onosproject.net.packet.PacketPriority;
Yi Tseng4b013202017-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;
97import java.util.Optional;
98import java.util.Set;
Yi Tseng7da339e2017-10-23 19:39:39 -070099import java.util.concurrent.atomic.AtomicInteger;
Yi Tseng51301292017-07-28 13:02:59 -0700100import java.util.stream.Collectors;
101
102import static com.google.common.base.Preconditions.checkNotNull;
103import static com.google.common.base.Preconditions.checkState;
104import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_CircuitID;
105import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_END;
106import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_MessageType;
107import static org.onlab.packet.MacAddress.valueOf;
108import static org.onlab.packet.dhcp.DhcpRelayAgentOption.RelayAgentInfoOptions.CIRCUIT_ID;
Yi Tseng7da339e2017-10-23 19:39:39 -0700109import static org.onosproject.net.flowobjective.Objective.Operation.ADD;
110import static org.onosproject.net.flowobjective.Objective.Operation.REMOVE;
Yi Tseng51301292017-07-28 13:02:59 -0700111
112@Component
113@Service
114@Property(name = "version", value = "4")
Yi Tseng4b013202017-09-08 17:22:51 -0700115public class Dhcp4HandlerImpl implements DhcpHandler, HostProvider {
Charles Chan75edab72017-09-12 17:09:32 -0700116 public static final String DHCP_V4_RELAY_APP = "org.onosproject.Dhcp4HandlerImpl";
117 public static final ProviderId PROVIDER_ID = new ProviderId("dhcp4", DHCP_V4_RELAY_APP);
Yi Tseng7da339e2017-10-23 19:39:39 -0700118 private static final String BROADCAST_IP = "255.255.255.255";
119 private static final int IGNORE_CONTROL_PRIORITY = PacketPriority.CONTROL.priorityValue() + 1000;
120
121 private static final TrafficSelector CLIENT_SERVER_SELECTOR = DefaultTrafficSelector.builder()
122 .matchEthType(Ethernet.TYPE_IPV4)
123 .matchIPProtocol(IPv4.PROTOCOL_UDP)
124 .matchIPSrc(Ip4Address.ZERO.toIpPrefix())
125 .matchIPDst(Ip4Address.valueOf(BROADCAST_IP).toIpPrefix())
126 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_CLIENT_PORT))
127 .matchUdpDst(TpPort.tpPort(UDP.DHCP_SERVER_PORT))
128 .build();
129 private static final TrafficSelector SERVER_RELAY_SELECTOR = DefaultTrafficSelector.builder()
130 .matchEthType(Ethernet.TYPE_IPV4)
131 .matchIPProtocol(IPv4.PROTOCOL_UDP)
132 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_SERVER_PORT))
133 .matchUdpDst(TpPort.tpPort(UDP.DHCP_SERVER_PORT))
134 .build();
135 static final Set<TrafficSelector> DHCP_SELECTORS = ImmutableSet.of(
136 CLIENT_SERVER_SELECTOR,
137 SERVER_RELAY_SELECTOR
138 );
Yi Tseng51301292017-07-28 13:02:59 -0700139 private static Logger log = LoggerFactory.getLogger(Dhcp4HandlerImpl.class);
140
141 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
142 protected DhcpRelayStore dhcpRelayStore;
143
144 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
145 protected PacketService packetService;
146
147 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yi Tseng51301292017-07-28 13:02:59 -0700148 protected RouteStore routeStore;
149
150 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
151 protected InterfaceService interfaceService;
152
153 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
154 protected HostService hostService;
155
Yi Tseng4b013202017-09-08 17:22:51 -0700156 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
157 protected HostProviderRegistry providerRegistry;
158
Yi Tseng7da339e2017-10-23 19:39:39 -0700159 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
160 protected CoreService coreService;
161
162 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
163 protected DeviceService deviceService;
164
165 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
166 protected FlowObjectiveService flowObjectiveService;
167
Yi Tseng4b013202017-09-08 17:22:51 -0700168 protected HostProviderService providerService;
Yi Tseng7da339e2017-10-23 19:39:39 -0700169 protected ApplicationId appId;
170 protected Multimap<DeviceId, VlanId> ignoredVlans = HashMultimap.create();
Yi Tsenge72fbb52017-08-02 15:03:31 -0700171 private InternalHostListener hostListener = new InternalHostListener();
172
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700173 private List<DhcpServerInfo> defaultServerInfoList = Lists.newArrayList();
174 private List<DhcpServerInfo> indirectServerInfoList = Lists.newArrayList();
Yi Tseng4ec727d2017-08-31 11:21:00 -0700175
Yi Tsenge72fbb52017-08-02 15:03:31 -0700176 @Activate
177 protected void activate() {
Yi Tseng7da339e2017-10-23 19:39:39 -0700178 appId = coreService.registerApplication(DHCP_V4_RELAY_APP);
Yi Tsenge72fbb52017-08-02 15:03:31 -0700179 hostService.addListener(hostListener);
Yi Tseng4b013202017-09-08 17:22:51 -0700180 providerService = providerRegistry.register(this);
Yi Tsenge72fbb52017-08-02 15:03:31 -0700181 }
182
183 @Deactivate
184 protected void deactivate() {
Yi Tseng4b013202017-09-08 17:22:51 -0700185 providerRegistry.unregister(this);
186 hostService.removeListener(hostListener);
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700187 defaultServerInfoList.forEach(this::stopMonitoringIps);
188 defaultServerInfoList.clear();
189 indirectServerInfoList.forEach(this::stopMonitoringIps);
190 indirectServerInfoList.clear();
Yi Tsenge72fbb52017-08-02 15:03:31 -0700191 }
192
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700193 private void stopMonitoringIps(DhcpServerInfo serverInfo) {
194 serverInfo.getDhcpGatewayIp4().ifPresent(gatewayIp -> {
195 hostService.stopMonitoringIp(gatewayIp);
196 });
197 serverInfo.getDhcpServerIp4().ifPresent(serverIp -> {
198 hostService.stopMonitoringIp(serverIp);
199 });
Yi Tseng51301292017-07-28 13:02:59 -0700200 }
201
202 @Override
Yi Tsenge72fbb52017-08-02 15:03:31 -0700203 public void setDefaultDhcpServerConfigs(Collection<DhcpServerConfig> configs) {
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700204 setDhcpServerConfigs(configs, defaultServerInfoList);
205 }
206
207 @Override
208 public void setIndirectDhcpServerConfigs(Collection<DhcpServerConfig> configs) {
209 setDhcpServerConfigs(configs, indirectServerInfoList);
210 }
211
212 @Override
213 public List<DhcpServerInfo> getDefaultDhcpServerInfoList() {
214 return defaultServerInfoList;
215 }
216
217 @Override
218 public List<DhcpServerInfo> getIndirectDhcpServerInfoList() {
219 return indirectServerInfoList;
220 }
221
Yi Tseng7da339e2017-10-23 19:39:39 -0700222 @Override
223 public void updateIgnoreVlanConfig(IgnoreDhcpConfig config) {
224 if (config == null) {
225 ignoredVlans.forEach(((deviceId, vlanId) -> {
226 processIgnoreVlanRule(deviceId, vlanId, REMOVE);
227 }));
228 return;
229 }
230 config.ignoredVlans().forEach((deviceId, vlanId) -> {
231 if (ignoredVlans.get(deviceId).contains(vlanId)) {
232 // don't need to process if it already ignored
233 return;
234 }
235 processIgnoreVlanRule(deviceId, vlanId, ADD);
236 });
237
238 ignoredVlans.forEach((deviceId, vlanId) -> {
239 if (!config.ignoredVlans().get(deviceId).contains(vlanId)) {
240 // not contains in new config, remove it
241 processIgnoreVlanRule(deviceId, vlanId, REMOVE);
242 }
243 });
244 }
245
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700246 public void setDhcpServerConfigs(Collection<DhcpServerConfig> configs, List<DhcpServerInfo> serverInfoList) {
Yi Tsenge72fbb52017-08-02 15:03:31 -0700247 if (configs.size() == 0) {
248 // no config to update
249 return;
250 }
251
252 // TODO: currently we pick up first DHCP server config.
253 // Will use other server configs in the future for HA.
254 DhcpServerConfig serverConfig = configs.iterator().next();
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700255
Yi Tsengaefbb002017-09-08 16:23:32 -0700256 if (!serverConfig.getDhcpServerIp4().isPresent()) {
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700257 // not a DHCPv4 config
Yi Tsenge72fbb52017-08-02 15:03:31 -0700258 return;
259 }
260
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700261 if (!serverInfoList.isEmpty()) {
262 // remove old server info
263 DhcpServerInfo oldServerInfo = serverInfoList.remove(0);
Yi Tsenge72fbb52017-08-02 15:03:31 -0700264
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700265 // stop monitoring gateway or server
266 oldServerInfo.getDhcpGatewayIp4().ifPresent(gatewayIp -> {
267 hostService.stopMonitoringIp(gatewayIp);
268 });
269 oldServerInfo.getDhcpServerIp4().ifPresent(serverIp -> {
270 hostService.stopMonitoringIp(serverIp);
Yi Tseng7da339e2017-10-23 19:39:39 -0700271 cancelDhcpPacket(serverIp);
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700272 });
Yi Tsenge72fbb52017-08-02 15:03:31 -0700273 }
Yi Tseng4fa05832017-08-17 13:08:31 -0700274
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700275 // Create new server info according to the config
276 DhcpServerInfo newServerInfo = new DhcpServerInfo(serverConfig,
277 DhcpServerInfo.Version.DHCP_V4);
278 checkState(newServerInfo.getDhcpServerConnectPoint().isPresent(),
Yi Tseng4ec727d2017-08-31 11:21:00 -0700279 "Connect point not exists");
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700280 checkState(newServerInfo.getDhcpServerIp4().isPresent(),
Yi Tseng4ec727d2017-08-31 11:21:00 -0700281 "IP of DHCP server not exists");
Yi Tseng4ec727d2017-08-31 11:21:00 -0700282
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700283 log.debug("DHCP server connect point: {}", newServerInfo.getDhcpServerConnectPoint().orElse(null));
284 log.debug("DHCP server IP: {}", newServerInfo.getDhcpServerIp4().orElse(null));
285
Yi Tseng7da339e2017-10-23 19:39:39 -0700286 Ip4Address serverIp = newServerInfo.getDhcpServerIp4().get();
287 Ip4Address ipToProbe;
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700288 if (newServerInfo.getDhcpGatewayIp4().isPresent()) {
289 ipToProbe = newServerInfo.getDhcpGatewayIp4().get();
290 } else {
291 ipToProbe = newServerInfo.getDhcpServerIp4().orElse(null);
Yi Tseng4ec727d2017-08-31 11:21:00 -0700292 }
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700293 String hostToProbe = newServerInfo.getDhcpGatewayIp4()
294 .map(ip -> "gateway").orElse("server");
Yi Tseng4ec727d2017-08-31 11:21:00 -0700295
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700296 log.debug("Probing to resolve {} IP {}", hostToProbe, ipToProbe);
Yi Tseng4ec727d2017-08-31 11:21:00 -0700297 hostService.startMonitoringIp(ipToProbe);
298
299 Set<Host> hosts = hostService.getHostsByIp(ipToProbe);
300 if (!hosts.isEmpty()) {
301 Host host = hosts.iterator().next();
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700302 newServerInfo.setDhcpConnectVlan(host.vlan());
303 newServerInfo.setDhcpConnectMac(host.mac());
Yi Tseng4ec727d2017-08-31 11:21:00 -0700304 }
305
Yi Tseng053682b2017-11-09 13:54:12 -0800306 // Add new server info
307 synchronized (this) {
308 serverInfoList.clear();
309 serverInfoList.add(0, newServerInfo);
310 }
311
Yi Tseng7da339e2017-10-23 19:39:39 -0700312 requestDhcpPacket(serverIp);
Yi Tsenge72fbb52017-08-02 15:03:31 -0700313 }
314
Yi Tseng4fa05832017-08-17 13:08:31 -0700315 @Override
Yi Tseng51301292017-07-28 13:02:59 -0700316 public void processDhcpPacket(PacketContext context, BasePacket payload) {
317 checkNotNull(payload, "DHCP payload can't be null");
318 checkState(payload instanceof DHCP, "Payload is not a DHCP");
319 DHCP dhcpPayload = (DHCP) payload;
320 if (!configured()) {
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700321 log.warn("Missing default DHCP relay server config. Abort packet processing");
Yi Tseng51301292017-07-28 13:02:59 -0700322 return;
323 }
324
325 ConnectPoint inPort = context.inPacket().receivedFrom();
Yi Tseng51301292017-07-28 13:02:59 -0700326 checkNotNull(dhcpPayload, "Can't find DHCP payload");
327 Ethernet packet = context.inPacket().parsed();
328 DHCP.MsgType incomingPacketType = dhcpPayload.getOptions().stream()
329 .filter(dhcpOption -> dhcpOption.getCode() == OptionCode_MessageType.getValue())
330 .map(DhcpOption::getData)
331 .map(data -> DHCP.MsgType.getType(data[0]))
332 .findFirst()
333 .orElse(null);
334 checkNotNull(incomingPacketType, "Can't get message type from DHCP payload {}", dhcpPayload);
335 switch (incomingPacketType) {
336 case DHCPDISCOVER:
Yi Tsengdcef2c22017-08-05 20:34:06 -0700337 // Add the gateway IP as virtual interface IP for server to understand
Yi Tseng51301292017-07-28 13:02:59 -0700338 // the lease to be assigned and forward the packet to dhcp server.
339 Ethernet ethernetPacketDiscover =
Yi Tsengdcef2c22017-08-05 20:34:06 -0700340 processDhcpPacketFromClient(context, packet);
Yi Tseng51301292017-07-28 13:02:59 -0700341 if (ethernetPacketDiscover != null) {
342 writeRequestDhcpRecord(inPort, packet, dhcpPayload);
Yi Tseng4ec727d2017-08-31 11:21:00 -0700343 handleDhcpDiscoverAndRequest(ethernetPacketDiscover, dhcpPayload);
Yi Tseng51301292017-07-28 13:02:59 -0700344 }
345 break;
346 case DHCPOFFER:
347 //reply to dhcp client.
348 Ethernet ethernetPacketOffer = processDhcpPacketFromServer(packet);
349 if (ethernetPacketOffer != null) {
350 writeResponseDhcpRecord(ethernetPacketOffer, dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -0700351 sendResponseToClient(ethernetPacketOffer, dhcpPayload);
Yi Tseng51301292017-07-28 13:02:59 -0700352 }
353 break;
354 case DHCPREQUEST:
355 // add the gateway ip as virtual interface ip for server to understand
356 // the lease to be assigned and forward the packet to dhcp server.
357 Ethernet ethernetPacketRequest =
Yi Tsengdcef2c22017-08-05 20:34:06 -0700358 processDhcpPacketFromClient(context, packet);
Yi Tseng51301292017-07-28 13:02:59 -0700359 if (ethernetPacketRequest != null) {
360 writeRequestDhcpRecord(inPort, packet, dhcpPayload);
Yi Tseng4ec727d2017-08-31 11:21:00 -0700361 handleDhcpDiscoverAndRequest(ethernetPacketRequest, dhcpPayload);
Yi Tseng51301292017-07-28 13:02:59 -0700362 }
363 break;
Charles Chan2f9aa2c2017-10-08 23:53:36 -0400364 case DHCPDECLINE:
365 break;
Yi Tseng51301292017-07-28 13:02:59 -0700366 case DHCPACK:
367 // reply to dhcp client.
368 Ethernet ethernetPacketAck = processDhcpPacketFromServer(packet);
369 if (ethernetPacketAck != null) {
370 writeResponseDhcpRecord(ethernetPacketAck, dhcpPayload);
371 handleDhcpAck(ethernetPacketAck, dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -0700372 sendResponseToClient(ethernetPacketAck, dhcpPayload);
Yi Tseng51301292017-07-28 13:02:59 -0700373 }
374 break;
Charles Chan2f9aa2c2017-10-08 23:53:36 -0400375 case DHCPNAK:
376 break;
Yi Tseng51301292017-07-28 13:02:59 -0700377 case DHCPRELEASE:
378 // TODO: release the ip address from client
379 break;
Charles Chan2f9aa2c2017-10-08 23:53:36 -0400380 case DHCPINFORM:
381 break;
382 case DHCPFORCERENEW:
383 break;
384 case DHCPLEASEQUERY:
385 handleLeaseQueryMsg(context, packet, dhcpPayload);
386 break;
387 case DHCPLEASEACTIVE:
388 handleLeaseQueryActivateMsg(packet, dhcpPayload);
389 break;
390 case DHCPLEASEUNASSIGNED:
391 case DHCPLEASEUNKNOWN:
392 handleLeaseQueryUnknown(packet, dhcpPayload);
393 break;
Yi Tseng51301292017-07-28 13:02:59 -0700394 default:
395 break;
396 }
397 }
398
399 /**
400 * Checks if this app has been configured.
401 *
402 * @return true if all information we need have been initialized
403 */
Yi Tseng4ec727d2017-08-31 11:21:00 -0700404 private boolean configured() {
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700405 return !defaultServerInfoList.isEmpty();
Yi Tseng51301292017-07-28 13:02:59 -0700406 }
407
408 /**
Yi Tsengdcef2c22017-08-05 20:34:06 -0700409 * Returns the first interface ip from interface.
Yi Tseng51301292017-07-28 13:02:59 -0700410 *
Yi Tsengdcef2c22017-08-05 20:34:06 -0700411 * @param iface interface of one connect point
Yi Tseng51301292017-07-28 13:02:59 -0700412 * @return the first interface IP; null if not exists an IP address in
413 * these interfaces
414 */
Yi Tseng4fa05832017-08-17 13:08:31 -0700415 private Ip4Address getFirstIpFromInterface(Interface iface) {
Yi Tsengdcef2c22017-08-05 20:34:06 -0700416 checkNotNull(iface, "Interface can't be null");
417 return iface.ipAddressesList().stream()
Yi Tseng51301292017-07-28 13:02:59 -0700418 .map(InterfaceIpAddress::ipAddress)
419 .filter(IpAddress::isIp4)
420 .map(IpAddress::getIp4Address)
421 .findFirst()
422 .orElse(null);
423 }
424
425 /**
Yi Tseng4ec727d2017-08-31 11:21:00 -0700426 * Gets Interface facing to the server for default host.
Yi Tsengdcef2c22017-08-05 20:34:06 -0700427 *
428 * @return the Interface facing to the server; null if not found
429 */
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700430 private Interface getDefaultServerInterface() {
431 return getServerInterface(defaultServerInfoList);
Yi Tsengdcef2c22017-08-05 20:34:06 -0700432 }
433
434 /**
Yi Tseng4ec727d2017-08-31 11:21:00 -0700435 * Gets Interface facing to the server for indirect hosts.
436 * Use default server Interface if indirect server not configured.
437 *
438 * @return the Interface facing to the server; null if not found
439 */
440 private Interface getIndirectServerInterface() {
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700441 return getServerInterface(indirectServerInfoList);
442 }
443
444 private Interface getServerInterface(List<DhcpServerInfo> serverInfos) {
445 DhcpServerInfo serverInfo = serverInfos.get(0);
446 ConnectPoint dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
447 VlanId dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
448 if (dhcpServerConnectPoint == null || dhcpConnectVlan == null) {
449 return null;
Yi Tseng4ec727d2017-08-31 11:21:00 -0700450 }
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700451 return interfaceService.getInterfacesByPort(dhcpServerConnectPoint)
Yi Tseng4ec727d2017-08-31 11:21:00 -0700452 .stream()
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700453 .filter(iface -> interfaceContainsVlan(iface, dhcpConnectVlan))
Yi Tseng4ec727d2017-08-31 11:21:00 -0700454 .findFirst()
455 .orElse(null);
456 }
457
458 /**
459 * Determind if an Interface contains a vlan id.
460 *
461 * @param iface the Interface
462 * @param vlanId the vlan id
463 * @return true if the Interface contains the vlan id
464 */
465 private boolean interfaceContainsVlan(Interface iface, VlanId vlanId) {
Yi Tseng58e74312017-09-30 11:35:42 +0800466 if (vlanId.equals(VlanId.NONE)) {
467 // untagged packet, check if vlan untagged or vlan native is not NONE
468 return !iface.vlanUntagged().equals(VlanId.NONE) ||
469 !iface.vlanNative().equals(VlanId.NONE);
470 }
471 // tagged packet, check if the interface contains the vlan
472 return iface.vlanTagged().contains(vlanId);
Yi Tseng4ec727d2017-08-31 11:21:00 -0700473 }
474
Charles Chan2f9aa2c2017-10-08 23:53:36 -0400475 private void handleLeaseQueryActivateMsg(Ethernet packet, DHCP dhcpPayload) {
476 log.debug("LQ: Got DHCPLEASEACTIVE packet!");
477
478 // TODO: release the ip address from client
479 MacAddress clientMacAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
480 VlanId vlanId = VlanId.vlanId(packet.getVlanID());
481 HostId hostId = HostId.hostId(clientMacAddress, vlanId);
482 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
483
484 if (record == null) {
485 log.warn("Can't find record for host {} when processing DHCPLEASEACTIVE", hostId);
486 return;
487 }
488
489 // need to update routes
490 log.debug("Lease Query for Client results in DHCPLEASEACTIVE - route needs to be modified");
491 // get current route
492 // find the ip of that client with the DhcpRelay store
493
494 Ip4Address clientIP = record.ip4Address().orElse(null);
495 log.debug("LQ: IP of host is " + clientIP.getIp4Address());
496
497 MacAddress nextHopMac = record.nextHop().orElse(null);
498 log.debug("LQ: MAC of resulting *OLD* NH for that host is " + nextHopMac.toString());
499
500 // find the new NH by looking at the src MAC of the dhcp request
501 // from the LQ store
502 MacAddress newNextHopMac = record.nextHopTemp().orElse(null);
503 log.debug("LQ: MAC of resulting *NEW* NH for that host is " + newNextHopMac.toString());
504
505 log.debug("LQ: updating dhcp relay record with new NH");
506 record.nextHop(newNextHopMac);
507
508 // find the next hop IP from its mac
509 HostId gwHostId = HostId.hostId(newNextHopMac, vlanId);
510 Host gwHost = hostService.getHost(gwHostId);
511
512 if (gwHost == null) {
513 log.warn("Can't find gateway for new NH host " + gwHostId);
514 return;
515 }
516
517 Ip4Address nextHopIp = gwHost.ipAddresses()
518 .stream()
519 .filter(IpAddress::isIp4)
520 .map(IpAddress::getIp4Address)
521 .findFirst()
522 .orElse(null);
523
524 if (nextHopIp == null) {
525 log.warn("Can't find IP address of gateway " + gwHost);
526 return;
527 }
528
529 log.debug("LQ: *NEW* NH IP for host is " + nextHopIp.getIp4Address());
530 Route route = new Route(Route.Source.STATIC, clientIP.toIpPrefix(), nextHopIp);
531 routeStore.updateRoute(route);
532
533 // and forward to client
534 Ethernet ethernetPacket = processLeaseQueryFromServer(packet);
535 if (ethernetPacket != null) {
536 sendResponseToClient(ethernetPacket, dhcpPayload);
537 }
538 }
539
540 /**
541 *
542 */
543 private void handleLeaseQueryMsg(PacketContext context, Ethernet packet, DHCP dhcpPayload) {
544 log.debug("LQ: Got DHCPLEASEQUERY packet!");
545 MacAddress clientMacAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
546 log.debug("LQ: got DHCPLEASEQUERY with MAC " + clientMacAddress.toString());
547 // add the client mac (hostid) of this request to a store (the entry will be removed with
548 // the reply sent to the originator)
549 VlanId vlanId = VlanId.vlanId(packet.getVlanID());
550 HostId hId = HostId.hostId(clientMacAddress, vlanId);
551 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hId).orElse(null);
552 if (record != null) {
553 //new NH is to be taken from src mac of LQ packet
554 MacAddress newNextHop = packet.getSourceMAC();
555 record.nextHopTemp(newNextHop);
556 record.ip4Status(dhcpPayload.getPacketType());
557 record.updateLastSeen();
558
559 // do a basic routing of the packet (this is unicast routing
560 // not a relay operation like for other broadcast dhcp packets
561 Ethernet ethernetPacketLQ = processLeaseQueryFromAgent(context, packet);
562 // and forward to server
563 handleDhcpDiscoverAndRequest(ethernetPacketLQ, dhcpPayload);
564 } else {
565 log.warn("LQ: Error! - DHCP relay record for that client not found - ignoring LQ!");
566 }
567 }
568
569 private void handleLeaseQueryUnknown(Ethernet packet, DHCP dhcpPayload) {
570 log.debug("Lease Query for Client results in DHCPLEASEUNASSIGNED or " +
571 "DHCPLEASEUNKNOWN - removing route & forwarding reply to originator");
572 MacAddress clientMacAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
573 VlanId vlanId = VlanId.vlanId(packet.getVlanID());
574 HostId hostId = HostId.hostId(clientMacAddress, vlanId);
575 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
576
577 if (record == null) {
578 log.warn("Can't find record for host {} when handling LQ UNKNOWN/UNASSIGNED message", hostId);
579 return;
580 }
581
582 Ip4Address clientIP = record.ip4Address().orElse(null);
583 log.debug("LQ: IP of host is " + clientIP.getIp4Address());
584
585 // find the new NH by looking at the src MAC of the dhcp request
586 // from the LQ store
587 MacAddress nextHopMac = record.nextHop().orElse(null);
588 log.debug("LQ: MAC of resulting *Existing* NH for that route is " + nextHopMac.toString());
589
590 // find the next hop IP from its mac
591 HostId gwHostId = HostId.hostId(nextHopMac, vlanId);
592 Host gwHost = hostService.getHost(gwHostId);
593
594 if (gwHost == null) {
595 log.warn("Can't find gateway for new NH host " + gwHostId);
596 return;
597 }
598
599 Ip4Address nextHopIp = gwHost.ipAddresses()
600 .stream()
601 .filter(IpAddress::isIp4)
602 .map(IpAddress::getIp4Address)
603 .findFirst()
604 .orElse(null);
605
606 if (nextHopIp == null) {
607 log.warn("Can't find IP address of gateway {}", gwHost);
608 return;
609 }
610
611 log.debug("LQ: *Existing* NH IP for host is " + nextHopIp.getIp4Address() + " removing route for it");
612 Route route = new Route(Route.Source.STATIC, clientIP.toIpPrefix(), nextHopIp);
613 routeStore.removeRoute(route);
614
615 // remove from temp store
616 dhcpRelayStore.removeDhcpRecord(hostId);
617
618 // and forward to client
619 Ethernet ethernetPacket = processLeaseQueryFromServer(packet);
620 if (ethernetPacket != null) {
621 sendResponseToClient(ethernetPacket, dhcpPayload);
622 }
623 }
624
Yi Tseng4ec727d2017-08-31 11:21:00 -0700625 /**
Yi Tseng51301292017-07-28 13:02:59 -0700626 * Build the DHCP discover/request packet with gateway IP(unicast packet).
627 *
628 * @param context the packet context
629 * @param ethernetPacket the ethernet payload to process
Yi Tseng51301292017-07-28 13:02:59 -0700630 * @return processed packet
631 */
632 private Ethernet processDhcpPacketFromClient(PacketContext context,
Yi Tsengdcef2c22017-08-05 20:34:06 -0700633 Ethernet ethernetPacket) {
Yi Tseng4ec727d2017-08-31 11:21:00 -0700634 // get dhcp header.
635 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
636 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
637 UDP udpPacket = (UDP) ipv4Packet.getPayload();
638 DHCP dhcpPacket = (DHCP) udpPacket.getPayload();
639
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700640 VlanId dhcpConnectVlan = null;
641 MacAddress dhcpConnectMac = null;
642 Ip4Address dhcpServerIp = null;
643 Ip4Address relayAgentIp = null;
644
645 VlanId indirectDhcpConnectVlan = null;
646 MacAddress indirectDhcpConnectMac = null;
647 Ip4Address indirectDhcpServerIp = null;
648 Ip4Address indirectRelayAgentIp = null;
649
650 if (!defaultServerInfoList.isEmpty()) {
651 DhcpServerInfo serverInfo = defaultServerInfoList.get(0);
652 dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
653 dhcpConnectMac = serverInfo.getDhcpConnectMac().orElse(null);
654 dhcpServerIp = serverInfo.getDhcpServerIp4().orElse(null);
655 relayAgentIp = serverInfo.getRelayAgentIp4().orElse(null);
656 }
657
658 if (!indirectServerInfoList.isEmpty()) {
659 DhcpServerInfo indirectServerInfo = indirectServerInfoList.get(0);
660 indirectDhcpConnectVlan = indirectServerInfo.getDhcpConnectVlan().orElse(null);
661 indirectDhcpConnectMac = indirectServerInfo.getDhcpConnectMac().orElse(null);
662 indirectDhcpServerIp = indirectServerInfo.getDhcpServerIp4().orElse(null);
663 indirectRelayAgentIp = indirectServerInfo.getRelayAgentIp4().orElse(null);
664 }
665
Yi Tsengdcef2c22017-08-05 20:34:06 -0700666 Ip4Address clientInterfaceIp =
667 interfaceService.getInterfacesByPort(context.inPacket().receivedFrom())
668 .stream()
669 .map(Interface::ipAddressesList)
670 .flatMap(Collection::stream)
671 .map(InterfaceIpAddress::ipAddress)
672 .filter(IpAddress::isIp4)
673 .map(IpAddress::getIp4Address)
674 .findFirst()
675 .orElse(null);
676 if (clientInterfaceIp == null) {
677 log.warn("Can't find interface IP for client interface for port {}",
678 context.inPacket().receivedFrom());
679 return null;
680 }
Yi Tseng4ec727d2017-08-31 11:21:00 -0700681 boolean isDirectlyConnected = directlyConnected(dhcpPacket);
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700682 Interface serverInterface = isDirectlyConnected ? getDefaultServerInterface() : getIndirectServerInterface();
Yi Tsengdcef2c22017-08-05 20:34:06 -0700683 if (serverInterface == null) {
Yi Tseng4ec727d2017-08-31 11:21:00 -0700684 log.warn("Can't get {} server interface, ignore", isDirectlyConnected ? "direct" : "indirect");
Yi Tsengdcef2c22017-08-05 20:34:06 -0700685 return null;
686 }
Yi Tseng4fa05832017-08-17 13:08:31 -0700687 Ip4Address ipFacingServer = getFirstIpFromInterface(serverInterface);
688 MacAddress macFacingServer = serverInterface.mac();
689 if (ipFacingServer == null || macFacingServer == null) {
Yi Tsengdcef2c22017-08-05 20:34:06 -0700690 log.warn("No IP address for server Interface {}", serverInterface);
Yi Tseng51301292017-07-28 13:02:59 -0700691 return null;
692 }
693 if (dhcpConnectMac == null) {
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700694 log.warn("DHCP Server/Gateway IP not yet resolved .. Aborting DHCP "
Yi Tseng51301292017-07-28 13:02:59 -0700695 + "packet processing from client on port: {}",
Yi Tsengdcef2c22017-08-05 20:34:06 -0700696 context.inPacket().receivedFrom());
Yi Tseng51301292017-07-28 13:02:59 -0700697 return null;
698 }
Yi Tseng4ec727d2017-08-31 11:21:00 -0700699
Yi Tseng4fa05832017-08-17 13:08:31 -0700700 etherReply.setSourceMACAddress(macFacingServer);
Yi Tseng4fa05832017-08-17 13:08:31 -0700701 ipv4Packet.setSourceAddress(ipFacingServer.toInt());
Yi Tseng51301292017-07-28 13:02:59 -0700702
Yi Tseng4ec727d2017-08-31 11:21:00 -0700703 if (isDirectlyConnected) {
Charles Chanb5d24822017-10-10 16:53:32 -0400704 etherReply.setDestinationMACAddress(dhcpConnectMac);
705 etherReply.setVlanID(dhcpConnectVlan.toShort());
706 ipv4Packet.setDestinationAddress(dhcpServerIp.toInt());
707
Yi Tseng51301292017-07-28 13:02:59 -0700708 ConnectPoint inPort = context.inPacket().receivedFrom();
709 VlanId vlanId = VlanId.vlanId(ethernetPacket.getVlanID());
710 // add connected in port and vlan
711 CircuitId cid = new CircuitId(inPort.toString(), vlanId);
712 byte[] circuitId = cid.serialize();
713 DhcpOption circuitIdSubOpt = new DhcpOption();
714 circuitIdSubOpt
715 .setCode(CIRCUIT_ID.getValue())
716 .setLength((byte) circuitId.length)
717 .setData(circuitId);
718
719 DhcpRelayAgentOption newRelayAgentOpt = new DhcpRelayAgentOption();
720 newRelayAgentOpt.setCode(OptionCode_CircuitID.getValue());
721 newRelayAgentOpt.addSubOption(circuitIdSubOpt);
722
Charles Chanb5d24822017-10-10 16:53:32 -0400723 // Removes END option first
Yi Tseng51301292017-07-28 13:02:59 -0700724 List<DhcpOption> options = dhcpPacket.getOptions().stream()
725 .filter(opt -> opt.getCode() != OptionCode_END.getValue())
726 .collect(Collectors.toList());
727
728 // push relay agent option
729 options.add(newRelayAgentOpt);
730
731 // make sure option 255(End) is the last option
732 DhcpOption endOption = new DhcpOption();
733 endOption.setCode(OptionCode_END.getValue());
734 options.add(endOption);
735
736 dhcpPacket.setOptions(options);
Yi Tsengdcef2c22017-08-05 20:34:06 -0700737
Charles Chanb5d24822017-10-10 16:53:32 -0400738 // Sets relay agent IP
739 int effectiveRelayAgentIp = relayAgentIp != null ?
740 relayAgentIp.toInt() : clientInterfaceIp.toInt();
741 dhcpPacket.setGatewayIPAddress(effectiveRelayAgentIp);
742 } else {
743 if (indirectDhcpServerIp != null) {
744 // Use indirect server config for indirect packets if configured
745 etherReply.setDestinationMACAddress(indirectDhcpConnectMac);
746 etherReply.setVlanID(indirectDhcpConnectVlan.toShort());
747 ipv4Packet.setDestinationAddress(indirectDhcpServerIp.toInt());
Yi Tseng51301292017-07-28 13:02:59 -0700748
Charles Chanb5d24822017-10-10 16:53:32 -0400749 // Set giaddr if indirect relay agent IP is configured
750 if (indirectRelayAgentIp != null) {
751 dhcpPacket.setGatewayIPAddress(indirectRelayAgentIp.toInt());
752 }
753 } else {
754 // Otherwise, use default server config for indirect packets
755 etherReply.setDestinationMACAddress(dhcpConnectMac);
756 etherReply.setVlanID(dhcpConnectVlan.toShort());
757 ipv4Packet.setDestinationAddress(dhcpServerIp.toInt());
Yi Tseng4ec727d2017-08-31 11:21:00 -0700758
Charles Chanb5d24822017-10-10 16:53:32 -0400759 // Set giaddr if direct relay agent IP is configured
760 if (relayAgentIp != null) {
761 dhcpPacket.setGatewayIPAddress(relayAgentIp.toInt());
762 }
Yi Tseng4ec727d2017-08-31 11:21:00 -0700763 }
Yi Tseng4fa05832017-08-17 13:08:31 -0700764 }
765
Yi Tsengf41681e2017-10-03 09:58:19 -0700766 // Remove broadcast flag
767 dhcpPacket.setFlags((short) 0);
768
Yi Tseng51301292017-07-28 13:02:59 -0700769 udpPacket.setPayload(dhcpPacket);
Yi Tseng4ec727d2017-08-31 11:21:00 -0700770 // As a DHCP relay, the source port should be server port( instead
771 // of client port.
Yi Tsengdcef2c22017-08-05 20:34:06 -0700772 udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
Yi Tseng51301292017-07-28 13:02:59 -0700773 udpPacket.setDestinationPort(UDP.DHCP_SERVER_PORT);
774 ipv4Packet.setPayload(udpPacket);
Charles Chan7edf7642017-10-09 11:07:25 -0400775 ipv4Packet.setTtl((byte) 64);
Yi Tseng51301292017-07-28 13:02:59 -0700776 etherReply.setPayload(ipv4Packet);
777 return etherReply;
778 }
779
Charles Chan2f9aa2c2017-10-08 23:53:36 -0400780
781 /**
782 * Do a basic routing for a packet from client (used for LQ processing).
783 *
784 * @param context the packet context
785 * @param ethernetPacket the ethernet payload to process
786 * @return processed packet
787 */
788 private Ethernet processLeaseQueryFromAgent(PacketContext context,
789 Ethernet ethernetPacket) {
790 // get dhcp header.
791 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
792 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
793 UDP udpPacket = (UDP) ipv4Packet.getPayload();
794 DHCP dhcpPacket = (DHCP) udpPacket.getPayload();
795
796 VlanId dhcpConnectVlan = null;
797 MacAddress dhcpConnectMac = null;
798 Ip4Address dhcpServerIp = null;
799
800 VlanId indirectDhcpConnectVlan = null;
801 MacAddress indirectDhcpConnectMac = null;
802 Ip4Address indirectDhcpServerIp = null;
803
804 if (!defaultServerInfoList.isEmpty()) {
805 DhcpServerInfo serverInfo = defaultServerInfoList.get(0);
806 dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
807 dhcpConnectMac = serverInfo.getDhcpConnectMac().orElse(null);
808 dhcpServerIp = serverInfo.getDhcpServerIp4().orElse(null);
809 }
810
811 if (!indirectServerInfoList.isEmpty()) {
812 DhcpServerInfo indirectServerInfo = indirectServerInfoList.get(0);
813 indirectDhcpConnectVlan = indirectServerInfo.getDhcpConnectVlan().orElse(null);
814 indirectDhcpConnectMac = indirectServerInfo.getDhcpConnectMac().orElse(null);
815 indirectDhcpServerIp = indirectServerInfo.getDhcpServerIp4().orElse(null);
816 }
817
818 Ip4Address clientInterfaceIp =
819 interfaceService.getInterfacesByPort(context.inPacket().receivedFrom())
820 .stream()
821 .map(Interface::ipAddressesList)
822 .flatMap(Collection::stream)
823 .map(InterfaceIpAddress::ipAddress)
824 .filter(IpAddress::isIp4)
825 .map(IpAddress::getIp4Address)
826 .findFirst()
827 .orElse(null);
828 if (clientInterfaceIp == null) {
829 log.warn("Can't find interface IP for client interface for port {}",
830 context.inPacket().receivedFrom());
831 return null;
832 }
833 boolean isDirectlyConnected = directlyConnected(dhcpPacket);
834 Interface serverInterface = isDirectlyConnected ? getDefaultServerInterface() : getIndirectServerInterface();
835 if (serverInterface == null) {
836 log.warn("Can't get {} server interface, ignore", isDirectlyConnected ? "direct" : "indirect");
837 return null;
838 }
839 Ip4Address ipFacingServer = getFirstIpFromInterface(serverInterface);
840 MacAddress macFacingServer = serverInterface.mac();
841 if (ipFacingServer == null || macFacingServer == null) {
842 log.warn("No IP address for server Interface {}", serverInterface);
843 return null;
844 }
845 if (dhcpConnectMac == null) {
846 log.warn("DHCP server/gateway not yet resolved .. Aborting DHCP "
847 + "packet processing from client on port: {}",
848 context.inPacket().receivedFrom());
849 return null;
850 }
851
852 etherReply.setSourceMACAddress(macFacingServer);
853 etherReply.setDestinationMACAddress(dhcpConnectMac);
854 etherReply.setVlanID(dhcpConnectVlan.toShort());
855 ipv4Packet.setSourceAddress(ipFacingServer.toInt());
856 ipv4Packet.setDestinationAddress(dhcpServerIp.toInt());
857
858 if (indirectDhcpServerIp != null) {
859 // Indirect case, replace destination to indirect dhcp server if exist
860 etherReply.setDestinationMACAddress(indirectDhcpConnectMac);
861 etherReply.setVlanID(indirectDhcpConnectVlan.toShort());
862 ipv4Packet.setDestinationAddress(indirectDhcpServerIp.toInt());
863 }
864
865 udpPacket.setPayload(dhcpPacket);
866 // As a DHCP relay, the source port should be server port( instead
867 // of client port.
868 udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
869 udpPacket.setDestinationPort(UDP.DHCP_SERVER_PORT);
870 ipv4Packet.setPayload(udpPacket);
871 etherReply.setPayload(ipv4Packet);
872 return etherReply;
873 }
874
875
Yi Tseng51301292017-07-28 13:02:59 -0700876 /**
877 * Writes DHCP record to the store according to the request DHCP packet (Discover, Request).
878 *
879 * @param location the location which DHCP packet comes from
880 * @param ethernet the DHCP packet
881 * @param dhcpPayload the DHCP payload
882 */
883 private void writeRequestDhcpRecord(ConnectPoint location,
884 Ethernet ethernet,
885 DHCP dhcpPayload) {
886 VlanId vlanId = VlanId.vlanId(ethernet.getVlanID());
887 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
888 HostId hostId = HostId.hostId(macAddress, vlanId);
889 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
890 if (record == null) {
891 record = new DhcpRecord(HostId.hostId(macAddress, vlanId));
892 } else {
893 record = record.clone();
894 }
895 record.addLocation(new HostLocation(location, System.currentTimeMillis()));
896 record.ip4Status(dhcpPayload.getPacketType());
897 record.setDirectlyConnected(directlyConnected(dhcpPayload));
898 if (!directlyConnected(dhcpPayload)) {
899 // Update gateway mac address if the host is not directly connected
900 record.nextHop(ethernet.getSourceMAC());
901 }
902 record.updateLastSeen();
903 dhcpRelayStore.updateDhcpRecord(HostId.hostId(macAddress, vlanId), record);
904 }
905
906 /**
907 * Writes DHCP record to the store according to the response DHCP packet (Offer, Ack).
908 *
909 * @param ethernet the DHCP packet
910 * @param dhcpPayload the DHCP payload
911 */
912 private void writeResponseDhcpRecord(Ethernet ethernet,
913 DHCP dhcpPayload) {
Yi Tsengdcef2c22017-08-05 20:34:06 -0700914 Optional<Interface> outInterface = getClientInterface(ethernet, dhcpPayload);
Yi Tseng51301292017-07-28 13:02:59 -0700915 if (!outInterface.isPresent()) {
916 log.warn("Failed to determine where to send {}", dhcpPayload.getPacketType());
917 return;
918 }
919
920 Interface outIface = outInterface.get();
921 ConnectPoint location = outIface.connectPoint();
Yi Tseng4ec727d2017-08-31 11:21:00 -0700922 VlanId vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -0700923 if (vlanId == null) {
924 vlanId = outIface.vlan();
925 }
Yi Tseng51301292017-07-28 13:02:59 -0700926 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
927 HostId hostId = HostId.hostId(macAddress, vlanId);
928 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
929 if (record == null) {
930 record = new DhcpRecord(HostId.hostId(macAddress, vlanId));
931 } else {
932 record = record.clone();
933 }
934 record.addLocation(new HostLocation(location, System.currentTimeMillis()));
935 if (dhcpPayload.getPacketType() == DHCP.MsgType.DHCPACK) {
936 record.ip4Address(Ip4Address.valueOf(dhcpPayload.getYourIPAddress()));
937 }
938 record.ip4Status(dhcpPayload.getPacketType());
939 record.setDirectlyConnected(directlyConnected(dhcpPayload));
940 record.updateLastSeen();
941 dhcpRelayStore.updateDhcpRecord(HostId.hostId(macAddress, vlanId), record);
942 }
943
944 /**
945 * Build the DHCP offer/ack with proper client port.
946 *
947 * @param ethernetPacket the original packet comes from server
948 * @return new packet which will send to the client
949 */
950 private Ethernet processDhcpPacketFromServer(Ethernet ethernetPacket) {
951 // get dhcp header.
952 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
953 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
954 UDP udpPacket = (UDP) ipv4Packet.getPayload();
955 DHCP dhcpPayload = (DHCP) udpPacket.getPayload();
956
957 // determine the vlanId of the client host - note that this vlan id
958 // could be different from the vlan in the packet from the server
Yi Tsengdcef2c22017-08-05 20:34:06 -0700959 Interface clientInterface = getClientInterface(ethernetPacket, dhcpPayload).orElse(null);
Yi Tseng51301292017-07-28 13:02:59 -0700960
Yi Tsengdcef2c22017-08-05 20:34:06 -0700961 if (clientInterface == null) {
Yi Tseng51301292017-07-28 13:02:59 -0700962 log.warn("Cannot find the interface for the DHCP {}", dhcpPayload);
963 return null;
964 }
Yi Tsengdcef2c22017-08-05 20:34:06 -0700965 VlanId vlanId;
966 if (clientInterface.vlanTagged().isEmpty()) {
967 vlanId = clientInterface.vlan();
968 } else {
969 // might be multiple vlan in same interface
Yi Tseng4ec727d2017-08-31 11:21:00 -0700970 vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -0700971 }
972 if (vlanId == null) {
973 vlanId = VlanId.NONE;
974 }
975 etherReply.setVlanID(vlanId.toShort());
976 etherReply.setSourceMACAddress(clientInterface.mac());
Yi Tseng51301292017-07-28 13:02:59 -0700977
Yi Tsengdcef2c22017-08-05 20:34:06 -0700978 if (!directlyConnected(dhcpPayload)) {
979 // if client is indirectly connected, try use next hop mac address
980 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
981 HostId hostId = HostId.hostId(macAddress, vlanId);
982 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
983 if (record != null) {
984 // if next hop can be found, use mac address of next hop
985 record.nextHop().ifPresent(etherReply::setDestinationMACAddress);
986 } else {
987 // otherwise, discard the packet
988 log.warn("Can't find record for host id {}, discard packet", hostId);
989 return null;
990 }
Yi Tsengc03fa242017-08-17 17:43:38 -0700991 } else {
992 etherReply.setDestinationMACAddress(dhcpPayload.getClientHardwareAddress());
Yi Tsengdcef2c22017-08-05 20:34:06 -0700993 }
994
Yi Tseng51301292017-07-28 13:02:59 -0700995 // we leave the srcMac from the original packet
Yi Tseng51301292017-07-28 13:02:59 -0700996 // figure out the relay agent IP corresponding to the original request
Yi Tseng4fa05832017-08-17 13:08:31 -0700997 Ip4Address ipFacingClient = getFirstIpFromInterface(clientInterface);
998 if (ipFacingClient == null) {
Yi Tseng51301292017-07-28 13:02:59 -0700999 log.warn("Cannot determine relay agent interface Ipv4 addr for host {}/{}. "
1000 + "Aborting relay for dhcp packet from server {}",
Yi Tsengdcef2c22017-08-05 20:34:06 -07001001 etherReply.getDestinationMAC(), clientInterface.vlan(),
Yi Tseng51301292017-07-28 13:02:59 -07001002 ethernetPacket);
1003 return null;
1004 }
1005 // SRC_IP: relay agent IP
1006 // DST_IP: offered IP
Yi Tseng4fa05832017-08-17 13:08:31 -07001007 ipv4Packet.setSourceAddress(ipFacingClient.toInt());
Yi Tseng51301292017-07-28 13:02:59 -07001008 ipv4Packet.setDestinationAddress(dhcpPayload.getYourIPAddress());
1009 udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
1010 if (directlyConnected(dhcpPayload)) {
1011 udpPacket.setDestinationPort(UDP.DHCP_CLIENT_PORT);
1012 } else {
1013 // forward to another dhcp relay
Yi Tseng72b599a2017-09-14 13:24:21 -07001014 // FIXME: Currently we assume the DHCP comes from a L2 relay with
1015 // Option 82, this might not work if DHCP message comes from
1016 // L3 relay.
1017 udpPacket.setDestinationPort(UDP.DHCP_CLIENT_PORT);
Yi Tseng51301292017-07-28 13:02:59 -07001018 }
1019
1020 udpPacket.setPayload(dhcpPayload);
1021 ipv4Packet.setPayload(udpPacket);
1022 etherReply.setPayload(ipv4Packet);
1023 return etherReply;
1024 }
1025
Yi Tsengdcef2c22017-08-05 20:34:06 -07001026 /**
Charles Chan2f9aa2c2017-10-08 23:53:36 -04001027 * Build the DHCP offer/ack with proper client port.
1028 *
1029 * @param ethernetPacket the original packet comes from server
1030 * @return new packet which will send to the client
1031 */
1032 private Ethernet processLeaseQueryFromServer(Ethernet ethernetPacket) {
1033 // get dhcp header.
1034 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
1035 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
1036 UDP udpPacket = (UDP) ipv4Packet.getPayload();
1037 DHCP dhcpPayload = (DHCP) udpPacket.getPayload();
1038
1039 // determine the vlanId of the client host - note that this vlan id
1040 // could be different from the vlan in the packet from the server
1041 Interface clientInterface = getClientInterface(ethernetPacket, dhcpPayload).orElse(null);
1042
1043 if (clientInterface == null) {
1044 log.warn("Cannot find the interface for the DHCP {}", dhcpPayload);
1045 return null;
1046 }
1047 VlanId vlanId;
1048 if (clientInterface.vlanTagged().isEmpty()) {
1049 vlanId = clientInterface.vlan();
1050 } else {
1051 // might be multiple vlan in same interface
1052 vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
1053 }
1054 if (vlanId == null) {
1055 vlanId = VlanId.NONE;
1056 }
1057 etherReply.setVlanID(vlanId.toShort());
1058 etherReply.setSourceMACAddress(clientInterface.mac());
1059
1060 if (!directlyConnected(dhcpPayload)) {
1061 // if client is indirectly connected, try use next hop mac address
1062 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
1063 HostId hostId = HostId.hostId(macAddress, vlanId);
1064 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1065 if (record != null) {
1066 // if next hop can be found, use mac address of next hop
1067 record.nextHop().ifPresent(etherReply::setDestinationMACAddress);
1068 } else {
1069 // otherwise, discard the packet
1070 log.warn("Can't find record for host id {}, discard packet", hostId);
1071 return null;
1072 }
1073 } else {
1074 etherReply.setDestinationMACAddress(dhcpPayload.getClientHardwareAddress());
1075 }
1076
1077 // default is client port
1078 udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
1079 udpPacket.setDestinationPort(UDP.DHCP_CLIENT_PORT);
1080
1081 udpPacket.setPayload(dhcpPayload);
1082 ipv4Packet.setPayload(udpPacket);
1083 etherReply.setPayload(ipv4Packet);
1084 return etherReply;
1085 }
1086 /**
Yi Tsengdcef2c22017-08-05 20:34:06 -07001087 * Extracts VLAN ID from relay agent option.
1088 *
1089 * @param dhcpPayload the DHCP payload
1090 * @return VLAN ID from DHCP payload; null if not exists
1091 */
Yi Tseng4ec727d2017-08-31 11:21:00 -07001092 private VlanId getVlanIdFromRelayAgentOption(DHCP dhcpPayload) {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001093 DhcpRelayAgentOption option = (DhcpRelayAgentOption) dhcpPayload.getOption(OptionCode_CircuitID);
1094 if (option == null) {
1095 return null;
1096 }
1097 DhcpOption circuitIdSubOption = option.getSubOption(CIRCUIT_ID.getValue());
1098 if (circuitIdSubOption == null) {
1099 return null;
1100 }
1101 try {
1102 CircuitId circuitId = CircuitId.deserialize(circuitIdSubOption.getData());
1103 return circuitId.vlanId();
1104 } catch (IllegalArgumentException e) {
1105 // can't deserialize the circuit ID
1106 return null;
1107 }
1108 }
1109
1110 /**
1111 * Removes DHCP relay agent information option (option 82) from DHCP payload.
1112 * Also reset giaddr to 0
1113 *
1114 * @param ethPacket the Ethernet packet to be processed
1115 * @return Ethernet packet processed
1116 */
1117 private Ethernet removeRelayAgentOption(Ethernet ethPacket) {
1118 Ethernet ethernet = (Ethernet) ethPacket.clone();
1119 IPv4 ipv4 = (IPv4) ethernet.getPayload();
1120 UDP udp = (UDP) ipv4.getPayload();
1121 DHCP dhcpPayload = (DHCP) udp.getPayload();
1122
1123 // removes relay agent information option
1124 List<DhcpOption> options = dhcpPayload.getOptions();
1125 options = options.stream()
1126 .filter(option -> option.getCode() != OptionCode_CircuitID.getValue())
1127 .collect(Collectors.toList());
1128 dhcpPayload.setOptions(options);
1129 dhcpPayload.setGatewayIPAddress(0);
1130
1131 udp.setPayload(dhcpPayload);
1132 ipv4.setPayload(udp);
1133 ethernet.setPayload(ipv4);
1134 return ethernet;
1135 }
1136
Yi Tseng51301292017-07-28 13:02:59 -07001137
1138 /**
1139 * Check if the host is directly connected to the network or not.
1140 *
1141 * @param dhcpPayload the dhcp payload
1142 * @return true if the host is directly connected to the network; false otherwise
1143 */
1144 private boolean directlyConnected(DHCP dhcpPayload) {
Yi Tseng2cf59912017-08-24 14:47:34 -07001145 DhcpRelayAgentOption relayAgentOption =
1146 (DhcpRelayAgentOption) dhcpPayload.getOption(OptionCode_CircuitID);
Yi Tseng51301292017-07-28 13:02:59 -07001147
1148 // Doesn't contains relay option
1149 if (relayAgentOption == null) {
1150 return true;
1151 }
1152
Yi Tseng2cf59912017-08-24 14:47:34 -07001153 // check circuit id, if circuit id is invalid, we say it is an indirect host
1154 DhcpOption circuitIdOpt = relayAgentOption.getSubOption(CIRCUIT_ID.getValue());
Yi Tseng51301292017-07-28 13:02:59 -07001155
Yi Tseng2cf59912017-08-24 14:47:34 -07001156 try {
1157 CircuitId.deserialize(circuitIdOpt.getData());
Yi Tseng51301292017-07-28 13:02:59 -07001158 return true;
Yi Tseng2cf59912017-08-24 14:47:34 -07001159 } catch (Exception e) {
1160 // invalid circuit id
1161 return false;
Yi Tseng51301292017-07-28 13:02:59 -07001162 }
Yi Tseng51301292017-07-28 13:02:59 -07001163 }
1164
1165
1166 /**
1167 * Send the DHCP ack to the requester host.
1168 * Modify Host or Route store according to the type of DHCP.
1169 *
1170 * @param ethernetPacketAck the packet
1171 * @param dhcpPayload the DHCP data
1172 */
1173 private void handleDhcpAck(Ethernet ethernetPacketAck, DHCP dhcpPayload) {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001174 Optional<Interface> outInterface = getClientInterface(ethernetPacketAck, dhcpPayload);
Yi Tseng51301292017-07-28 13:02:59 -07001175 if (!outInterface.isPresent()) {
1176 log.warn("Can't find output interface for dhcp: {}", dhcpPayload);
1177 return;
1178 }
1179
1180 Interface outIface = outInterface.get();
1181 HostLocation hostLocation = new HostLocation(outIface.connectPoint(), System.currentTimeMillis());
1182 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
Yi Tseng4ec727d2017-08-31 11:21:00 -07001183 VlanId vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -07001184 if (vlanId == null) {
1185 vlanId = outIface.vlan();
1186 }
Yi Tseng51301292017-07-28 13:02:59 -07001187 HostId hostId = HostId.hostId(macAddress, vlanId);
1188 Ip4Address ip = Ip4Address.valueOf(dhcpPayload.getYourIPAddress());
1189
1190 if (directlyConnected(dhcpPayload)) {
1191 // Add to host store if it connect to network directly
1192 Set<IpAddress> ips = Sets.newHashSet(ip);
Yi Tseng4b013202017-09-08 17:22:51 -07001193 Host host = hostService.getHost(hostId);
Yi Tseng51301292017-07-28 13:02:59 -07001194
Yi Tseng4b013202017-09-08 17:22:51 -07001195 Set<HostLocation> hostLocations = Sets.newHashSet(hostLocation);
1196 if (host != null) {
1197 // Dual homing support:
1198 // if host exists, use old locations and new location
1199 hostLocations.addAll(host.locations());
1200 }
1201 HostDescription desc = new DefaultHostDescription(macAddress, vlanId,
1202 hostLocations, ips, false);
1203 // Add IP address when dhcp server give the host new ip address
1204 providerService.hostDetected(hostId, desc, false);
Yi Tseng51301292017-07-28 13:02:59 -07001205 } else {
1206 // Add to route store if it does not connect to network directly
1207 // Get gateway host IP according to host mac address
Yi Tsengdcef2c22017-08-05 20:34:06 -07001208 // TODO: remove relay store here
Yi Tseng51301292017-07-28 13:02:59 -07001209 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1210
1211 if (record == null) {
1212 log.warn("Can't find DHCP record of host {}", hostId);
1213 return;
1214 }
1215
1216 MacAddress gwMac = record.nextHop().orElse(null);
1217 if (gwMac == null) {
1218 log.warn("Can't find gateway mac address from record {}", record);
1219 return;
1220 }
1221
1222 HostId gwHostId = HostId.hostId(gwMac, record.vlanId());
1223 Host gwHost = hostService.getHost(gwHostId);
1224
1225 if (gwHost == null) {
1226 log.warn("Can't find gateway host {}", gwHostId);
1227 return;
1228 }
1229
1230 Ip4Address nextHopIp = gwHost.ipAddresses()
1231 .stream()
1232 .filter(IpAddress::isIp4)
1233 .map(IpAddress::getIp4Address)
1234 .findFirst()
1235 .orElse(null);
1236
1237 if (nextHopIp == null) {
1238 log.warn("Can't find IP address of gateway {}", gwHost);
1239 return;
1240 }
1241
1242 Route route = new Route(Route.Source.STATIC, ip.toIpPrefix(), nextHopIp);
1243 routeStore.updateRoute(route);
1244 }
Yi Tseng51301292017-07-28 13:02:59 -07001245 }
1246
1247 /**
1248 * forward the packet to ConnectPoint where the DHCP server is attached.
1249 *
1250 * @param packet the packet
1251 */
Yi Tseng4ec727d2017-08-31 11:21:00 -07001252 private void handleDhcpDiscoverAndRequest(Ethernet packet, DHCP dhcpPayload) {
Yi Tseng2fe8f3f2017-09-07 16:22:51 -07001253 boolean direct = directlyConnected(dhcpPayload);
1254 DhcpServerInfo serverInfo = defaultServerInfoList.get(0);
1255 if (!direct && !indirectServerInfoList.isEmpty()) {
1256 serverInfo = indirectServerInfoList.get(0);
Yi Tseng4ec727d2017-08-31 11:21:00 -07001257 }
Yi Tseng2fe8f3f2017-09-07 16:22:51 -07001258 ConnectPoint portToFotward = serverInfo.getDhcpServerConnectPoint().orElse(null);
Yi Tseng51301292017-07-28 13:02:59 -07001259 // send packet to dhcp server connect point.
Yi Tseng4ec727d2017-08-31 11:21:00 -07001260 if (portToFotward != null) {
Yi Tseng51301292017-07-28 13:02:59 -07001261 TrafficTreatment t = DefaultTrafficTreatment.builder()
Yi Tseng4ec727d2017-08-31 11:21:00 -07001262 .setOutput(portToFotward.port()).build();
Yi Tseng51301292017-07-28 13:02:59 -07001263 OutboundPacket o = new DefaultOutboundPacket(
Yi Tseng4ec727d2017-08-31 11:21:00 -07001264 portToFotward.deviceId(), t, ByteBuffer.wrap(packet.serialize()));
Yi Tseng51301292017-07-28 13:02:59 -07001265 if (log.isTraceEnabled()) {
1266 log.trace("Relaying packet to dhcp server {}", packet);
1267 }
1268 packetService.emit(o);
1269 } else {
1270 log.warn("Can't find DHCP server connect point, abort.");
1271 }
1272 }
1273
1274
1275 /**
1276 * Gets output interface of a dhcp packet.
1277 * If option 82 exists in the dhcp packet and the option was sent by
Yi Tseng4ec727d2017-08-31 11:21:00 -07001278 * ONOS (circuit format is correct), use the connect
Yi Tseng51301292017-07-28 13:02:59 -07001279 * point and vlan id from circuit id; otherwise, find host by destination
1280 * address and use vlan id from sender (dhcp server).
1281 *
1282 * @param ethPacket the ethernet packet
1283 * @param dhcpPayload the dhcp packet
1284 * @return an interface represent the output port and vlan; empty value
1285 * if the host or circuit id not found
1286 */
Yi Tsengdcef2c22017-08-05 20:34:06 -07001287 private Optional<Interface> getClientInterface(Ethernet ethPacket, DHCP dhcpPayload) {
Yi Tseng51301292017-07-28 13:02:59 -07001288 VlanId originalPacketVlanId = VlanId.vlanId(ethPacket.getVlanID());
Yi Tseng51301292017-07-28 13:02:59 -07001289 DhcpRelayAgentOption option = (DhcpRelayAgentOption) dhcpPayload.getOption(OptionCode_CircuitID);
1290
Yi Tseng4ec727d2017-08-31 11:21:00 -07001291 DhcpOption circuitIdSubOption = option.getSubOption(CIRCUIT_ID.getValue());
1292 try {
1293 CircuitId circuitId = CircuitId.deserialize(circuitIdSubOption.getData());
1294 ConnectPoint connectPoint = ConnectPoint.deviceConnectPoint(circuitId.connectPoint());
1295 VlanId vlanId = circuitId.vlanId();
1296 return interfaceService.getInterfacesByPort(connectPoint)
1297 .stream()
1298 .filter(iface -> interfaceContainsVlan(iface, vlanId))
1299 .findFirst();
1300 } catch (IllegalArgumentException ex) {
1301 // invalid circuit format, didn't sent by ONOS
1302 log.debug("Invalid circuit {}, use information from dhcp payload",
1303 circuitIdSubOption.getData());
Yi Tseng51301292017-07-28 13:02:59 -07001304 }
1305
1306 // Use Vlan Id from DHCP server if DHCP relay circuit id was not
1307 // sent by ONOS or circuit Id can't be parsed
Yi Tsengdcef2c22017-08-05 20:34:06 -07001308 // TODO: remove relay store from this method
Yi Tseng51301292017-07-28 13:02:59 -07001309 MacAddress dstMac = valueOf(dhcpPayload.getClientHardwareAddress());
1310 Optional<DhcpRecord> dhcpRecord = dhcpRelayStore.getDhcpRecord(HostId.hostId(dstMac, originalPacketVlanId));
Yi Tsengdcef2c22017-08-05 20:34:06 -07001311 ConnectPoint clientConnectPoint = dhcpRecord
Yi Tseng51301292017-07-28 13:02:59 -07001312 .map(DhcpRecord::locations)
1313 .orElse(Collections.emptySet())
1314 .stream()
1315 .reduce((hl1, hl2) -> {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001316 // find latest host connect point
Yi Tseng51301292017-07-28 13:02:59 -07001317 if (hl1 == null || hl2 == null) {
1318 return hl1 == null ? hl2 : hl1;
1319 }
1320 return hl1.time() > hl2.time() ? hl1 : hl2;
1321 })
Yi Tsengdcef2c22017-08-05 20:34:06 -07001322 .orElse(null);
Yi Tseng51301292017-07-28 13:02:59 -07001323
Yi Tsengdcef2c22017-08-05 20:34:06 -07001324 if (clientConnectPoint != null) {
1325 return interfaceService.getInterfacesByPort(clientConnectPoint)
1326 .stream()
Yi Tseng4ec727d2017-08-31 11:21:00 -07001327 .filter(iface -> interfaceContainsVlan(iface, originalPacketVlanId))
Yi Tsengdcef2c22017-08-05 20:34:06 -07001328 .findFirst();
1329 }
1330 return Optional.empty();
Yi Tseng51301292017-07-28 13:02:59 -07001331 }
1332
1333 /**
1334 * Send the response DHCP to the requester host.
1335 *
1336 * @param ethPacket the packet
1337 * @param dhcpPayload the DHCP data
1338 */
1339 private void sendResponseToClient(Ethernet ethPacket, DHCP dhcpPayload) {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001340 Optional<Interface> outInterface = getClientInterface(ethPacket, dhcpPayload);
1341 if (directlyConnected(dhcpPayload)) {
1342 ethPacket = removeRelayAgentOption(ethPacket);
1343 }
1344 if (!outInterface.isPresent()) {
1345 log.warn("Can't find output interface for client, ignore");
1346 return;
1347 }
1348 Interface outIface = outInterface.get();
1349 TrafficTreatment treatment = DefaultTrafficTreatment.builder()
1350 .setOutput(outIface.connectPoint().port())
1351 .build();
1352 OutboundPacket o = new DefaultOutboundPacket(
1353 outIface.connectPoint().deviceId(),
1354 treatment,
1355 ByteBuffer.wrap(ethPacket.serialize()));
1356 if (log.isTraceEnabled()) {
1357 log.trace("Relaying packet to DHCP client {} via {}, vlan {}",
1358 ethPacket,
1359 outIface.connectPoint(),
1360 outIface.vlan());
1361 }
1362 packetService.emit(o);
Yi Tseng51301292017-07-28 13:02:59 -07001363 }
Yi Tsenge72fbb52017-08-02 15:03:31 -07001364
Yi Tseng4b013202017-09-08 17:22:51 -07001365 @Override
1366 public void triggerProbe(Host host) {
1367 // Do nothing here
1368 }
1369
1370 @Override
1371 public ProviderId id() {
Charles Chan75edab72017-09-12 17:09:32 -07001372 return PROVIDER_ID;
Yi Tseng4b013202017-09-08 17:22:51 -07001373 }
1374
Yi Tsenge72fbb52017-08-02 15:03:31 -07001375 class InternalHostListener implements HostListener {
1376 @Override
1377 public void event(HostEvent event) {
Yi Tseng2fe8f3f2017-09-07 16:22:51 -07001378 if (!configured()) {
1379 return;
1380 }
Yi Tsenge72fbb52017-08-02 15:03:31 -07001381 switch (event.type()) {
1382 case HOST_ADDED:
1383 case HOST_UPDATED:
1384 hostUpdated(event.subject());
1385 break;
1386 case HOST_REMOVED:
1387 hostRemoved(event.subject());
1388 break;
Yi Tsenge72fbb52017-08-02 15:03:31 -07001389 default:
1390 break;
1391 }
1392 }
1393 }
1394
1395 /**
Yi Tsenge72fbb52017-08-02 15:03:31 -07001396 * Handle host updated.
1397 * If the host is DHCP server or gateway, update connect mac and vlan.
1398 *
1399 * @param host the host
1400 */
1401 private void hostUpdated(Host host) {
Yi Tseng7da339e2017-10-23 19:39:39 -07001402 hostUpdated(host, defaultServerInfoList);
1403 hostUpdated(host, indirectServerInfoList);
Yi Tsenge72fbb52017-08-02 15:03:31 -07001404 }
1405
Yi Tseng7da339e2017-10-23 19:39:39 -07001406 private void hostUpdated(Host host, List<DhcpServerInfo> srverInfoList) {
1407 DhcpServerInfo serverInfo;
1408 Ip4Address targetIp;
1409 if (!srverInfoList.isEmpty()) {
1410 serverInfo = srverInfoList.get(0);
1411 targetIp = serverInfo.getDhcpGatewayIp4().orElse(null);
1412 Ip4Address serverIp = serverInfo.getDhcpServerIp4().orElse(null);
1413
1414 if (targetIp == null) {
1415 targetIp = serverIp;
1416 }
1417
1418 if (targetIp != null) {
1419 if (host.ipAddresses().contains(targetIp)) {
1420 serverInfo.setDhcpConnectMac(host.mac());
1421 serverInfo.setDhcpConnectVlan(host.vlan());
1422 requestDhcpPacket(serverIp);
1423 }
1424 }
1425 }
1426 }
1427
1428
Yi Tsenge72fbb52017-08-02 15:03:31 -07001429 /**
1430 * Handle host removed.
1431 * If the host is DHCP server or gateway, unset connect mac and vlan.
1432 *
1433 * @param host the host
1434 */
1435 private void hostRemoved(Host host) {
Yi Tseng7da339e2017-10-23 19:39:39 -07001436 hostRemoved(host, defaultServerInfoList);
1437 hostRemoved(host, indirectServerInfoList);
1438 }
1439
1440 private void hostRemoved(Host host, List<DhcpServerInfo> serverInfoList) {
Yi Tseng2fe8f3f2017-09-07 16:22:51 -07001441 DhcpServerInfo serverInfo;
Yi Tseng7da339e2017-10-23 19:39:39 -07001442 Ip4Address targetIp;
1443 if (!serverInfoList.isEmpty()) {
1444 serverInfo = serverInfoList.get(0);
1445 Ip4Address serverIp = serverInfo.getDhcpServerIp4().orElse(null);
1446 targetIp = serverInfo.getDhcpGatewayIp4().orElse(null);
Yi Tseng2fe8f3f2017-09-07 16:22:51 -07001447
Yi Tseng7da339e2017-10-23 19:39:39 -07001448 if (targetIp == null) {
1449 targetIp = serverIp;
Yi Tseng2fe8f3f2017-09-07 16:22:51 -07001450 }
Yi Tseng7da339e2017-10-23 19:39:39 -07001451
1452 if (targetIp != null) {
1453 if (host.ipAddresses().contains(targetIp)) {
Yi Tseng2fe8f3f2017-09-07 16:22:51 -07001454 serverInfo.setDhcpConnectVlan(null);
1455 serverInfo.setDhcpConnectMac(null);
Yi Tseng7da339e2017-10-23 19:39:39 -07001456 cancelDhcpPacket(serverIp);
Yi Tseng2fe8f3f2017-09-07 16:22:51 -07001457 }
Yi Tsenge72fbb52017-08-02 15:03:31 -07001458 }
Yi Tsenge72fbb52017-08-02 15:03:31 -07001459 }
Yi Tseng7da339e2017-10-23 19:39:39 -07001460 }
Yi Tseng2fe8f3f2017-09-07 16:22:51 -07001461
Yi Tseng7da339e2017-10-23 19:39:39 -07001462 private void requestDhcpPacket(Ip4Address serverIp) {
1463 requestServerDhcpPacket(serverIp);
1464 requestClientDhcpPacket(serverIp);
1465 }
Yi Tseng2fe8f3f2017-09-07 16:22:51 -07001466
Yi Tseng7da339e2017-10-23 19:39:39 -07001467 private void cancelDhcpPacket(Ip4Address serverIp) {
1468 cancelServerDhcpPacket(serverIp);
1469 cancelClientDhcpPacket(serverIp);
1470 }
1471
1472 private void cancelServerDhcpPacket(Ip4Address serverIp) {
1473 TrafficSelector serverSelector =
1474 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1475 .matchIPSrc(serverIp.toIpPrefix())
1476 .build();
1477 packetService.cancelPackets(serverSelector,
1478 PacketPriority.CONTROL,
1479 appId);
1480 }
1481
1482 private void requestServerDhcpPacket(Ip4Address serverIp) {
1483 TrafficSelector serverSelector =
1484 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1485 .matchIPSrc(serverIp.toIpPrefix())
1486 .build();
1487 packetService.requestPackets(serverSelector,
1488 PacketPriority.CONTROL,
1489 appId);
1490 }
1491
1492 private void cancelClientDhcpPacket(Ip4Address serverIp) {
1493 // Packet comes from relay
1494 TrafficSelector indirectClientSelector =
1495 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1496 .matchIPDst(serverIp.toIpPrefix())
1497 .build();
1498 packetService.cancelPackets(indirectClientSelector,
1499 PacketPriority.CONTROL,
1500 appId);
1501
1502 // Packet comes from client
1503 packetService.cancelPackets(CLIENT_SERVER_SELECTOR,
1504 PacketPriority.CONTROL,
1505 appId);
1506 }
1507
1508 private void requestClientDhcpPacket(Ip4Address serverIp) {
1509 // Packet comes from relay
1510 TrafficSelector indirectClientSelector =
1511 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1512 .matchIPDst(serverIp.toIpPrefix())
1513 .build();
1514 packetService.requestPackets(indirectClientSelector,
1515 PacketPriority.CONTROL,
1516 appId);
1517
1518 // Packet comes from client
1519 packetService.requestPackets(CLIENT_SERVER_SELECTOR,
1520 PacketPriority.CONTROL,
1521 appId);
1522 }
1523
1524 /**
1525 * Process the ignore rules.
1526 *
1527 * @param deviceId the device id
1528 * @param vlanId the vlan to be ignored
1529 * @param op the operation, ADD to install; REMOVE to uninstall rules
1530 */
1531 private void processIgnoreVlanRule(DeviceId deviceId, VlanId vlanId, Objective.Operation op) {
1532 TrafficTreatment dropTreatment = DefaultTrafficTreatment.builder().wipeDeferred().build();
1533 AtomicInteger installedCount = new AtomicInteger(DHCP_SELECTORS.size());
1534 DHCP_SELECTORS.forEach(trafficSelector -> {
1535 TrafficSelector selector = DefaultTrafficSelector.builder(trafficSelector)
1536 .matchVlanId(vlanId)
1537 .build();
1538
1539 ForwardingObjective.Builder builder = DefaultForwardingObjective.builder()
1540 .withFlag(ForwardingObjective.Flag.VERSATILE)
1541 .withSelector(selector)
1542 .withPriority(IGNORE_CONTROL_PRIORITY)
1543 .withTreatment(dropTreatment)
1544 .fromApp(appId);
1545
1546
1547 ObjectiveContext objectiveContext = new ObjectiveContext() {
1548 @Override
1549 public void onSuccess(Objective objective) {
1550 log.info("Ignore rule {} (Vlan id {}, device {}, selector {})",
1551 op, vlanId, deviceId, selector);
1552 int countDown = installedCount.decrementAndGet();
1553 if (countDown != 0) {
1554 return;
1555 }
1556 switch (op) {
1557 case ADD:
1558 ignoredVlans.put(deviceId, vlanId);
1559 break;
1560 case REMOVE:
1561 ignoredVlans.remove(deviceId, vlanId);
1562 break;
1563 default:
1564 log.warn("Unsupported objective operation {}", op);
1565 break;
1566 }
Yi Tseng2fe8f3f2017-09-07 16:22:51 -07001567 }
Yi Tseng7da339e2017-10-23 19:39:39 -07001568
1569 @Override
1570 public void onError(Objective objective, ObjectiveError error) {
1571 log.warn("Can't {} ignore rule (vlan id {}, selector {}, device {}) due to {}",
1572 op, vlanId, selector, deviceId, error);
Yi Tseng2fe8f3f2017-09-07 16:22:51 -07001573 }
Yi Tseng7da339e2017-10-23 19:39:39 -07001574 };
1575
1576 ForwardingObjective fwd;
1577 switch (op) {
1578 case ADD:
1579 fwd = builder.add(objectiveContext);
1580 break;
1581 case REMOVE:
1582 fwd = builder.remove(objectiveContext);
1583 break;
1584 default:
1585 log.warn("Unsupported objective operation {}", op);
1586 return;
Yi Tseng4ec727d2017-08-31 11:21:00 -07001587 }
Yi Tseng7da339e2017-10-23 19:39:39 -07001588
1589 Device device = deviceService.getDevice(deviceId);
1590 if (device == null || !device.is(Pipeliner.class)) {
1591 log.warn("Device {} is not available now, wait until device is available", deviceId);
1592 return;
1593 }
1594 flowObjectiveService.apply(deviceId, fwd);
1595 });
Yi Tsenge72fbb52017-08-02 15:03:31 -07001596 }
Yi Tseng51301292017-07-28 13:02:59 -07001597}