Skip to content

Commit

Permalink
feat: Updated the ProfinetDriver, to intercept mac-address connection…
Browse files Browse the repository at this point in the history
… strings and in this case to initially update the remote devices IP address using PN-DCP before actually initializing the PN connection.
  • Loading branch information
chrisdutz committed Dec 17, 2023
1 parent 9faa864 commit 54fcaf6
Show file tree
Hide file tree
Showing 6 changed files with 217 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@
package org.apache.plc4x.java.profinet;

import io.netty.buffer.ByteBuf;
import org.apache.commons.net.util.SubnetUtils;
import org.apache.plc4x.java.api.PlcConnection;
import org.apache.plc4x.java.api.authentication.PlcAuthentication;
import org.apache.plc4x.java.api.exceptions.PlcConnectionException;
import org.apache.plc4x.java.api.messages.PlcDiscoveryRequest;
import org.apache.plc4x.java.api.metadata.PlcDriverMetadata;
import org.apache.plc4x.java.profinet.channel.ProfinetChannel;
Expand All @@ -27,25 +31,48 @@
import org.apache.plc4x.java.profinet.context.ProfinetDriverContext;
import org.apache.plc4x.java.profinet.discovery.ProfinetDiscoverer;
import org.apache.plc4x.java.profinet.protocol.ProfinetProtocolLogic;
import org.apache.plc4x.java.profinet.readwrite.Ethernet_Frame;
import org.apache.plc4x.java.profinet.readwrite.*;
import org.apache.plc4x.java.profinet.tag.ProfinetTag;
import org.apache.plc4x.java.profinet.tag.ProfinetTagHandler;
import org.apache.plc4x.java.spi.configuration.Configuration;
import org.apache.plc4x.java.spi.configuration.ConfigurationFactory;
import org.apache.plc4x.java.spi.connection.GeneratedDriverBase;
import org.apache.plc4x.java.spi.connection.ProtocolStackConfigurer;
import org.apache.plc4x.java.spi.connection.SingleProtocolStackConfigurer;
import org.apache.plc4x.java.spi.generation.ParseException;
import org.apache.plc4x.java.spi.generation.ReadBufferByteBased;
import org.apache.plc4x.java.spi.generation.SerializationException;
import org.apache.plc4x.java.spi.generation.WriteBufferByteBased;
import org.apache.plc4x.java.spi.messages.DefaultPlcDiscoveryRequest;
import org.apache.plc4x.java.spi.optimizer.BaseOptimizer;
import org.apache.plc4x.java.spi.optimizer.SingleTagOptimizer;
import org.apache.plc4x.java.spi.transport.TransportConfiguration;
import org.apache.plc4x.java.spi.transport.TransportConfigurationTypeProvider;
import org.pcap4j.core.PcapNativeException;
import org.pcap4j.core.Pcaps;
import org.pcap4j.core.*;
import org.pcap4j.packet.EthernetPacket;
import org.pcap4j.packet.IllegalRawDataException;
import org.pcap4j.packet.Packet;
import org.pcap4j.util.MacAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.*;
import java.util.Collections;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.ToIntFunction;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ProfinetDriver extends GeneratedDriverBase<Ethernet_Frame> implements TransportConfigurationTypeProvider {

private final Logger logger = LoggerFactory.getLogger(ProfinetDriver.class);

public static final Pattern MAC_ADDRESS = Pattern.compile(
"^([0-9A-Fa-f]{2}[\\\\.:-]){5}?");

public static final String DRIVER_CODE = "profinet";

@Override
Expand Down Expand Up @@ -171,4 +198,140 @@ public Class<? extends TransportConfiguration> getTransportConfigurationType(Str
return null;
}

@Override
public PlcConnection getConnection(String connectionString, PlcAuthentication authentication) throws PlcConnectionException {
// Check if this is a connection string with a MAC address and "assign-ip" in the options.
Matcher matcher = URI_PATTERN.matcher(connectionString);
if (!matcher.matches()) {
throw new PlcConnectionException(
"Connection string doesn't match the format '{protocol-code}:({transport-code})?//{transport-config}(?{parameter-string)?'");
}
final String protocolCode = matcher.group("protocolCode");
String transportCodeMatch = matcher.group("transportCode");
final String transportCode = (transportCodeMatch != null) ? transportCodeMatch : getDefaultTransport();
final String transportConfig = matcher.group("transportConfig");
final String paramString = matcher.group("paramString");
Matcher macMatcher = MAC_ADDRESS.matcher(connectionString);
if (!macMatcher.matches()) {
logger.info("Setting remote PROFINET device IP using DCP");
ConfigurationFactory configurationFactory = new ConfigurationFactory();
ProfinetConfiguration configuration = (ProfinetConfiguration) configurationFactory
.createConfiguration(getConfigurationType(), protocolCode, transportCode, transportConfig, paramString);
if (configuration == null) {
throw new PlcConnectionException("Unsupported configuration");
}

// Check if the paramString, contains an "ip-address" option, as this is required for connecting.
if(configuration.ipAddress == null) {
throw new PlcConnectionException("When using mac-address connection string, the parameter 'ip-address' is required");
}

// Find which network device could communicate with a device on the given IP address.
try {
Inet4Address inet4Address = (Inet4Address) Inet4Address.getByName(configuration.ipAddress);
deviceLoop: for (PcapNetworkInterface dev : Pcaps.findAllDevs()) {
// We're only interested in real running network interfaces, skip the rest.
if (dev.isLoopBack()) {
continue;
}

for (PcapAddress curAddress : dev.getAddresses()) {
if((curAddress.getAddress() == null) || (curAddress.getNetmask() == null)) {
continue;
}
if(!(curAddress instanceof PcapIpV4Address)) {
continue;
}
final SubnetUtils.SubnetInfo subnetInfo = new SubnetUtils(curAddress.getAddress().getHostAddress(), curAddress.getNetmask().getHostAddress()).getInfo();
if(subnetInfo.isInRange(inet4Address.getHostAddress())) {
ProfinetRawSocketTransportConfiguration profinetRawSocketTransportConfiguration = new ProfinetRawSocketTransportConfiguration();
InetSocketAddress remoteAddress = new InetSocketAddress(configuration.ipAddress, profinetRawSocketTransportConfiguration.getDefaultPort());
MacAddress remoteMacAddress = MacAddress.getByName(transportConfig);
MacAddress localMacAddress = dev.getLinkLayerAddresses().stream()
.filter(linkLayerAddress -> linkLayerAddress instanceof MacAddress).map(linkLayerAddress -> (MacAddress) linkLayerAddress)
.findFirst().orElse(null);

// TODO: Use DCP to assign an IP address to the device (Send one packet to every network device)
Ethernet_Frame frame = new Ethernet_Frame(
new org.apache.plc4x.java.profinet.readwrite.MacAddress(remoteMacAddress.getAddress()),
new org.apache.plc4x.java.profinet.readwrite.MacAddress(localMacAddress.getAddress()),
new Ethernet_FramePayload_VirtualLan(
VirtualLanPriority.INTERNETWORK_CONTROL,
false,
(short) 0,
new Ethernet_FramePayload_PnDcp(
new PcDcp_GetSet_Pdu(
PnDcp_FrameId.DCP_GetSet_PDU.getValue(),
false,
false,
0x10000001L,
Collections.singletonList(
new PnDcp_Block_IpParameter(
false,
false,
true,
remoteAddress.getAddress().getAddress(),
new byte[] {(byte) 255, (byte) 255, (byte) 255, (byte) 0},
new byte[] {(byte) 0, (byte) 0, (byte) 0, (byte) 0}
)
)
)
)
)
);
// Open a raw socket and send out the packet to the device.
try (PcapHandle handle = dev.openLive(65536, PcapNetworkInterface.PromiscuousMode.PROMISCUOUS, 10)) {
handle.setFilter(
// Profinet (0x8892) packets received from the remote mac address targeted at our own.
"(ether proto 0x8892) and (ether dst " + Pcaps.toBpfString(localMacAddress) + ") and (ether src " + Pcaps.toBpfString(remoteMacAddress) + ")",
BpfProgram.BpfCompileMode.OPTIMIZE);
WriteBufferByteBased buffer = new WriteBufferByteBased(frame.getLengthInBytes());
try {
frame.serialize(buffer);
Packet packet = EthernetPacket.newPacket(buffer.getBytes(), 0, frame.getLengthInBytes());
handle.sendPacket(packet);
} catch (PcapNativeException | NotOpenException | SerializationException |
IllegalRawDataException e) {
throw new RuntimeException(e);
}

// Now wait for a short while for the device to respond.
CompletableFuture<Boolean> future = new CompletableFuture<>();
handle.loop(1, (PacketListener) packet -> {
try {
ReadBufferByteBased readBuffer = new ReadBufferByteBased(packet.getRawData());
Ethernet_Frame ethernetFrame = Ethernet_Frame.staticParse(readBuffer);
if(ethernetFrame.getPayload() instanceof Ethernet_FramePayload_PnDcp) {
Ethernet_FramePayload_PnDcp payloadPnDcp = (Ethernet_FramePayload_PnDcp) ethernetFrame.getPayload();
if(payloadPnDcp.getPdu() instanceof PcDcp_GetSet_Pdu) {
// TODO: Possibly have a look if this operation was successful
future.complete(true);
return;
}
}
future.completeExceptionally(new PlcConnectionException("Unexpected response"));
} catch (ParseException e) {
future.completeExceptionally(new PlcConnectionException("Error setting ip address", e));
}
});
future.get(1000, TimeUnit.MILLISECONDS);

logger.info("Finished setting remote PROFINET device IP");
} catch (InterruptedException | TimeoutException | ExecutionException e) {
throw new PlcConnectionException(e);
}
break deviceLoop;
}
}
}
} catch (PcapNativeException | UnknownHostException |NotOpenException e) {
throw new PlcConnectionException(e);
}

// Use a re-written connection string using the IP to really connect.
return super.getConnection(String.format("%s:%s://%s?%s", protocolCode, transportCode, configuration.ipAddress, paramString), authentication);
}

return super.getConnection(connectionString, authentication);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ public Map<MacAddress, PcapHandle> getInterfaceHandles(List<PcapNetworkInterface
PcapHandle handle = dev.openLive(65536, PcapNetworkInterface.PromiscuousMode.PROMISCUOUS, 10);
openHandles.put(toPlc4xMacAddress(macAddress), handle);

// Only react on PROFINET, UDP or LLDP packets targeted at our current MAC address.
// Only react on PROFINET (0x8891), UDP (0x0800 ... actually IPv4) or LLDP (0x88CC) packets targeted at our current MAC address.
handle.setFilter(
"(ether proto 0x0800) or (((ether proto 0x8100) or (ether proto 0x8892)) and (ether dst " + Pcaps.toBpfString(macAddress) + ")) or (ether proto 0x88cc)",
BpfProgram.BpfCompileMode.OPTIMIZE);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ public class ProfinetConfiguration implements Configuration {
@ConfigurationParameter("dap-id")
public String dapId;

@ConfigurationParameter("ip-address")
public String ipAddress;

public ProfinetISO15745Profile getGsdProfile(int vendorId, int deviceId) {
String value = gsdDirectory;
if(value.startsWith("~")) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.apache.plc4x.java.profinet;

import org.apache.plc4x.java.DefaultPlcDriverManager;
import org.apache.plc4x.java.api.PlcConnection;
import org.apache.plc4x.java.api.messages.PlcSubscriptionRequest;
import org.apache.plc4x.java.api.messages.PlcSubscriptionResponse;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

public class ManualProfinetIoTest3 {

public static void main(String[] args) throws Exception {
// WireShark filter: "eth.addr == 00:30:de:61:37:79"
try(PlcConnection connection = new DefaultPlcDriverManager().getConnection("profinet:raw://00:30:de:61:37:79?ip-address=192.168.24.51")) {
// Create and execute the subscription request.
PlcSubscriptionRequest subscriptionRequest = connection.subscriptionRequestBuilder()
.addCyclicTagAddress("inputs", "1.1.INPUT.0:BYTE[10]", Duration.ofMillis(400))
.addCyclicTagAddress("output", "1.1.OUTPUT.0:DWORD", Duration.ofMillis(400))
.build();
PlcSubscriptionResponse subscriptionResponse = subscriptionRequest.execute().get(10000, TimeUnit.MILLISECONDS);
System.out.println(subscriptionResponse);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
</encoder>
</appender>

<root level="trace">
<root level="info">
<appender-ref ref="STDOUT" />
</root>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ protected void doConnect(SocketAddress remoteAddress, SocketAddress localAddress
if(remoteAddress instanceof RawSocketPassiveAddress) {
RawSocketPassiveAddress rawSocketPassiveAddress = (RawSocketPassiveAddress) remoteAddress;
String deviceName = getDeviceName(rawSocketPassiveAddress);
if(deviceName == null) {
if (deviceName == null) {
logger.error("Network device not specified and couldn't detect it automatically");
pipeline().fireExceptionCaught(
new PcapException("Network device not specified and couldn't detect it automatically"));
Expand Down

0 comments on commit 54fcaf6

Please sign in to comment.