blob: 06a7f4fa13a2c4c53b34b7e0c8209aa8b5d28cc2 [file] [log] [blame]
Amit Ghosh47243cb2017-07-26 05:08:53 +01001/*
Deepa vaddireddy0060f532017-08-04 06:46:05 +00002 * Copyright 2017-present Open Networking Foundation
Amit Ghosh47243cb2017-07-26 05:08:53 +01003 *
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 */
16package org.opencord.dhcpl2relay;
17
18import com.google.common.collect.ImmutableSet;
Amit Ghosha17354e2017-08-23 12:56:04 +010019import com.google.common.collect.Maps;
Deepa vaddireddy0060f532017-08-04 06:46:05 +000020import com.google.common.collect.Lists;
Amit Ghosh8951f042017-08-10 13:48:10 +010021import com.google.common.collect.Sets;
Deepa vaddireddy0060f532017-08-04 06:46:05 +000022
Amit Ghosh47243cb2017-07-26 05:08:53 +010023import org.apache.felix.scr.annotations.Activate;
24import org.apache.felix.scr.annotations.Component;
25import org.apache.felix.scr.annotations.Deactivate;
26import org.apache.felix.scr.annotations.Modified;
27import org.apache.felix.scr.annotations.Property;
28import org.apache.felix.scr.annotations.Reference;
29import org.apache.felix.scr.annotations.ReferenceCardinality;
Deepa vaddireddy0060f532017-08-04 06:46:05 +000030import org.onlab.packet.DeserializationException;
Amit Ghosh47243cb2017-07-26 05:08:53 +010031import org.onlab.packet.DHCP;
32import org.onlab.packet.DHCPOption;
33import org.onlab.packet.DHCPPacketType;
Deepa vaddireddy0060f532017-08-04 06:46:05 +000034import org.onlab.packet.Ethernet;
Amit Ghosha17354e2017-08-23 12:56:04 +010035import org.onlab.packet.IpAddress;
Amit Ghosh47243cb2017-07-26 05:08:53 +010036import org.onlab.packet.IPv4;
Deepa vaddireddy0060f532017-08-04 06:46:05 +000037import org.onlab.packet.MacAddress;
Amit Ghosh47243cb2017-07-26 05:08:53 +010038import org.onlab.packet.TpPort;
39import org.onlab.packet.UDP;
40import org.onlab.packet.VlanId;
Amit Ghosh8951f042017-08-10 13:48:10 +010041import org.onosproject.mastership.MastershipEvent;
42import org.onosproject.mastership.MastershipListener;
43import org.onosproject.mastership.MastershipService;
44import org.onosproject.net.device.DeviceEvent;
45import org.onosproject.net.device.DeviceListener;
Deepa vaddireddy0060f532017-08-04 06:46:05 +000046import org.opencord.dhcpl2relay.packet.DhcpEthernet;
47import org.opencord.dhcpl2relay.packet.DhcpOption82;
Amit Ghosh47243cb2017-07-26 05:08:53 +010048import org.onlab.util.Tools;
49import org.onosproject.cfg.ComponentConfigService;
50import org.onosproject.core.ApplicationId;
51import org.onosproject.core.CoreService;
52import org.onosproject.net.AnnotationKeys;
53import org.onosproject.net.ConnectPoint;
54import org.onosproject.net.Host;
55import org.onosproject.net.Port;
56import org.onosproject.net.config.ConfigFactory;
57import org.onosproject.net.config.NetworkConfigEvent;
58import org.onosproject.net.config.NetworkConfigListener;
59import org.onosproject.net.config.NetworkConfigRegistry;
60import org.onosproject.net.device.DeviceService;
61import org.onosproject.net.flow.DefaultTrafficSelector;
62import org.onosproject.net.flow.DefaultTrafficTreatment;
63import org.onosproject.net.flow.TrafficSelector;
64import org.onosproject.net.flow.TrafficTreatment;
65import org.onosproject.net.host.HostService;
66import org.onosproject.net.packet.DefaultOutboundPacket;
67import org.onosproject.net.packet.OutboundPacket;
68import org.onosproject.net.packet.PacketContext;
69import org.onosproject.net.packet.PacketPriority;
70import org.onosproject.net.packet.PacketProcessor;
71import org.onosproject.net.packet.PacketService;
72
73import org.opencord.sadis.SubscriberAndDeviceInformation;
74import org.opencord.sadis.SubscriberAndDeviceInformationService;
Amit Ghosh47243cb2017-07-26 05:08:53 +010075import org.osgi.service.component.ComponentContext;
76import org.slf4j.Logger;
77import org.slf4j.LoggerFactory;
78
79import java.nio.ByteBuffer;
80import java.util.Dictionary;
Amit Ghosha17354e2017-08-23 12:56:04 +010081import java.util.Map;
Deepa vaddireddy0060f532017-08-04 06:46:05 +000082import java.util.List;
Deepa vaddireddy0060f532017-08-04 06:46:05 +000083import java.util.Set;
Amit Ghosh8951f042017-08-10 13:48:10 +010084import java.util.concurrent.atomic.AtomicReference;
Deepa vaddireddy0060f532017-08-04 06:46:05 +000085import java.util.stream.Collectors;
Amit Ghosh47243cb2017-07-26 05:08:53 +010086
87import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_MessageType;
88import static org.onlab.packet.MacAddress.valueOf;
89import static org.onosproject.net.config.basics.SubjectFactories.APP_SUBJECT_FACTORY;
90
91/**
92 * DHCP Relay Agent Application Component.
93 */
94@Component(immediate = true)
95public class DhcpL2Relay {
96
97 public static final String DHCP_L2RELAY_APP = "org.opencord.dhcpl2relay";
98 private final Logger log = LoggerFactory.getLogger(getClass());
99 private final InternalConfigListener cfgListener =
100 new InternalConfigListener();
101
102 private final Set<ConfigFactory> factories = ImmutableSet.of(
103 new ConfigFactory<ApplicationId, DhcpL2RelayConfig>(APP_SUBJECT_FACTORY,
104 DhcpL2RelayConfig.class,
105 "dhcpl2relay") {
106 @Override
107 public DhcpL2RelayConfig createConfig() {
108 return new DhcpL2RelayConfig();
109 }
110 }
111 );
112
113 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
114 protected NetworkConfigRegistry cfgService;
115
116 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
117 protected CoreService coreService;
118
119 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
120 protected PacketService packetService;
121
122 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
123 protected HostService hostService;
124
125 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
126 protected ComponentConfigService componentConfigService;
127
128 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
129 protected SubscriberAndDeviceInformationService subsService;
130
131 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
132 protected DeviceService deviceService;
133
Amit Ghosh8951f042017-08-10 13:48:10 +0100134 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
135 protected MastershipService mastershipService;
136
Amit Ghosh47243cb2017-07-26 05:08:53 +0100137 @Property(name = "option82", boolValue = true,
138 label = "Add option 82 to relayed packets")
139 protected boolean option82 = true;
140
Amit Ghosha17354e2017-08-23 12:56:04 +0100141 @Property(name = "enableDhcpBroadcastReplies", boolValue = false,
142 label = "Add option 82 to relayed packets")
143 protected boolean enableDhcpBroadcastReplies = false;
144
Amit Ghosh47243cb2017-07-26 05:08:53 +0100145 private DhcpRelayPacketProcessor dhcpRelayPacketProcessor =
146 new DhcpRelayPacketProcessor();
147
Amit Ghosh8951f042017-08-10 13:48:10 +0100148 private InnerMastershipListener changeListener = new InnerMastershipListener();
149 private InnerDeviceListener deviceListener = new InnerDeviceListener();
Amit Ghosh47243cb2017-07-26 05:08:53 +0100150
Amit Ghosh8951f042017-08-10 13:48:10 +0100151 // connect points to the DHCP server
152 Set<ConnectPoint> dhcpConnectPoints;
153 private AtomicReference<ConnectPoint> dhcpServerConnectPoint = new AtomicReference<>();
Amit Ghosh47243cb2017-07-26 05:08:53 +0100154 private MacAddress dhcpConnectMac = MacAddress.BROADCAST;
155 private ApplicationId appId;
156
Amit Ghosha17354e2017-08-23 12:56:04 +0100157 static Map<String, DhcpAllocationInfo> allocationMap = Maps.newConcurrentMap();
158
Amit Ghosh47243cb2017-07-26 05:08:53 +0100159 @Activate
160 protected void activate(ComponentContext context) {
161 //start the dhcp relay agent
162 appId = coreService.registerApplication(DHCP_L2RELAY_APP);
163 componentConfigService.registerProperties(getClass());
164
165 cfgService.addListener(cfgListener);
Amit Ghosh8951f042017-08-10 13:48:10 +0100166 mastershipService.addListener(changeListener);
167 deviceService.addListener(deviceListener);
168
Amit Ghosh47243cb2017-07-26 05:08:53 +0100169 factories.forEach(cfgService::registerConfigFactory);
170 //update the dhcp server configuration.
171 updateConfig();
172 //add the packet services.
173 packetService.addProcessor(dhcpRelayPacketProcessor,
174 PacketProcessor.director(0));
175 requestDhcpPackets();
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000176 if (context != null) {
177 modified(context);
178 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100179
180 log.info("DHCP-L2-RELAY Started");
181 }
182
183 @Deactivate
184 protected void deactivate() {
185 cfgService.removeListener(cfgListener);
186 factories.forEach(cfgService::unregisterConfigFactory);
187 packetService.removeProcessor(dhcpRelayPacketProcessor);
188 cancelDhcpPackets();
189
190 componentConfigService.unregisterProperties(getClass(), false);
191
192 log.info("DHCP-L2-RELAY Stopped");
193 }
194
195 @Modified
196 protected void modified(ComponentContext context) {
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000197
Amit Ghosh47243cb2017-07-26 05:08:53 +0100198 Dictionary<?, ?> properties = context.getProperties();
199
200 Boolean o = Tools.isPropertyEnabled(properties, "option82");
201 if (o != null) {
202 option82 = o;
203 }
204 }
205
206 /**
207 * Checks if this app has been configured.
208 *
209 * @return true if all information we need have been initialized
210 */
211 private boolean configured() {
Amit Ghosh8951f042017-08-10 13:48:10 +0100212 return dhcpServerConnectPoint.get() != null;
Amit Ghosh47243cb2017-07-26 05:08:53 +0100213 }
214
Amit Ghosh8951f042017-08-10 13:48:10 +0100215 /**
216 * Selects a connect point through an available device for which it is the master.
217 */
218 private void selectServerConnectPoint() {
219 synchronized (this) {
220 dhcpServerConnectPoint.set(null);
221 if (dhcpConnectPoints != null) {
222 // find a connect point through a device for which we are master
223 for (ConnectPoint cp: dhcpConnectPoints) {
224 if (mastershipService.isLocalMaster(cp.deviceId())) {
225 if (deviceService.isAvailable(cp.deviceId())) {
226 dhcpServerConnectPoint.set(cp);
227 }
228 log.info("DHCP connectPoint selected is {}", cp);
229 break;
230 }
231 }
232 }
233
234 log.info("DHCP Server connectPoint is {}", dhcpServerConnectPoint.get());
235
236 if (dhcpServerConnectPoint.get() == null) {
237 log.error("Master of none, can't relay DHCP Message to server");
238 }
239 }
240 }
241
242 /**
243 * Updates the network configuration.
244 */
Amit Ghosh47243cb2017-07-26 05:08:53 +0100245 private void updateConfig() {
246 DhcpL2RelayConfig cfg = cfgService.getConfig(appId, DhcpL2RelayConfig.class);
247 if (cfg == null) {
248 log.warn("Dhcp Server info not available");
249 return;
250 }
Amit Ghosh8951f042017-08-10 13:48:10 +0100251
252 dhcpConnectPoints = Sets.newConcurrentHashSet(cfg.getDhcpServerConnectPoint());
253
254 selectServerConnectPoint();
Amit Ghosh47243cb2017-07-26 05:08:53 +0100255
Amit Ghosh47243cb2017-07-26 05:08:53 +0100256 log.info("dhcp server connect point: " + dhcpServerConnectPoint);
257 }
258
259 /**
260 * Request DHCP packet in via PacketService.
261 */
262 private void requestDhcpPackets() {
Amit Ghosh8951f042017-08-10 13:48:10 +0100263 TrafficSelector.Builder selectorServer = DefaultTrafficSelector.builder()
264 .matchEthType(Ethernet.TYPE_IPV4)
265 .matchIPProtocol(IPv4.PROTOCOL_UDP)
266 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_SERVER_PORT));
267 packetService.requestPackets(selectorServer.build(),
268 PacketPriority.CONTROL, appId);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100269
Amit Ghosh8951f042017-08-10 13:48:10 +0100270 TrafficSelector.Builder selectorClient = DefaultTrafficSelector.builder()
271 .matchEthType(Ethernet.TYPE_IPV4)
272 .matchIPProtocol(IPv4.PROTOCOL_UDP)
273 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_CLIENT_PORT));
274 packetService.requestPackets(selectorClient.build(),
275 PacketPriority.CONTROL, appId);
276
Amit Ghosh47243cb2017-07-26 05:08:53 +0100277 }
278
279 /**
280 * Cancel requested DHCP packets in via packet service.
281 */
282 private void cancelDhcpPackets() {
Amit Ghosh8951f042017-08-10 13:48:10 +0100283 TrafficSelector.Builder selectorServer = DefaultTrafficSelector.builder()
284 .matchEthType(Ethernet.TYPE_IPV4)
285 .matchIPProtocol(IPv4.PROTOCOL_UDP)
286 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_SERVER_PORT));
287 packetService.cancelPackets(selectorServer.build(),
288 PacketPriority.CONTROL, appId);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100289
Amit Ghosh8951f042017-08-10 13:48:10 +0100290 TrafficSelector.Builder selectorClient = DefaultTrafficSelector.builder()
291 .matchEthType(Ethernet.TYPE_IPV4)
292 .matchIPProtocol(IPv4.PROTOCOL_UDP)
293 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_CLIENT_PORT));
294 packetService.cancelPackets(selectorClient.build(),
295 PacketPriority.CONTROL, appId);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100296 }
297
Amit Ghosha17354e2017-08-23 12:56:04 +0100298 public static Map<String, DhcpAllocationInfo> allocationMap() {
299 return allocationMap;
300 }
301
Amit Ghosh47243cb2017-07-26 05:08:53 +0100302 private SubscriberAndDeviceInformation getDevice(PacketContext context) {
303 String serialNo = deviceService.getDevice(context.inPacket().
304 receivedFrom().deviceId()).serialNumber();
305
306 return subsService.get(serialNo);
307 }
308
309 private SubscriberAndDeviceInformation getDevice(ConnectPoint cp) {
310 String serialNo = deviceService.getDevice(cp.deviceId()).
311 serialNumber();
312
313 return subsService.get(serialNo);
314 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100315
316 private MacAddress relayAgentMacAddress(PacketContext context) {
317
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000318 SubscriberAndDeviceInformation device = this.getDevice(context);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100319 if (device == null) {
320 log.warn("Device not found for {}", context.inPacket().
321 receivedFrom());
322 return null;
323 }
324
325 return device.hardwareIdentifier();
326 }
327
328 private String nasPortId(PacketContext context) {
Amit Ghosh8951f042017-08-10 13:48:10 +0100329 return nasPortId(context.inPacket().receivedFrom());
330 }
331
332 private String nasPortId(ConnectPoint cp) {
333 Port p = deviceService.getPort(cp);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100334 return p.annotations().value(AnnotationKeys.PORT_NAME);
335 }
336
337 private SubscriberAndDeviceInformation getSubscriber(PacketContext context) {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100338 return subsService.get(nasPortId(context));
339 }
340
341 private VlanId cTag(PacketContext context) {
342 SubscriberAndDeviceInformation sub = getSubscriber(context);
343 if (sub == null) {
344 log.warn("Subscriber info not found for {}", context.inPacket().
345 receivedFrom());
346 return VlanId.NONE;
347 }
348 return sub.cTag();
349 }
350
Amit Ghosh8951f042017-08-10 13:48:10 +0100351 private VlanId cTag(ConnectPoint cp) {
352 String portId = nasPortId(cp);
353 SubscriberAndDeviceInformation sub = subsService.get(portId);
354 if (sub == null) {
355 log.warn("Subscriber info not found for {} looking for C-TAG", cp);
356 return VlanId.NONE;
357 }
358 return sub.cTag();
359 }
360
361 private VlanId sTag(ConnectPoint cp) {
362 String portId = nasPortId(cp);
363 SubscriberAndDeviceInformation sub = subsService.get(portId);
364 if (sub == null) {
365 log.warn("Subscriber info not found for {} looking for S-TAG", cp);
366 return VlanId.NONE;
367 }
368 return sub.sTag();
369 }
370
Amit Ghosh47243cb2017-07-26 05:08:53 +0100371 private VlanId sTag(PacketContext context) {
372 SubscriberAndDeviceInformation sub = getSubscriber(context);
373 if (sub == null) {
374 log.warn("Subscriber info not found for {}", context.inPacket().
375 receivedFrom());
376 return VlanId.NONE;
377 }
378 return sub.sTag();
379 }
380
381 private class DhcpRelayPacketProcessor implements PacketProcessor {
382
383 @Override
384 public void process(PacketContext context) {
385 if (!configured()) {
386 log.warn("Missing DHCP relay config. Abort packet processing");
387 return;
388 }
389
390 // process the packet and get the payload
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000391 DhcpEthernet packet = null;
392 ByteBuffer byteBuffer = context.inPacket().unparsed();
393 try {
394 packet = DhcpEthernet.deserializer().deserialize(byteBuffer.array(), 0, byteBuffer.array().length);
395 } catch (DeserializationException e) {
396 log.warn("Unable to deserialize packet");
397 }
398
Amit Ghosh47243cb2017-07-26 05:08:53 +0100399 if (packet == null) {
400 log.warn("Packet is null");
401 return;
402 }
403
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000404 log.debug("Got a packet ", packet);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100405
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000406 if (packet.getEtherType() == DhcpEthernet.TYPE_IPV4) {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100407 IPv4 ipv4Packet = (IPv4) packet.getPayload();
408
409 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_UDP) {
410 UDP udpPacket = (UDP) ipv4Packet.getPayload();
411 if (udpPacket.getSourcePort() == UDP.DHCP_CLIENT_PORT ||
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000412 udpPacket.getSourcePort() == UDP.DHCP_SERVER_PORT) {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100413 DHCP dhcpPayload = (DHCP) udpPacket.getPayload();
414 //This packet is dhcp.
415 processDhcpPacket(context, packet, dhcpPayload);
416 }
417 }
418 }
419 }
420
421 //forward the packet to ConnectPoint where the DHCP server is attached.
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000422 private void forwardPacket(DhcpEthernet packet) {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100423
Amit Ghosh8951f042017-08-10 13:48:10 +0100424 if (dhcpServerConnectPoint.get() != null) {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100425 TrafficTreatment t = DefaultTrafficTreatment.builder()
Amit Ghosh8951f042017-08-10 13:48:10 +0100426 .setOutput(dhcpServerConnectPoint.get().port()).build();
Amit Ghosh47243cb2017-07-26 05:08:53 +0100427 OutboundPacket o = new DefaultOutboundPacket(
Amit Ghosh8951f042017-08-10 13:48:10 +0100428 dhcpServerConnectPoint.get().deviceId(), t,
Amit Ghosh47243cb2017-07-26 05:08:53 +0100429 ByteBuffer.wrap(packet.serialize()));
430 if (log.isTraceEnabled()) {
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000431 log.trace("Relaying packet to dhcp server {} at {}",
Amit Ghosh8951f042017-08-10 13:48:10 +0100432 packet, dhcpServerConnectPoint.get());
Amit Ghosh47243cb2017-07-26 05:08:53 +0100433 }
434 packetService.emit(o);
435 } else {
436 log.warn("No dhcp server connect point");
437 }
438 }
439
Amit Ghosha17354e2017-08-23 12:56:04 +0100440 // get the type of the DHCP packet
441 private DHCPPacketType getDhcpPacketType(DHCP dhcpPayload) {
442
443 for (DHCPOption option : dhcpPayload.getOptions()) {
444 if (option.getCode() == OptionCode_MessageType.getValue()) {
445 byte[] data = option.getData();
446 return DHCPPacketType.getType(data[0]);
447 }
448 }
449 return null;
450 }
451
Amit Ghosh47243cb2017-07-26 05:08:53 +0100452 //process the dhcp packet before sending to server
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000453 private void processDhcpPacket(PacketContext context, DhcpEthernet packet,
Amit Ghosh47243cb2017-07-26 05:08:53 +0100454 DHCP dhcpPayload) {
455 if (dhcpPayload == null) {
456 log.warn("DHCP payload is null");
457 return;
458 }
459
Amit Ghosha17354e2017-08-23 12:56:04 +0100460 DHCPPacketType incomingPacketType = getDhcpPacketType(dhcpPayload);
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000461
Amit Ghosh47243cb2017-07-26 05:08:53 +0100462 log.info("Received DHCP Packet of type {}", incomingPacketType);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100463
464 switch (incomingPacketType) {
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000465 case DHCPDISCOVER:
466 DhcpEthernet ethernetPacketDiscover =
467 processDhcpPacketFromClient(context, packet);
468 if (ethernetPacketDiscover != null) {
469 forwardPacket(ethernetPacketDiscover);
470 }
471 break;
472 case DHCPOFFER:
473 //reply to dhcp client.
474 DhcpEthernet ethernetPacketOffer = processDhcpPacketFromServer(packet);
475 if (ethernetPacketOffer != null) {
476 sendReply(ethernetPacketOffer, dhcpPayload);
477 }
478 break;
479 case DHCPREQUEST:
480 DhcpEthernet ethernetPacketRequest =
481 processDhcpPacketFromClient(context, packet);
482 if (ethernetPacketRequest != null) {
483 forwardPacket(ethernetPacketRequest);
484 }
485 break;
486 case DHCPACK:
487 //reply to dhcp client.
488 DhcpEthernet ethernetPacketAck = processDhcpPacketFromServer(packet);
489 if (ethernetPacketAck != null) {
490 sendReply(ethernetPacketAck, dhcpPayload);
491 }
492 break;
493 default:
494 break;
Amit Ghosh47243cb2017-07-26 05:08:53 +0100495 }
496 }
497
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000498 private DhcpEthernet processDhcpPacketFromClient(PacketContext context,
499 DhcpEthernet ethernetPacket) {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100500
501 MacAddress relayAgentMac = relayAgentMacAddress(context);
502 if (relayAgentMac == null) {
503 log.warn("RelayAgent MAC not found ");
Amit Ghosh47243cb2017-07-26 05:08:53 +0100504 return null;
505 }
506
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000507 DhcpEthernet etherReply = ethernetPacket;
Amit Ghosh47243cb2017-07-26 05:08:53 +0100508
509 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
510 UDP udpPacket = (UDP) ipv4Packet.getPayload();
511 DHCP dhcpPacket = (DHCP) udpPacket.getPayload();
512
Amit Ghosha17354e2017-08-23 12:56:04 +0100513 if (enableDhcpBroadcastReplies) {
514 // We want the reply to come back as a L2 broadcast
515 dhcpPacket.setFlags((short) 0x8000);
516 }
517
518 // remove from the allocation map (used for display) as it's is
519 // requesting a fresh allocation
520 if (getDhcpPacketType(dhcpPacket) == DHCPPacketType.DHCPREQUEST) {
521
522 String portId = nasPortId(context.inPacket().receivedFrom());
523 SubscriberAndDeviceInformation sub = subsService.get(portId);
524 if (sub != null) {
525 allocationMap.remove(sub.nasPortId());
526 }
527 } // end allocation for display
528
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000529 if (option82) {
530 SubscriberAndDeviceInformation entry = getSubscriber(context);
531 if (entry == null) {
532 log.info("Dropping packet as subscriber entry is not available");
533 return null;
534 }
535
536 DHCP dhcpPacketWithOption82 = addOption82(dhcpPacket, entry);
537 udpPacket.setPayload(dhcpPacketWithOption82);
538 }
539
540 ipv4Packet.setPayload(udpPacket);
541 etherReply.setPayload(ipv4Packet);
542 etherReply.setSourceMacAddress(relayAgentMac);
543 etherReply.setDestinationMacAddress(dhcpConnectMac);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100544
Amit Ghosh8951f042017-08-10 13:48:10 +0100545 etherReply.setPriorityCode(ethernetPacket.getPriorityCode());
Amit Ghosh47243cb2017-07-26 05:08:53 +0100546 etherReply.setVlanID(cTag(context).toShort());
Amit Ghosha17354e2017-08-23 12:56:04 +0100547 etherReply.setQinQtpid(DhcpEthernet.TYPE_VLAN);
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000548 etherReply.setQinQVid(sTag(context).toShort());
Amit Ghosh47243cb2017-07-26 05:08:53 +0100549
Amit Ghosh8951f042017-08-10 13:48:10 +0100550 log.info("Finished processing packet -- sending packet {}", etherReply);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100551 return etherReply;
552 }
553
554 //build the DHCP offer/ack with proper client port.
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000555 private DhcpEthernet processDhcpPacketFromServer(DhcpEthernet ethernetPacket) {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100556 // get dhcp header.
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000557 DhcpEthernet etherReply = (DhcpEthernet) ethernetPacket.clone();
Amit Ghosh47243cb2017-07-26 05:08:53 +0100558 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
559 UDP udpPacket = (UDP) ipv4Packet.getPayload();
560 DHCP dhcpPayload = (DHCP) udpPacket.getPayload();
561
Amit Ghosh47243cb2017-07-26 05:08:53 +0100562 MacAddress dstMac = valueOf(dhcpPayload.getClientHardwareAddress());
Amit Ghosha17354e2017-08-23 12:56:04 +0100563 ConnectPoint subsCp = getConnectPointOfClient(dstMac);
564 // if it's an ACK packet store the information for display purpose
565 if (getDhcpPacketType(dhcpPayload) == DHCPPacketType.DHCPACK) {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100566
Amit Ghosha17354e2017-08-23 12:56:04 +0100567 String portId = nasPortId(subsCp);
568 SubscriberAndDeviceInformation sub = subsService.get(portId);
569 if (sub != null) {
570 List<DHCPOption> options = dhcpPayload.getOptions();
571 List<DHCPOption> circuitIds = options.stream()
572 .filter(option -> option.getCode() == DHCP.DHCPOptionCode.OptionCode_CircuitID.getValue())
573 .collect(Collectors.toList());
574
575 String circuitId = "None";
576 if (circuitIds.size() == 1) {
577 circuitId = circuitIds.get(0).getData().toString();
578 }
579
580 IpAddress ip = IpAddress.valueOf(dhcpPayload.getYourIPAddress());
581
582 //storeDHCPAllocationInfo
583 DhcpAllocationInfo info = new DhcpAllocationInfo(circuitId, dstMac, ip);
584
585 allocationMap.put(sub.nasPortId(), info);
586 }
587 } // end storing of info
Amit Ghosh47243cb2017-07-26 05:08:53 +0100588
589 // we leave the srcMac from the original packet
Amit Ghosh8951f042017-08-10 13:48:10 +0100590 etherReply.setDestinationMacAddress(dstMac);
591 etherReply.setQinQVid(sTag(subsCp).toShort());
592 etherReply.setPriorityCode(ethernetPacket.getPriorityCode());
593 etherReply.setVlanID((cTag(subsCp).toShort()));
Amit Ghosh47243cb2017-07-26 05:08:53 +0100594
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000595 if (option82) {
596 udpPacket.setPayload(removeOption82(dhcpPayload));
597 } else {
598 udpPacket.setPayload(dhcpPayload);
599 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100600 ipv4Packet.setPayload(udpPacket);
601 etherReply.setPayload(ipv4Packet);
602
603 log.info("Finished processing packet");
604 return etherReply;
605 }
606
Amit Ghosha17354e2017-08-23 12:56:04 +0100607 /*
608 * Get ConnectPoint of the Client based on it's MAC address
609 */
610 private ConnectPoint getConnectPointOfClient(MacAddress dstMac) {
611 Set<Host> hosts = hostService.getHostsByMac(dstMac);
612 if (hosts == null || hosts.isEmpty()) {
613 log.warn("Cannot determine host for DHCP client: {}. Aborting "
614 + "relay for dhcp packet from server",
615 dstMac);
616 return null;
617 }
618 for (Host h : hosts) {
619 // if more than one,
620 // find the connect point which has an valid entry in SADIS
621 ConnectPoint cp = new ConnectPoint(h.location().deviceId(),
622 h.location().port());
623
624 if (sTag(cp) != VlanId.NONE) {
625 return cp;
626 }
627 }
628
629 return null;
630 }
631
Amit Ghosh47243cb2017-07-26 05:08:53 +0100632 //send the response to the requester host.
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000633 private void sendReply(DhcpEthernet ethPacket, DHCP dhcpPayload) {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100634 MacAddress descMac = valueOf(dhcpPayload.getClientHardwareAddress());
Amit Ghosha17354e2017-08-23 12:56:04 +0100635 ConnectPoint subCp = getConnectPointOfClient(descMac);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100636
637 // Send packet out to requester if the host information is available
Amit Ghosha17354e2017-08-23 12:56:04 +0100638 if (subCp != null) {
639 log.info("Sending DHCP packet to cp: {}", subCp);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100640 TrafficTreatment t = DefaultTrafficTreatment.builder()
Amit Ghosha17354e2017-08-23 12:56:04 +0100641 .setOutput(subCp.port()).build();
Amit Ghosh47243cb2017-07-26 05:08:53 +0100642 OutboundPacket o = new DefaultOutboundPacket(
Amit Ghosha17354e2017-08-23 12:56:04 +0100643 subCp.deviceId(), t, ByteBuffer.wrap(ethPacket.serialize()));
Amit Ghosh47243cb2017-07-26 05:08:53 +0100644 if (log.isTraceEnabled()) {
645 log.trace("Relaying packet to dhcp client {}", ethPacket);
646 }
647 packetService.emit(o);
Amit Ghosha17354e2017-08-23 12:56:04 +0100648 log.info("DHCP Packet sent to {}", subCp);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100649 } else {
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000650 log.error("Dropping DHCP packet because can't find host for {}", descMac);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100651 }
652 }
653 }
654
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000655 private DHCP addOption82(DHCP dhcpPacket, SubscriberAndDeviceInformation entry) {
656 log.debug("option82data {} ", entry);
657
658 List<DHCPOption> options = Lists.newArrayList(dhcpPacket.getOptions());
659 DhcpOption82 option82 = new DhcpOption82();
660 option82.setAgentCircuitId(entry.circuitId());
661 option82.setAgentRemoteId(entry.remoteId());
662 DHCPOption option = new DHCPOption()
663 .setCode(DHCP.DHCPOptionCode.OptionCode_CircuitID.getValue())
664 .setData(option82.toByteArray())
665 .setLength(option82.length());
666
667 options.add(options.size() - 1, option);
668 dhcpPacket.setOptions(options);
Amit Ghosh8951f042017-08-10 13:48:10 +0100669
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000670 return dhcpPacket;
671
672 }
673
674 private DHCP removeOption82(DHCP dhcpPacket) {
675 List<DHCPOption> options = dhcpPacket.getOptions();
676 List<DHCPOption> newoptions = options.stream()
677 .filter(option -> option.getCode() != DHCP.DHCPOptionCode.OptionCode_CircuitID.getValue())
678 .collect(Collectors.toList());
679
680 return dhcpPacket.setOptions(newoptions);
681 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100682 /**
683 * Listener for network config events.
684 */
685 private class InternalConfigListener implements NetworkConfigListener {
686
687 @Override
688 public void event(NetworkConfigEvent event) {
689
690 if ((event.type() == NetworkConfigEvent.Type.CONFIG_ADDED ||
691 event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED) &&
692 event.configClass().equals(DhcpL2RelayConfig.class)) {
693 updateConfig();
694 log.info("Reconfigured");
695 }
696 }
697 }
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000698
Amit Ghosh8951f042017-08-10 13:48:10 +0100699 /**
700 * Handles Mastership changes for the devices which connect
701 * to the DHCP server.
702 */
703 private class InnerMastershipListener implements MastershipListener {
704 @Override
705 public void event(MastershipEvent event) {
706 if (dhcpServerConnectPoint.get() != null &&
707 dhcpServerConnectPoint.get().deviceId().
708 equals(event.subject())) {
709 log.trace("Mastership Event recevived for {}", event.subject());
710 // mastership of the device for our connect point has changed
711 // reselect
712 selectServerConnectPoint();
713 }
714 }
715 }
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000716
Amit Ghosh8951f042017-08-10 13:48:10 +0100717 /**
718 * Handles Device status change for the devices which connect
719 * to the DHCP server.
720 */
721 private class InnerDeviceListener implements DeviceListener {
722 @Override
723 public void event(DeviceEvent event) {
724 log.trace("Device Event recevived for {} event {}", event.subject(), event.type());
725 if (dhcpServerConnectPoint.get() == null) {
726 switch (event.type()) {
727 case DEVICE_ADDED:
728 case DEVICE_AVAILABILITY_CHANGED:
729 // some device is available check if we can get one
730 selectServerConnectPoint();
731 break;
732 default:
733 break;
734 }
735 return;
736 }
737 if (dhcpServerConnectPoint.get().deviceId().
738 equals(event.subject().id())) {
739 switch (event.type()) {
740 case DEVICE_AVAILABILITY_CHANGED:
741 case DEVICE_REMOVED:
742 case DEVICE_SUSPENDED:
743 // state of our device has changed, check if we need
744 // to re-select
745 selectServerConnectPoint();
746 break;
747 default:
748 break;
749 }
750 }
751 }
752 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100753}