blob: 6c5390c91a7855249830e80cb582e85650eeead1 [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 Tsengc44dc2e2017-11-03 16:27:32 -0700634 ConnectPoint receivedFrom = context.inPacket().receivedFrom();
635 DeviceId receivedFromDevice = receivedFrom.deviceId();
636
Yi Tseng4ec727d2017-08-31 11:21:00 -0700637 // get dhcp header.
638 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
639 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
640 UDP udpPacket = (UDP) ipv4Packet.getPayload();
641 DHCP dhcpPacket = (DHCP) udpPacket.getPayload();
642
Yi Tsengc44dc2e2017-11-03 16:27:32 -0700643 // TODO: refactor
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700644 VlanId dhcpConnectVlan = null;
645 MacAddress dhcpConnectMac = null;
646 Ip4Address dhcpServerIp = null;
647 Ip4Address relayAgentIp = null;
648
649 VlanId indirectDhcpConnectVlan = null;
650 MacAddress indirectDhcpConnectMac = null;
651 Ip4Address indirectDhcpServerIp = null;
652 Ip4Address indirectRelayAgentIp = null;
653
654 if (!defaultServerInfoList.isEmpty()) {
655 DhcpServerInfo serverInfo = defaultServerInfoList.get(0);
656 dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
657 dhcpConnectMac = serverInfo.getDhcpConnectMac().orElse(null);
658 dhcpServerIp = serverInfo.getDhcpServerIp4().orElse(null);
Yi Tsengc44dc2e2017-11-03 16:27:32 -0700659 relayAgentIp = serverInfo.getRelayAgentIp4(receivedFromDevice).orElse(null);
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700660 }
661
662 if (!indirectServerInfoList.isEmpty()) {
663 DhcpServerInfo indirectServerInfo = indirectServerInfoList.get(0);
664 indirectDhcpConnectVlan = indirectServerInfo.getDhcpConnectVlan().orElse(null);
665 indirectDhcpConnectMac = indirectServerInfo.getDhcpConnectMac().orElse(null);
666 indirectDhcpServerIp = indirectServerInfo.getDhcpServerIp4().orElse(null);
Yi Tsengc44dc2e2017-11-03 16:27:32 -0700667 indirectRelayAgentIp = indirectServerInfo.getRelayAgentIp4(receivedFromDevice).orElse(null);
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700668 }
669
Yi Tsengdcef2c22017-08-05 20:34:06 -0700670 Ip4Address clientInterfaceIp =
671 interfaceService.getInterfacesByPort(context.inPacket().receivedFrom())
672 .stream()
673 .map(Interface::ipAddressesList)
674 .flatMap(Collection::stream)
675 .map(InterfaceIpAddress::ipAddress)
676 .filter(IpAddress::isIp4)
677 .map(IpAddress::getIp4Address)
678 .findFirst()
679 .orElse(null);
680 if (clientInterfaceIp == null) {
681 log.warn("Can't find interface IP for client interface for port {}",
682 context.inPacket().receivedFrom());
683 return null;
684 }
Yi Tseng4ec727d2017-08-31 11:21:00 -0700685 boolean isDirectlyConnected = directlyConnected(dhcpPacket);
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700686 Interface serverInterface = isDirectlyConnected ? getDefaultServerInterface() : getIndirectServerInterface();
Yi Tsengdcef2c22017-08-05 20:34:06 -0700687 if (serverInterface == null) {
Yi Tseng4ec727d2017-08-31 11:21:00 -0700688 log.warn("Can't get {} server interface, ignore", isDirectlyConnected ? "direct" : "indirect");
Yi Tsengdcef2c22017-08-05 20:34:06 -0700689 return null;
690 }
Yi Tseng4fa05832017-08-17 13:08:31 -0700691 Ip4Address ipFacingServer = getFirstIpFromInterface(serverInterface);
692 MacAddress macFacingServer = serverInterface.mac();
693 if (ipFacingServer == null || macFacingServer == null) {
Yi Tsengdcef2c22017-08-05 20:34:06 -0700694 log.warn("No IP address for server Interface {}", serverInterface);
Yi Tseng51301292017-07-28 13:02:59 -0700695 return null;
696 }
697 if (dhcpConnectMac == null) {
Yi Tseng2fe8f3f2017-09-07 16:22:51 -0700698 log.warn("DHCP Server/Gateway IP not yet resolved .. Aborting DHCP "
Yi Tseng51301292017-07-28 13:02:59 -0700699 + "packet processing from client on port: {}",
Yi Tsengdcef2c22017-08-05 20:34:06 -0700700 context.inPacket().receivedFrom());
Yi Tseng51301292017-07-28 13:02:59 -0700701 return null;
702 }
Yi Tseng4ec727d2017-08-31 11:21:00 -0700703
Yi Tseng4fa05832017-08-17 13:08:31 -0700704 etherReply.setSourceMACAddress(macFacingServer);
Yi Tseng4fa05832017-08-17 13:08:31 -0700705 ipv4Packet.setSourceAddress(ipFacingServer.toInt());
Yi Tseng51301292017-07-28 13:02:59 -0700706
Yi Tseng4ec727d2017-08-31 11:21:00 -0700707 if (isDirectlyConnected) {
Charles Chanb5d24822017-10-10 16:53:32 -0400708 etherReply.setDestinationMACAddress(dhcpConnectMac);
709 etherReply.setVlanID(dhcpConnectVlan.toShort());
710 ipv4Packet.setDestinationAddress(dhcpServerIp.toInt());
711
Yi Tseng51301292017-07-28 13:02:59 -0700712 ConnectPoint inPort = context.inPacket().receivedFrom();
713 VlanId vlanId = VlanId.vlanId(ethernetPacket.getVlanID());
714 // add connected in port and vlan
715 CircuitId cid = new CircuitId(inPort.toString(), vlanId);
716 byte[] circuitId = cid.serialize();
717 DhcpOption circuitIdSubOpt = new DhcpOption();
718 circuitIdSubOpt
719 .setCode(CIRCUIT_ID.getValue())
720 .setLength((byte) circuitId.length)
721 .setData(circuitId);
722
723 DhcpRelayAgentOption newRelayAgentOpt = new DhcpRelayAgentOption();
724 newRelayAgentOpt.setCode(OptionCode_CircuitID.getValue());
725 newRelayAgentOpt.addSubOption(circuitIdSubOpt);
726
Charles Chanb5d24822017-10-10 16:53:32 -0400727 // Removes END option first
Yi Tseng51301292017-07-28 13:02:59 -0700728 List<DhcpOption> options = dhcpPacket.getOptions().stream()
729 .filter(opt -> opt.getCode() != OptionCode_END.getValue())
730 .collect(Collectors.toList());
731
732 // push relay agent option
733 options.add(newRelayAgentOpt);
734
735 // make sure option 255(End) is the last option
736 DhcpOption endOption = new DhcpOption();
737 endOption.setCode(OptionCode_END.getValue());
738 options.add(endOption);
739
740 dhcpPacket.setOptions(options);
Yi Tsengdcef2c22017-08-05 20:34:06 -0700741
Charles Chanb5d24822017-10-10 16:53:32 -0400742 // Sets relay agent IP
743 int effectiveRelayAgentIp = relayAgentIp != null ?
744 relayAgentIp.toInt() : clientInterfaceIp.toInt();
745 dhcpPacket.setGatewayIPAddress(effectiveRelayAgentIp);
746 } else {
747 if (indirectDhcpServerIp != null) {
748 // Use indirect server config for indirect packets if configured
749 etherReply.setDestinationMACAddress(indirectDhcpConnectMac);
750 etherReply.setVlanID(indirectDhcpConnectVlan.toShort());
751 ipv4Packet.setDestinationAddress(indirectDhcpServerIp.toInt());
Yi Tseng51301292017-07-28 13:02:59 -0700752
Charles Chanb5d24822017-10-10 16:53:32 -0400753 // Set giaddr if indirect relay agent IP is configured
754 if (indirectRelayAgentIp != null) {
755 dhcpPacket.setGatewayIPAddress(indirectRelayAgentIp.toInt());
756 }
757 } else {
758 // Otherwise, use default server config for indirect packets
759 etherReply.setDestinationMACAddress(dhcpConnectMac);
760 etherReply.setVlanID(dhcpConnectVlan.toShort());
761 ipv4Packet.setDestinationAddress(dhcpServerIp.toInt());
Yi Tseng4ec727d2017-08-31 11:21:00 -0700762
Charles Chanb5d24822017-10-10 16:53:32 -0400763 // Set giaddr if direct relay agent IP is configured
764 if (relayAgentIp != null) {
765 dhcpPacket.setGatewayIPAddress(relayAgentIp.toInt());
766 }
Yi Tseng4ec727d2017-08-31 11:21:00 -0700767 }
Yi Tseng4fa05832017-08-17 13:08:31 -0700768 }
769
Yi Tsengf41681e2017-10-03 09:58:19 -0700770 // Remove broadcast flag
771 dhcpPacket.setFlags((short) 0);
772
Yi Tseng51301292017-07-28 13:02:59 -0700773 udpPacket.setPayload(dhcpPacket);
Yi Tseng4ec727d2017-08-31 11:21:00 -0700774 // As a DHCP relay, the source port should be server port( instead
775 // of client port.
Yi Tsengdcef2c22017-08-05 20:34:06 -0700776 udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
Yi Tseng51301292017-07-28 13:02:59 -0700777 udpPacket.setDestinationPort(UDP.DHCP_SERVER_PORT);
778 ipv4Packet.setPayload(udpPacket);
Charles Chan7edf7642017-10-09 11:07:25 -0400779 ipv4Packet.setTtl((byte) 64);
Yi Tseng51301292017-07-28 13:02:59 -0700780 etherReply.setPayload(ipv4Packet);
781 return etherReply;
782 }
783
Charles Chan2f9aa2c2017-10-08 23:53:36 -0400784
785 /**
786 * Do a basic routing for a packet from client (used for LQ processing).
787 *
788 * @param context the packet context
789 * @param ethernetPacket the ethernet payload to process
790 * @return processed packet
791 */
792 private Ethernet processLeaseQueryFromAgent(PacketContext context,
793 Ethernet ethernetPacket) {
794 // get dhcp header.
795 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
796 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
797 UDP udpPacket = (UDP) ipv4Packet.getPayload();
798 DHCP dhcpPacket = (DHCP) udpPacket.getPayload();
799
800 VlanId dhcpConnectVlan = null;
801 MacAddress dhcpConnectMac = null;
802 Ip4Address dhcpServerIp = null;
803
804 VlanId indirectDhcpConnectVlan = null;
805 MacAddress indirectDhcpConnectMac = null;
806 Ip4Address indirectDhcpServerIp = null;
807
808 if (!defaultServerInfoList.isEmpty()) {
809 DhcpServerInfo serverInfo = defaultServerInfoList.get(0);
810 dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
811 dhcpConnectMac = serverInfo.getDhcpConnectMac().orElse(null);
812 dhcpServerIp = serverInfo.getDhcpServerIp4().orElse(null);
813 }
814
815 if (!indirectServerInfoList.isEmpty()) {
816 DhcpServerInfo indirectServerInfo = indirectServerInfoList.get(0);
817 indirectDhcpConnectVlan = indirectServerInfo.getDhcpConnectVlan().orElse(null);
818 indirectDhcpConnectMac = indirectServerInfo.getDhcpConnectMac().orElse(null);
819 indirectDhcpServerIp = indirectServerInfo.getDhcpServerIp4().orElse(null);
820 }
821
822 Ip4Address clientInterfaceIp =
823 interfaceService.getInterfacesByPort(context.inPacket().receivedFrom())
824 .stream()
825 .map(Interface::ipAddressesList)
826 .flatMap(Collection::stream)
827 .map(InterfaceIpAddress::ipAddress)
828 .filter(IpAddress::isIp4)
829 .map(IpAddress::getIp4Address)
830 .findFirst()
831 .orElse(null);
832 if (clientInterfaceIp == null) {
833 log.warn("Can't find interface IP for client interface for port {}",
834 context.inPacket().receivedFrom());
835 return null;
836 }
837 boolean isDirectlyConnected = directlyConnected(dhcpPacket);
838 Interface serverInterface = isDirectlyConnected ? getDefaultServerInterface() : getIndirectServerInterface();
839 if (serverInterface == null) {
840 log.warn("Can't get {} server interface, ignore", isDirectlyConnected ? "direct" : "indirect");
841 return null;
842 }
843 Ip4Address ipFacingServer = getFirstIpFromInterface(serverInterface);
844 MacAddress macFacingServer = serverInterface.mac();
845 if (ipFacingServer == null || macFacingServer == null) {
846 log.warn("No IP address for server Interface {}", serverInterface);
847 return null;
848 }
849 if (dhcpConnectMac == null) {
850 log.warn("DHCP server/gateway not yet resolved .. Aborting DHCP "
851 + "packet processing from client on port: {}",
852 context.inPacket().receivedFrom());
853 return null;
854 }
855
856 etherReply.setSourceMACAddress(macFacingServer);
857 etherReply.setDestinationMACAddress(dhcpConnectMac);
858 etherReply.setVlanID(dhcpConnectVlan.toShort());
859 ipv4Packet.setSourceAddress(ipFacingServer.toInt());
860 ipv4Packet.setDestinationAddress(dhcpServerIp.toInt());
861
862 if (indirectDhcpServerIp != null) {
863 // Indirect case, replace destination to indirect dhcp server if exist
864 etherReply.setDestinationMACAddress(indirectDhcpConnectMac);
865 etherReply.setVlanID(indirectDhcpConnectVlan.toShort());
866 ipv4Packet.setDestinationAddress(indirectDhcpServerIp.toInt());
867 }
868
869 udpPacket.setPayload(dhcpPacket);
870 // As a DHCP relay, the source port should be server port( instead
871 // of client port.
872 udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
873 udpPacket.setDestinationPort(UDP.DHCP_SERVER_PORT);
874 ipv4Packet.setPayload(udpPacket);
875 etherReply.setPayload(ipv4Packet);
876 return etherReply;
877 }
878
879
Yi Tseng51301292017-07-28 13:02:59 -0700880 /**
881 * Writes DHCP record to the store according to the request DHCP packet (Discover, Request).
882 *
883 * @param location the location which DHCP packet comes from
884 * @param ethernet the DHCP packet
885 * @param dhcpPayload the DHCP payload
886 */
887 private void writeRequestDhcpRecord(ConnectPoint location,
888 Ethernet ethernet,
889 DHCP dhcpPayload) {
890 VlanId vlanId = VlanId.vlanId(ethernet.getVlanID());
891 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
892 HostId hostId = HostId.hostId(macAddress, vlanId);
893 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
894 if (record == null) {
895 record = new DhcpRecord(HostId.hostId(macAddress, vlanId));
896 } else {
897 record = record.clone();
898 }
899 record.addLocation(new HostLocation(location, System.currentTimeMillis()));
900 record.ip4Status(dhcpPayload.getPacketType());
901 record.setDirectlyConnected(directlyConnected(dhcpPayload));
902 if (!directlyConnected(dhcpPayload)) {
903 // Update gateway mac address if the host is not directly connected
904 record.nextHop(ethernet.getSourceMAC());
905 }
906 record.updateLastSeen();
907 dhcpRelayStore.updateDhcpRecord(HostId.hostId(macAddress, vlanId), record);
908 }
909
910 /**
911 * Writes DHCP record to the store according to the response DHCP packet (Offer, Ack).
912 *
913 * @param ethernet the DHCP packet
914 * @param dhcpPayload the DHCP payload
915 */
916 private void writeResponseDhcpRecord(Ethernet ethernet,
917 DHCP dhcpPayload) {
Yi Tsengdcef2c22017-08-05 20:34:06 -0700918 Optional<Interface> outInterface = getClientInterface(ethernet, dhcpPayload);
Yi Tseng51301292017-07-28 13:02:59 -0700919 if (!outInterface.isPresent()) {
920 log.warn("Failed to determine where to send {}", dhcpPayload.getPacketType());
921 return;
922 }
923
924 Interface outIface = outInterface.get();
925 ConnectPoint location = outIface.connectPoint();
Yi Tseng4ec727d2017-08-31 11:21:00 -0700926 VlanId vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -0700927 if (vlanId == null) {
928 vlanId = outIface.vlan();
929 }
Yi Tseng51301292017-07-28 13:02:59 -0700930 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
931 HostId hostId = HostId.hostId(macAddress, vlanId);
932 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
933 if (record == null) {
934 record = new DhcpRecord(HostId.hostId(macAddress, vlanId));
935 } else {
936 record = record.clone();
937 }
938 record.addLocation(new HostLocation(location, System.currentTimeMillis()));
939 if (dhcpPayload.getPacketType() == DHCP.MsgType.DHCPACK) {
940 record.ip4Address(Ip4Address.valueOf(dhcpPayload.getYourIPAddress()));
941 }
942 record.ip4Status(dhcpPayload.getPacketType());
943 record.setDirectlyConnected(directlyConnected(dhcpPayload));
944 record.updateLastSeen();
945 dhcpRelayStore.updateDhcpRecord(HostId.hostId(macAddress, vlanId), record);
946 }
947
948 /**
949 * Build the DHCP offer/ack with proper client port.
950 *
951 * @param ethernetPacket the original packet comes from server
952 * @return new packet which will send to the client
953 */
954 private Ethernet processDhcpPacketFromServer(Ethernet ethernetPacket) {
955 // get dhcp header.
956 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
957 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
958 UDP udpPacket = (UDP) ipv4Packet.getPayload();
959 DHCP dhcpPayload = (DHCP) udpPacket.getPayload();
960
961 // determine the vlanId of the client host - note that this vlan id
962 // could be different from the vlan in the packet from the server
Yi Tsengdcef2c22017-08-05 20:34:06 -0700963 Interface clientInterface = getClientInterface(ethernetPacket, dhcpPayload).orElse(null);
Yi Tseng51301292017-07-28 13:02:59 -0700964
Yi Tsengdcef2c22017-08-05 20:34:06 -0700965 if (clientInterface == null) {
Yi Tseng51301292017-07-28 13:02:59 -0700966 log.warn("Cannot find the interface for the DHCP {}", dhcpPayload);
967 return null;
968 }
Yi Tsengdcef2c22017-08-05 20:34:06 -0700969 VlanId vlanId;
970 if (clientInterface.vlanTagged().isEmpty()) {
971 vlanId = clientInterface.vlan();
972 } else {
973 // might be multiple vlan in same interface
Yi Tseng4ec727d2017-08-31 11:21:00 -0700974 vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -0700975 }
976 if (vlanId == null) {
977 vlanId = VlanId.NONE;
978 }
979 etherReply.setVlanID(vlanId.toShort());
980 etherReply.setSourceMACAddress(clientInterface.mac());
Yi Tseng51301292017-07-28 13:02:59 -0700981
Yi Tsengdcef2c22017-08-05 20:34:06 -0700982 if (!directlyConnected(dhcpPayload)) {
983 // if client is indirectly connected, try use next hop mac address
984 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
985 HostId hostId = HostId.hostId(macAddress, vlanId);
986 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
987 if (record != null) {
988 // if next hop can be found, use mac address of next hop
989 record.nextHop().ifPresent(etherReply::setDestinationMACAddress);
990 } else {
991 // otherwise, discard the packet
992 log.warn("Can't find record for host id {}, discard packet", hostId);
993 return null;
994 }
Yi Tsengc03fa242017-08-17 17:43:38 -0700995 } else {
996 etherReply.setDestinationMACAddress(dhcpPayload.getClientHardwareAddress());
Yi Tsengdcef2c22017-08-05 20:34:06 -0700997 }
998
Yi Tseng51301292017-07-28 13:02:59 -0700999 // we leave the srcMac from the original packet
Yi Tseng51301292017-07-28 13:02:59 -07001000 // figure out the relay agent IP corresponding to the original request
Yi Tseng4fa05832017-08-17 13:08:31 -07001001 Ip4Address ipFacingClient = getFirstIpFromInterface(clientInterface);
1002 if (ipFacingClient == null) {
Yi Tseng51301292017-07-28 13:02:59 -07001003 log.warn("Cannot determine relay agent interface Ipv4 addr for host {}/{}. "
1004 + "Aborting relay for dhcp packet from server {}",
Yi Tsengdcef2c22017-08-05 20:34:06 -07001005 etherReply.getDestinationMAC(), clientInterface.vlan(),
Yi Tseng51301292017-07-28 13:02:59 -07001006 ethernetPacket);
1007 return null;
1008 }
1009 // SRC_IP: relay agent IP
1010 // DST_IP: offered IP
Yi Tseng4fa05832017-08-17 13:08:31 -07001011 ipv4Packet.setSourceAddress(ipFacingClient.toInt());
Yi Tseng51301292017-07-28 13:02:59 -07001012 ipv4Packet.setDestinationAddress(dhcpPayload.getYourIPAddress());
1013 udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
1014 if (directlyConnected(dhcpPayload)) {
1015 udpPacket.setDestinationPort(UDP.DHCP_CLIENT_PORT);
1016 } else {
1017 // forward to another dhcp relay
Yi Tseng72b599a2017-09-14 13:24:21 -07001018 // FIXME: Currently we assume the DHCP comes from a L2 relay with
1019 // Option 82, this might not work if DHCP message comes from
1020 // L3 relay.
1021 udpPacket.setDestinationPort(UDP.DHCP_CLIENT_PORT);
Yi Tseng51301292017-07-28 13:02:59 -07001022 }
1023
1024 udpPacket.setPayload(dhcpPayload);
1025 ipv4Packet.setPayload(udpPacket);
1026 etherReply.setPayload(ipv4Packet);
1027 return etherReply;
1028 }
1029
Yi Tsengdcef2c22017-08-05 20:34:06 -07001030 /**
Charles Chan2f9aa2c2017-10-08 23:53:36 -04001031 * Build the DHCP offer/ack with proper client port.
1032 *
1033 * @param ethernetPacket the original packet comes from server
1034 * @return new packet which will send to the client
1035 */
1036 private Ethernet processLeaseQueryFromServer(Ethernet ethernetPacket) {
1037 // get dhcp header.
1038 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
1039 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
1040 UDP udpPacket = (UDP) ipv4Packet.getPayload();
1041 DHCP dhcpPayload = (DHCP) udpPacket.getPayload();
1042
1043 // determine the vlanId of the client host - note that this vlan id
1044 // could be different from the vlan in the packet from the server
1045 Interface clientInterface = getClientInterface(ethernetPacket, dhcpPayload).orElse(null);
1046
1047 if (clientInterface == null) {
1048 log.warn("Cannot find the interface for the DHCP {}", dhcpPayload);
1049 return null;
1050 }
1051 VlanId vlanId;
1052 if (clientInterface.vlanTagged().isEmpty()) {
1053 vlanId = clientInterface.vlan();
1054 } else {
1055 // might be multiple vlan in same interface
1056 vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
1057 }
1058 if (vlanId == null) {
1059 vlanId = VlanId.NONE;
1060 }
1061 etherReply.setVlanID(vlanId.toShort());
1062 etherReply.setSourceMACAddress(clientInterface.mac());
1063
1064 if (!directlyConnected(dhcpPayload)) {
1065 // if client is indirectly connected, try use next hop mac address
1066 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
1067 HostId hostId = HostId.hostId(macAddress, vlanId);
1068 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1069 if (record != null) {
1070 // if next hop can be found, use mac address of next hop
1071 record.nextHop().ifPresent(etherReply::setDestinationMACAddress);
1072 } else {
1073 // otherwise, discard the packet
1074 log.warn("Can't find record for host id {}, discard packet", hostId);
1075 return null;
1076 }
1077 } else {
1078 etherReply.setDestinationMACAddress(dhcpPayload.getClientHardwareAddress());
1079 }
1080
1081 // default is client port
1082 udpPacket.setSourcePort(UDP.DHCP_SERVER_PORT);
1083 udpPacket.setDestinationPort(UDP.DHCP_CLIENT_PORT);
1084
1085 udpPacket.setPayload(dhcpPayload);
1086 ipv4Packet.setPayload(udpPacket);
1087 etherReply.setPayload(ipv4Packet);
1088 return etherReply;
1089 }
1090 /**
Yi Tsengdcef2c22017-08-05 20:34:06 -07001091 * Extracts VLAN ID from relay agent option.
1092 *
1093 * @param dhcpPayload the DHCP payload
1094 * @return VLAN ID from DHCP payload; null if not exists
1095 */
Yi Tseng4ec727d2017-08-31 11:21:00 -07001096 private VlanId getVlanIdFromRelayAgentOption(DHCP dhcpPayload) {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001097 DhcpRelayAgentOption option = (DhcpRelayAgentOption) dhcpPayload.getOption(OptionCode_CircuitID);
1098 if (option == null) {
1099 return null;
1100 }
1101 DhcpOption circuitIdSubOption = option.getSubOption(CIRCUIT_ID.getValue());
1102 if (circuitIdSubOption == null) {
1103 return null;
1104 }
1105 try {
1106 CircuitId circuitId = CircuitId.deserialize(circuitIdSubOption.getData());
1107 return circuitId.vlanId();
1108 } catch (IllegalArgumentException e) {
1109 // can't deserialize the circuit ID
1110 return null;
1111 }
1112 }
1113
1114 /**
1115 * Removes DHCP relay agent information option (option 82) from DHCP payload.
1116 * Also reset giaddr to 0
1117 *
1118 * @param ethPacket the Ethernet packet to be processed
1119 * @return Ethernet packet processed
1120 */
1121 private Ethernet removeRelayAgentOption(Ethernet ethPacket) {
1122 Ethernet ethernet = (Ethernet) ethPacket.clone();
1123 IPv4 ipv4 = (IPv4) ethernet.getPayload();
1124 UDP udp = (UDP) ipv4.getPayload();
1125 DHCP dhcpPayload = (DHCP) udp.getPayload();
1126
1127 // removes relay agent information option
1128 List<DhcpOption> options = dhcpPayload.getOptions();
1129 options = options.stream()
1130 .filter(option -> option.getCode() != OptionCode_CircuitID.getValue())
1131 .collect(Collectors.toList());
1132 dhcpPayload.setOptions(options);
1133 dhcpPayload.setGatewayIPAddress(0);
1134
1135 udp.setPayload(dhcpPayload);
1136 ipv4.setPayload(udp);
1137 ethernet.setPayload(ipv4);
1138 return ethernet;
1139 }
1140
Yi Tseng51301292017-07-28 13:02:59 -07001141
1142 /**
1143 * Check if the host is directly connected to the network or not.
1144 *
1145 * @param dhcpPayload the dhcp payload
1146 * @return true if the host is directly connected to the network; false otherwise
1147 */
1148 private boolean directlyConnected(DHCP dhcpPayload) {
Yi Tseng2cf59912017-08-24 14:47:34 -07001149 DhcpRelayAgentOption relayAgentOption =
1150 (DhcpRelayAgentOption) dhcpPayload.getOption(OptionCode_CircuitID);
Yi Tseng51301292017-07-28 13:02:59 -07001151
1152 // Doesn't contains relay option
1153 if (relayAgentOption == null) {
1154 return true;
1155 }
1156
Yi Tseng2cf59912017-08-24 14:47:34 -07001157 // check circuit id, if circuit id is invalid, we say it is an indirect host
1158 DhcpOption circuitIdOpt = relayAgentOption.getSubOption(CIRCUIT_ID.getValue());
Yi Tseng51301292017-07-28 13:02:59 -07001159
Yi Tseng2cf59912017-08-24 14:47:34 -07001160 try {
1161 CircuitId.deserialize(circuitIdOpt.getData());
Yi Tseng51301292017-07-28 13:02:59 -07001162 return true;
Yi Tseng2cf59912017-08-24 14:47:34 -07001163 } catch (Exception e) {
1164 // invalid circuit id
1165 return false;
Yi Tseng51301292017-07-28 13:02:59 -07001166 }
Yi Tseng51301292017-07-28 13:02:59 -07001167 }
1168
1169
1170 /**
1171 * Send the DHCP ack to the requester host.
1172 * Modify Host or Route store according to the type of DHCP.
1173 *
1174 * @param ethernetPacketAck the packet
1175 * @param dhcpPayload the DHCP data
1176 */
1177 private void handleDhcpAck(Ethernet ethernetPacketAck, DHCP dhcpPayload) {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001178 Optional<Interface> outInterface = getClientInterface(ethernetPacketAck, dhcpPayload);
Yi Tseng51301292017-07-28 13:02:59 -07001179 if (!outInterface.isPresent()) {
1180 log.warn("Can't find output interface for dhcp: {}", dhcpPayload);
1181 return;
1182 }
1183
1184 Interface outIface = outInterface.get();
1185 HostLocation hostLocation = new HostLocation(outIface.connectPoint(), System.currentTimeMillis());
1186 MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
Yi Tseng4ec727d2017-08-31 11:21:00 -07001187 VlanId vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
Yi Tsengdcef2c22017-08-05 20:34:06 -07001188 if (vlanId == null) {
1189 vlanId = outIface.vlan();
1190 }
Yi Tseng51301292017-07-28 13:02:59 -07001191 HostId hostId = HostId.hostId(macAddress, vlanId);
1192 Ip4Address ip = Ip4Address.valueOf(dhcpPayload.getYourIPAddress());
1193
1194 if (directlyConnected(dhcpPayload)) {
1195 // Add to host store if it connect to network directly
1196 Set<IpAddress> ips = Sets.newHashSet(ip);
Yi Tseng4b013202017-09-08 17:22:51 -07001197 Host host = hostService.getHost(hostId);
Yi Tseng51301292017-07-28 13:02:59 -07001198
Yi Tseng4b013202017-09-08 17:22:51 -07001199 Set<HostLocation> hostLocations = Sets.newHashSet(hostLocation);
1200 if (host != null) {
1201 // Dual homing support:
1202 // if host exists, use old locations and new location
1203 hostLocations.addAll(host.locations());
1204 }
1205 HostDescription desc = new DefaultHostDescription(macAddress, vlanId,
1206 hostLocations, ips, false);
1207 // Add IP address when dhcp server give the host new ip address
1208 providerService.hostDetected(hostId, desc, false);
Yi Tseng51301292017-07-28 13:02:59 -07001209 } else {
1210 // Add to route store if it does not connect to network directly
1211 // Get gateway host IP according to host mac address
Yi Tsengdcef2c22017-08-05 20:34:06 -07001212 // TODO: remove relay store here
Yi Tseng51301292017-07-28 13:02:59 -07001213 DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
1214
1215 if (record == null) {
1216 log.warn("Can't find DHCP record of host {}", hostId);
1217 return;
1218 }
1219
1220 MacAddress gwMac = record.nextHop().orElse(null);
1221 if (gwMac == null) {
1222 log.warn("Can't find gateway mac address from record {}", record);
1223 return;
1224 }
1225
1226 HostId gwHostId = HostId.hostId(gwMac, record.vlanId());
1227 Host gwHost = hostService.getHost(gwHostId);
1228
1229 if (gwHost == null) {
1230 log.warn("Can't find gateway host {}", gwHostId);
1231 return;
1232 }
1233
1234 Ip4Address nextHopIp = gwHost.ipAddresses()
1235 .stream()
1236 .filter(IpAddress::isIp4)
1237 .map(IpAddress::getIp4Address)
1238 .findFirst()
1239 .orElse(null);
1240
1241 if (nextHopIp == null) {
1242 log.warn("Can't find IP address of gateway {}", gwHost);
1243 return;
1244 }
1245
1246 Route route = new Route(Route.Source.STATIC, ip.toIpPrefix(), nextHopIp);
1247 routeStore.updateRoute(route);
1248 }
Yi Tseng51301292017-07-28 13:02:59 -07001249 }
1250
1251 /**
1252 * forward the packet to ConnectPoint where the DHCP server is attached.
1253 *
1254 * @param packet the packet
1255 */
Yi Tseng4ec727d2017-08-31 11:21:00 -07001256 private void handleDhcpDiscoverAndRequest(Ethernet packet, DHCP dhcpPayload) {
Yi Tseng2fe8f3f2017-09-07 16:22:51 -07001257 boolean direct = directlyConnected(dhcpPayload);
1258 DhcpServerInfo serverInfo = defaultServerInfoList.get(0);
1259 if (!direct && !indirectServerInfoList.isEmpty()) {
1260 serverInfo = indirectServerInfoList.get(0);
Yi Tseng4ec727d2017-08-31 11:21:00 -07001261 }
Yi Tseng2fe8f3f2017-09-07 16:22:51 -07001262 ConnectPoint portToFotward = serverInfo.getDhcpServerConnectPoint().orElse(null);
Yi Tseng51301292017-07-28 13:02:59 -07001263 // send packet to dhcp server connect point.
Yi Tseng4ec727d2017-08-31 11:21:00 -07001264 if (portToFotward != null) {
Yi Tseng51301292017-07-28 13:02:59 -07001265 TrafficTreatment t = DefaultTrafficTreatment.builder()
Yi Tseng4ec727d2017-08-31 11:21:00 -07001266 .setOutput(portToFotward.port()).build();
Yi Tseng51301292017-07-28 13:02:59 -07001267 OutboundPacket o = new DefaultOutboundPacket(
Yi Tseng4ec727d2017-08-31 11:21:00 -07001268 portToFotward.deviceId(), t, ByteBuffer.wrap(packet.serialize()));
Yi Tseng51301292017-07-28 13:02:59 -07001269 if (log.isTraceEnabled()) {
1270 log.trace("Relaying packet to dhcp server {}", packet);
1271 }
1272 packetService.emit(o);
1273 } else {
1274 log.warn("Can't find DHCP server connect point, abort.");
1275 }
1276 }
1277
1278
1279 /**
1280 * Gets output interface of a dhcp packet.
1281 * If option 82 exists in the dhcp packet and the option was sent by
Yi Tseng4ec727d2017-08-31 11:21:00 -07001282 * ONOS (circuit format is correct), use the connect
Yi Tseng51301292017-07-28 13:02:59 -07001283 * point and vlan id from circuit id; otherwise, find host by destination
1284 * address and use vlan id from sender (dhcp server).
1285 *
1286 * @param ethPacket the ethernet packet
1287 * @param dhcpPayload the dhcp packet
1288 * @return an interface represent the output port and vlan; empty value
1289 * if the host or circuit id not found
1290 */
Yi Tsengdcef2c22017-08-05 20:34:06 -07001291 private Optional<Interface> getClientInterface(Ethernet ethPacket, DHCP dhcpPayload) {
Yi Tseng51301292017-07-28 13:02:59 -07001292 VlanId originalPacketVlanId = VlanId.vlanId(ethPacket.getVlanID());
Yi Tseng51301292017-07-28 13:02:59 -07001293 DhcpRelayAgentOption option = (DhcpRelayAgentOption) dhcpPayload.getOption(OptionCode_CircuitID);
1294
Yi Tseng4ec727d2017-08-31 11:21:00 -07001295 DhcpOption circuitIdSubOption = option.getSubOption(CIRCUIT_ID.getValue());
1296 try {
1297 CircuitId circuitId = CircuitId.deserialize(circuitIdSubOption.getData());
1298 ConnectPoint connectPoint = ConnectPoint.deviceConnectPoint(circuitId.connectPoint());
1299 VlanId vlanId = circuitId.vlanId();
1300 return interfaceService.getInterfacesByPort(connectPoint)
1301 .stream()
1302 .filter(iface -> interfaceContainsVlan(iface, vlanId))
1303 .findFirst();
1304 } catch (IllegalArgumentException ex) {
1305 // invalid circuit format, didn't sent by ONOS
1306 log.debug("Invalid circuit {}, use information from dhcp payload",
1307 circuitIdSubOption.getData());
Yi Tseng51301292017-07-28 13:02:59 -07001308 }
1309
1310 // Use Vlan Id from DHCP server if DHCP relay circuit id was not
1311 // sent by ONOS or circuit Id can't be parsed
Yi Tsengdcef2c22017-08-05 20:34:06 -07001312 // TODO: remove relay store from this method
Yi Tseng51301292017-07-28 13:02:59 -07001313 MacAddress dstMac = valueOf(dhcpPayload.getClientHardwareAddress());
1314 Optional<DhcpRecord> dhcpRecord = dhcpRelayStore.getDhcpRecord(HostId.hostId(dstMac, originalPacketVlanId));
Yi Tsengdcef2c22017-08-05 20:34:06 -07001315 ConnectPoint clientConnectPoint = dhcpRecord
Yi Tseng51301292017-07-28 13:02:59 -07001316 .map(DhcpRecord::locations)
1317 .orElse(Collections.emptySet())
1318 .stream()
1319 .reduce((hl1, hl2) -> {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001320 // find latest host connect point
Yi Tseng51301292017-07-28 13:02:59 -07001321 if (hl1 == null || hl2 == null) {
1322 return hl1 == null ? hl2 : hl1;
1323 }
1324 return hl1.time() > hl2.time() ? hl1 : hl2;
1325 })
Yi Tsengdcef2c22017-08-05 20:34:06 -07001326 .orElse(null);
Yi Tseng51301292017-07-28 13:02:59 -07001327
Yi Tsengdcef2c22017-08-05 20:34:06 -07001328 if (clientConnectPoint != null) {
1329 return interfaceService.getInterfacesByPort(clientConnectPoint)
1330 .stream()
Yi Tseng4ec727d2017-08-31 11:21:00 -07001331 .filter(iface -> interfaceContainsVlan(iface, originalPacketVlanId))
Yi Tsengdcef2c22017-08-05 20:34:06 -07001332 .findFirst();
1333 }
1334 return Optional.empty();
Yi Tseng51301292017-07-28 13:02:59 -07001335 }
1336
1337 /**
1338 * Send the response DHCP to the requester host.
1339 *
1340 * @param ethPacket the packet
1341 * @param dhcpPayload the DHCP data
1342 */
1343 private void sendResponseToClient(Ethernet ethPacket, DHCP dhcpPayload) {
Yi Tsengdcef2c22017-08-05 20:34:06 -07001344 Optional<Interface> outInterface = getClientInterface(ethPacket, dhcpPayload);
1345 if (directlyConnected(dhcpPayload)) {
1346 ethPacket = removeRelayAgentOption(ethPacket);
1347 }
1348 if (!outInterface.isPresent()) {
1349 log.warn("Can't find output interface for client, ignore");
1350 return;
1351 }
1352 Interface outIface = outInterface.get();
1353 TrafficTreatment treatment = DefaultTrafficTreatment.builder()
1354 .setOutput(outIface.connectPoint().port())
1355 .build();
1356 OutboundPacket o = new DefaultOutboundPacket(
1357 outIface.connectPoint().deviceId(),
1358 treatment,
1359 ByteBuffer.wrap(ethPacket.serialize()));
1360 if (log.isTraceEnabled()) {
1361 log.trace("Relaying packet to DHCP client {} via {}, vlan {}",
1362 ethPacket,
1363 outIface.connectPoint(),
1364 outIface.vlan());
1365 }
1366 packetService.emit(o);
Yi Tseng51301292017-07-28 13:02:59 -07001367 }
Yi Tsenge72fbb52017-08-02 15:03:31 -07001368
Yi Tseng4b013202017-09-08 17:22:51 -07001369 @Override
1370 public void triggerProbe(Host host) {
1371 // Do nothing here
1372 }
1373
1374 @Override
1375 public ProviderId id() {
Charles Chan75edab72017-09-12 17:09:32 -07001376 return PROVIDER_ID;
Yi Tseng4b013202017-09-08 17:22:51 -07001377 }
1378
Yi Tsenge72fbb52017-08-02 15:03:31 -07001379 class InternalHostListener implements HostListener {
1380 @Override
1381 public void event(HostEvent event) {
Yi Tseng2fe8f3f2017-09-07 16:22:51 -07001382 if (!configured()) {
1383 return;
1384 }
Yi Tsenge72fbb52017-08-02 15:03:31 -07001385 switch (event.type()) {
1386 case HOST_ADDED:
1387 case HOST_UPDATED:
1388 hostUpdated(event.subject());
1389 break;
1390 case HOST_REMOVED:
1391 hostRemoved(event.subject());
1392 break;
Yi Tsenge72fbb52017-08-02 15:03:31 -07001393 default:
1394 break;
1395 }
1396 }
1397 }
1398
1399 /**
Yi Tsenge72fbb52017-08-02 15:03:31 -07001400 * Handle host updated.
1401 * If the host is DHCP server or gateway, update connect mac and vlan.
1402 *
1403 * @param host the host
1404 */
1405 private void hostUpdated(Host host) {
Yi Tseng7da339e2017-10-23 19:39:39 -07001406 hostUpdated(host, defaultServerInfoList);
1407 hostUpdated(host, indirectServerInfoList);
Yi Tsenge72fbb52017-08-02 15:03:31 -07001408 }
1409
Yi Tseng7da339e2017-10-23 19:39:39 -07001410 private void hostUpdated(Host host, List<DhcpServerInfo> srverInfoList) {
1411 DhcpServerInfo serverInfo;
1412 Ip4Address targetIp;
1413 if (!srverInfoList.isEmpty()) {
1414 serverInfo = srverInfoList.get(0);
1415 targetIp = serverInfo.getDhcpGatewayIp4().orElse(null);
1416 Ip4Address serverIp = serverInfo.getDhcpServerIp4().orElse(null);
1417
1418 if (targetIp == null) {
1419 targetIp = serverIp;
1420 }
1421
1422 if (targetIp != null) {
1423 if (host.ipAddresses().contains(targetIp)) {
1424 serverInfo.setDhcpConnectMac(host.mac());
1425 serverInfo.setDhcpConnectVlan(host.vlan());
1426 requestDhcpPacket(serverIp);
1427 }
1428 }
1429 }
1430 }
1431
1432
Yi Tsenge72fbb52017-08-02 15:03:31 -07001433 /**
1434 * Handle host removed.
1435 * If the host is DHCP server or gateway, unset connect mac and vlan.
1436 *
1437 * @param host the host
1438 */
1439 private void hostRemoved(Host host) {
Yi Tseng7da339e2017-10-23 19:39:39 -07001440 hostRemoved(host, defaultServerInfoList);
1441 hostRemoved(host, indirectServerInfoList);
1442 }
1443
1444 private void hostRemoved(Host host, List<DhcpServerInfo> serverInfoList) {
Yi Tseng2fe8f3f2017-09-07 16:22:51 -07001445 DhcpServerInfo serverInfo;
Yi Tseng7da339e2017-10-23 19:39:39 -07001446 Ip4Address targetIp;
1447 if (!serverInfoList.isEmpty()) {
1448 serverInfo = serverInfoList.get(0);
1449 Ip4Address serverIp = serverInfo.getDhcpServerIp4().orElse(null);
1450 targetIp = serverInfo.getDhcpGatewayIp4().orElse(null);
Yi Tseng2fe8f3f2017-09-07 16:22:51 -07001451
Yi Tseng7da339e2017-10-23 19:39:39 -07001452 if (targetIp == null) {
1453 targetIp = serverIp;
Yi Tseng2fe8f3f2017-09-07 16:22:51 -07001454 }
Yi Tseng7da339e2017-10-23 19:39:39 -07001455
1456 if (targetIp != null) {
1457 if (host.ipAddresses().contains(targetIp)) {
Yi Tseng2fe8f3f2017-09-07 16:22:51 -07001458 serverInfo.setDhcpConnectVlan(null);
1459 serverInfo.setDhcpConnectMac(null);
Yi Tseng7da339e2017-10-23 19:39:39 -07001460 cancelDhcpPacket(serverIp);
Yi Tseng2fe8f3f2017-09-07 16:22:51 -07001461 }
Yi Tsenge72fbb52017-08-02 15:03:31 -07001462 }
Yi Tsenge72fbb52017-08-02 15:03:31 -07001463 }
Yi Tseng7da339e2017-10-23 19:39:39 -07001464 }
Yi Tseng2fe8f3f2017-09-07 16:22:51 -07001465
Yi Tseng7da339e2017-10-23 19:39:39 -07001466 private void requestDhcpPacket(Ip4Address serverIp) {
1467 requestServerDhcpPacket(serverIp);
1468 requestClientDhcpPacket(serverIp);
1469 }
Yi Tseng2fe8f3f2017-09-07 16:22:51 -07001470
Yi Tseng7da339e2017-10-23 19:39:39 -07001471 private void cancelDhcpPacket(Ip4Address serverIp) {
1472 cancelServerDhcpPacket(serverIp);
1473 cancelClientDhcpPacket(serverIp);
1474 }
1475
1476 private void cancelServerDhcpPacket(Ip4Address serverIp) {
1477 TrafficSelector serverSelector =
1478 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1479 .matchIPSrc(serverIp.toIpPrefix())
1480 .build();
1481 packetService.cancelPackets(serverSelector,
1482 PacketPriority.CONTROL,
1483 appId);
1484 }
1485
1486 private void requestServerDhcpPacket(Ip4Address serverIp) {
1487 TrafficSelector serverSelector =
1488 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1489 .matchIPSrc(serverIp.toIpPrefix())
1490 .build();
1491 packetService.requestPackets(serverSelector,
1492 PacketPriority.CONTROL,
1493 appId);
1494 }
1495
1496 private void cancelClientDhcpPacket(Ip4Address serverIp) {
1497 // Packet comes from relay
1498 TrafficSelector indirectClientSelector =
1499 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1500 .matchIPDst(serverIp.toIpPrefix())
1501 .build();
1502 packetService.cancelPackets(indirectClientSelector,
1503 PacketPriority.CONTROL,
1504 appId);
1505
1506 // Packet comes from client
1507 packetService.cancelPackets(CLIENT_SERVER_SELECTOR,
1508 PacketPriority.CONTROL,
1509 appId);
1510 }
1511
1512 private void requestClientDhcpPacket(Ip4Address serverIp) {
1513 // Packet comes from relay
1514 TrafficSelector indirectClientSelector =
1515 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1516 .matchIPDst(serverIp.toIpPrefix())
1517 .build();
1518 packetService.requestPackets(indirectClientSelector,
1519 PacketPriority.CONTROL,
1520 appId);
1521
1522 // Packet comes from client
1523 packetService.requestPackets(CLIENT_SERVER_SELECTOR,
1524 PacketPriority.CONTROL,
1525 appId);
1526 }
1527
1528 /**
1529 * Process the ignore rules.
1530 *
1531 * @param deviceId the device id
1532 * @param vlanId the vlan to be ignored
1533 * @param op the operation, ADD to install; REMOVE to uninstall rules
1534 */
1535 private void processIgnoreVlanRule(DeviceId deviceId, VlanId vlanId, Objective.Operation op) {
Yi Tseng7da339e2017-10-23 19:39:39 -07001536 AtomicInteger installedCount = new AtomicInteger(DHCP_SELECTORS.size());
1537 DHCP_SELECTORS.forEach(trafficSelector -> {
1538 TrafficSelector selector = DefaultTrafficSelector.builder(trafficSelector)
1539 .matchVlanId(vlanId)
1540 .build();
1541
1542 ForwardingObjective.Builder builder = DefaultForwardingObjective.builder()
1543 .withFlag(ForwardingObjective.Flag.VERSATILE)
1544 .withSelector(selector)
1545 .withPriority(IGNORE_CONTROL_PRIORITY)
Yi Tsengf29ffd72017-11-29 10:49:20 -08001546 .withTreatment(DefaultTrafficTreatment.emptyTreatment())
Yi Tseng7da339e2017-10-23 19:39:39 -07001547 .fromApp(appId);
1548
1549
1550 ObjectiveContext objectiveContext = new ObjectiveContext() {
1551 @Override
1552 public void onSuccess(Objective objective) {
1553 log.info("Ignore rule {} (Vlan id {}, device {}, selector {})",
1554 op, vlanId, deviceId, selector);
1555 int countDown = installedCount.decrementAndGet();
1556 if (countDown != 0) {
1557 return;
1558 }
1559 switch (op) {
1560 case ADD:
1561 ignoredVlans.put(deviceId, vlanId);
1562 break;
1563 case REMOVE:
1564 ignoredVlans.remove(deviceId, vlanId);
1565 break;
1566 default:
1567 log.warn("Unsupported objective operation {}", op);
1568 break;
1569 }
Yi Tseng2fe8f3f2017-09-07 16:22:51 -07001570 }
Yi Tseng7da339e2017-10-23 19:39:39 -07001571
1572 @Override
1573 public void onError(Objective objective, ObjectiveError error) {
1574 log.warn("Can't {} ignore rule (vlan id {}, selector {}, device {}) due to {}",
1575 op, vlanId, selector, deviceId, error);
Yi Tseng2fe8f3f2017-09-07 16:22:51 -07001576 }
Yi Tseng7da339e2017-10-23 19:39:39 -07001577 };
1578
1579 ForwardingObjective fwd;
1580 switch (op) {
1581 case ADD:
1582 fwd = builder.add(objectiveContext);
1583 break;
1584 case REMOVE:
1585 fwd = builder.remove(objectiveContext);
1586 break;
1587 default:
1588 log.warn("Unsupported objective operation {}", op);
1589 return;
Yi Tseng4ec727d2017-08-31 11:21:00 -07001590 }
Yi Tseng7da339e2017-10-23 19:39:39 -07001591
1592 Device device = deviceService.getDevice(deviceId);
1593 if (device == null || !device.is(Pipeliner.class)) {
1594 log.warn("Device {} is not available now, wait until device is available", deviceId);
1595 return;
1596 }
1597 flowObjectiveService.apply(deviceId, fwd);
1598 });
Yi Tsenge72fbb52017-08-02 15:03:31 -07001599 }
Yi Tseng51301292017-07-28 13:02:59 -07001600}