dan-s1 commented on code in PR #8691: URL: https://github.com/apache/nifi/pull/8691#discussion_r1605314449
########## nifi-extension-bundles/nifi-network-bundle/nifi-network-processors/src/main/java/org/apache/nifi/processors/network/pcap/PCAP.java: ########## @@ -0,0 +1,438 @@ +// MIT License + +// Copyright (c) 2015-2023 Kaitai Project + +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +package org.apache.nifi.processors.network.pcap; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ListIterator; +import java.util.ArrayList; +import java.util.List; + +/** + * PCAP (named after libpcap / winpcap) is a popular format for saving + * network traffic grabbed by network sniffers. It is typically + * produced by tools like [tcpdump](<a href="https://www.tcpdump.org/">...</a>) or + * [Wireshark](<a href="https://www.wireshark.org/">...</a>). + * + * @see <a href= + * "https://wiki.wireshark.org/Development/LibpcapFileFormat">Source</a> + */ +public class PCAP { + private ByteBufferInterface io; + + public PCAP(ByteBufferInterface io) { + this(io, null, null); + } + + public PCAP(ByteBufferInterface io, Object parent, PCAP root) { + + this.parent = parent; + this.root = root == null ? this : root; + this.io = io; + read(); + } + + public PCAP(Header hdr, List<Packet> packets) { + this.hdr = hdr; + this.packets = packets; + } + + public byte[] readBytesFull() { + + int headerBufferSize = 20 + this.hdr().magicNumber().length; + ByteBuffer headerBuffer = ByteBuffer.allocate(headerBufferSize); + headerBuffer.order(ByteOrder.LITTLE_ENDIAN); + + headerBuffer.put(this.hdr().magicNumber()); + headerBuffer.put(this.readIntToNBytes(this.hdr().versionMajor(), 2, false)); + headerBuffer.put(this.readIntToNBytes(this.hdr().versionMinor(), 2, false)); + headerBuffer.put(this.readIntToNBytes(this.hdr().thiszone(), 4, false)); + headerBuffer.put(this.readLongToNBytes(this.hdr().sigfigs(), 4, true)); + headerBuffer.put(this.readLongToNBytes(this.hdr().snaplen(), 4, true)); + headerBuffer.put(this.readLongToNBytes(this.hdr().network(), 4, true)); + + List<byte[]> packetByteArrays = new ArrayList<>(); + + ListIterator<Packet> packetsIterator = packets.listIterator(); + + int packetBufferSize = 0; + + for (int loop = 0; loop < packets.size(); loop++) { + Packet currentPacket = packetsIterator.next(); + ByteBuffer currentPacketBytes = ByteBuffer.allocate(16 + currentPacket.rawBody().length); + currentPacketBytes.put(readLongToNBytes(currentPacket.tsSec, 4, false)); + currentPacketBytes.put(readLongToNBytes(currentPacket.tsUsec, 4, false)); + currentPacketBytes.put(readLongToNBytes(currentPacket.inclLen, 4, false)); + currentPacketBytes.put(readLongToNBytes(currentPacket.origLen, 4, false)); + currentPacketBytes.put(currentPacket.rawBody()); + + packetByteArrays.add(currentPacketBytes.array()); + packetBufferSize += 16 + currentPacket.rawBody().length; + } + + ByteBuffer packetBuffer = ByteBuffer.allocate(packetBufferSize); + packetBuffer.order(ByteOrder.LITTLE_ENDIAN); + + for (byte[] packetByteArray : packetByteArrays) { + packetBuffer.put(packetByteArray); + } + + ByteBuffer allBytes = ByteBuffer.allocate(headerBufferSize + packetBufferSize); + allBytes.order(ByteOrder.LITTLE_ENDIAN); + + allBytes.put(headerBuffer.array()); + allBytes.put(packetBuffer.array()); + + return allBytes.array(); + } + + private byte[] readIntToNBytes(int input, int numberOfBytes, boolean isSigned) { + byte[] output = new byte[numberOfBytes]; + output[0] = (byte) (input & 0xff); + for (int loop = 1; loop < numberOfBytes; loop++) { + if (isSigned) { + output[loop] = (byte) (input >> (8 * loop)); + } else { + output[loop] = (byte) (input >>> (8 * loop)); + } + } + return output; + } + + private byte[] readLongToNBytes(long input, int numberOfBytes, boolean isSigned) { + byte[] output = new byte[numberOfBytes]; + output[0] = (byte) (input & 0xff); + for (int loop = 1; loop < numberOfBytes; loop++) { + if (isSigned) { + output[loop] = (byte) (input >> (8 * loop)); + } else { + output[loop] = (byte) (input >>> (8 * loop)); + } + } + return output; + } + + private void read() { + this.hdr = new Header(this.io, this, root); + this.packets = new ArrayList<>(); + { + while (!this.io.isEof()) { + this.packets.add(new Packet(this.io, this, root)); + } + } + } + + public static class ByteBufferInterface { Review Comment: Since there is a separate package now, please refactor and place classes `ByteBufferInterface`, `Header` and `Packet` in their own files. Please remember to use the `MIT License` found in the `PCAP` file. Also one gotcha when placing `Packet` in its own file are lines 84-87 instead of the access to private variables use the public access methods. i.e. instead of ``` currentPacketBytes.put(readLongToNBytes(currentPacket.tsSec, 4, false)); currentPacketBytes.put(readLongToNBytes(currentPacket.tsUsec, 4, false)); currentPacketBytes.put(readLongToNBytes(currentPacket.inclLen, 4, false)); currentPacketBytes.put(readLongToNBytes(currentPacket.origLen, 4, false)); ``` use ``` currentPacketBytes.put(readLongToNBytes(currentPacket.tsSec(), 4, false)); currentPacketBytes.put(readLongToNBytes(currentPacket.tsUsec(), 4, false)); currentPacketBytes.put(readLongToNBytes(currentPacket.inclLen(), 4, false)); currentPacketBytes.put(readLongToNBytes(currentPacket.origLen(), 4, false)); ``` ########## nifi-extension-bundles/nifi-network-bundle/nifi-network-processors/src/main/java/org/apache/nifi/processors/network/pcap/PCAP.java: ########## @@ -0,0 +1,438 @@ +// MIT License + +// Copyright (c) 2015-2023 Kaitai Project + +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +package org.apache.nifi.processors.network.pcap; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ListIterator; +import java.util.ArrayList; +import java.util.List; + +/** + * PCAP (named after libpcap / winpcap) is a popular format for saving + * network traffic grabbed by network sniffers. It is typically + * produced by tools like [tcpdump](<a href="https://www.tcpdump.org/">...</a>) or + * [Wireshark](<a href="https://www.wireshark.org/">...</a>). + * + * @see <a href= + * "https://wiki.wireshark.org/Development/LibpcapFileFormat">Source</a> + */ +public class PCAP { + private ByteBufferInterface io; + + public PCAP(ByteBufferInterface io) { + this(io, null, null); + } + + public PCAP(ByteBufferInterface io, Object parent, PCAP root) { + + this.parent = parent; + this.root = root == null ? this : root; + this.io = io; + read(); + } + + public PCAP(Header hdr, List<Packet> packets) { + this.hdr = hdr; + this.packets = packets; + } + + public byte[] readBytesFull() { + + int headerBufferSize = 20 + this.hdr().magicNumber().length; + ByteBuffer headerBuffer = ByteBuffer.allocate(headerBufferSize); + headerBuffer.order(ByteOrder.LITTLE_ENDIAN); + + headerBuffer.put(this.hdr().magicNumber()); + headerBuffer.put(this.readIntToNBytes(this.hdr().versionMajor(), 2, false)); + headerBuffer.put(this.readIntToNBytes(this.hdr().versionMinor(), 2, false)); + headerBuffer.put(this.readIntToNBytes(this.hdr().thiszone(), 4, false)); + headerBuffer.put(this.readLongToNBytes(this.hdr().sigfigs(), 4, true)); + headerBuffer.put(this.readLongToNBytes(this.hdr().snaplen(), 4, true)); + headerBuffer.put(this.readLongToNBytes(this.hdr().network(), 4, true)); + + List<byte[]> packetByteArrays = new ArrayList<>(); + + ListIterator<Packet> packetsIterator = packets.listIterator(); + + int packetBufferSize = 0; + + for (int loop = 0; loop < packets.size(); loop++) { + Packet currentPacket = packetsIterator.next(); + ByteBuffer currentPacketBytes = ByteBuffer.allocate(16 + currentPacket.rawBody().length); + currentPacketBytes.put(readLongToNBytes(currentPacket.tsSec, 4, false)); + currentPacketBytes.put(readLongToNBytes(currentPacket.tsUsec, 4, false)); + currentPacketBytes.put(readLongToNBytes(currentPacket.inclLen, 4, false)); + currentPacketBytes.put(readLongToNBytes(currentPacket.origLen, 4, false)); + currentPacketBytes.put(currentPacket.rawBody()); + + packetByteArrays.add(currentPacketBytes.array()); + packetBufferSize += 16 + currentPacket.rawBody().length; + } + + ByteBuffer packetBuffer = ByteBuffer.allocate(packetBufferSize); + packetBuffer.order(ByteOrder.LITTLE_ENDIAN); + + for (byte[] packetByteArray : packetByteArrays) { + packetBuffer.put(packetByteArray); + } + + ByteBuffer allBytes = ByteBuffer.allocate(headerBufferSize + packetBufferSize); + allBytes.order(ByteOrder.LITTLE_ENDIAN); + + allBytes.put(headerBuffer.array()); + allBytes.put(packetBuffer.array()); + + return allBytes.array(); + } + + private byte[] readIntToNBytes(int input, int numberOfBytes, boolean isSigned) { + byte[] output = new byte[numberOfBytes]; + output[0] = (byte) (input & 0xff); + for (int loop = 1; loop < numberOfBytes; loop++) { + if (isSigned) { + output[loop] = (byte) (input >> (8 * loop)); + } else { + output[loop] = (byte) (input >>> (8 * loop)); + } + } + return output; + } + + private byte[] readLongToNBytes(long input, int numberOfBytes, boolean isSigned) { + byte[] output = new byte[numberOfBytes]; + output[0] = (byte) (input & 0xff); + for (int loop = 1; loop < numberOfBytes; loop++) { + if (isSigned) { + output[loop] = (byte) (input >> (8 * loop)); + } else { + output[loop] = (byte) (input >>> (8 * loop)); + } + } + return output; + } + + private void read() { + this.hdr = new Header(this.io, this, root); + this.packets = new ArrayList<>(); + { + while (!this.io.isEof()) { + this.packets.add(new Packet(this.io, this, root)); + } + } + } + + public static class ByteBufferInterface { + + public ByteBufferInterface(byte[] byteArray) { + this.buffer = ByteBuffer.wrap(byteArray); + } + + public static class ValidationNotEqualError extends Exception { + public ValidationNotEqualError(String message) { + super(message); + } + } + + public ByteBuffer buffer; + + public int readU2be() { + buffer.order(ByteOrder.BIG_ENDIAN); + return (buffer.getShort() & 0xffff); + } + + public int readU2le() { + buffer.order(ByteOrder.LITTLE_ENDIAN); + return (buffer.getShort() & 0xffff); + } + + public long readU4be() { + buffer.order(ByteOrder.BIG_ENDIAN); + return ((long) buffer.getInt() & 0xffffffffL); + } + + public long readU4le() { + buffer.order(ByteOrder.LITTLE_ENDIAN); + return ((long) buffer.getInt() & 0xffffffffL); + } + + public int readS4be() { + buffer.order(ByteOrder.BIG_ENDIAN); + return buffer.getInt(); + } + + public int readS4le() { + buffer.order(ByteOrder.LITTLE_ENDIAN); + return buffer.getInt(); + } + + public byte[] readBytes(int n) { + byte[] output = new byte[n]; + buffer.get(output); + return output; + } + + public byte[] readBytes(long n) { + byte[] output = new byte[(int) n]; + buffer.get(output); + return output; + } + + public boolean isEof() { + return !buffer.hasRemaining(); + } + } + + /** + * @see <a href= + * "https://wiki.wireshark.org/Development/LibpcapFileFormat#Global_Header">Source</a> + */ + public static class Header { + private ByteBufferInterface io; + private final Logger logger = LoggerFactory.getLogger(Header.class); + + public Header(ByteBufferInterface io, PCAP parent, PCAP root) { + + this.parent = parent; + this.root = root; + this.io = io; + + try { + read(); + } catch (ByteBufferInterface.ValidationNotEqualError e) { + this.logger.error("PCAP file header could not be parsed due to {}", e); + } + } + + public Header(byte[] magicNumber, int versionMajor, int versionMinor, int thiszone, long sigfigs, long snaplen, + long network) { + + this.magicNumber = magicNumber; + this.versionMajor = versionMajor; + this.versionMinor = versionMinor; + this.thiszone = thiszone; + this.sigfigs = sigfigs; + this.snaplen = snaplen; + this.network = network; + } + + public ByteBufferInterface io() { + return io; + } + + private void read() + throws ByteBufferInterface.ValidationNotEqualError { + this.magicNumber = this.io.readBytes(4); + if (this.magicNumber == new byte[] {(byte) 0xd4, (byte) 0xc3, (byte) 0xb2, (byte) 0xa1 }) { + // have to swap the bits + this.versionMajor = this.io.readU2be(); + if (!(versionMajor() == 2)) { + + throw new ByteBufferInterface.ValidationNotEqualError("Packet major version is not 2."); + } + this.versionMinor = this.io.readU2be(); + this.thiszone = this.io.readS4be(); + this.sigfigs = this.io.readU4be(); + this.snaplen = this.io.readU4be(); + this.network = this.io.readU4be(); + } else { + this.versionMajor = this.io.readU2le(); + if (!(versionMajor() == 2)) { + throw new ByteBufferInterface.ValidationNotEqualError("Packet major version is not 2."); + } + this.versionMinor = this.io.readU2le(); + this.thiszone = this.io.readS4le(); + this.sigfigs = this.io.readU4le(); + this.snaplen = this.io.readU4le(); + this.network = this.io.readU4le(); + } + } + + private byte[] magicNumber; + private int versionMajor; + private int versionMinor; + private int thiszone; + private long sigfigs; + private long snaplen; + private long network; + private PCAP root; + private PCAP parent; + + public byte[] magicNumber() { + return magicNumber; + } + + public int versionMajor() { + return versionMajor; + } + + public int versionMinor() { + return versionMinor; + } + + /** + * Correction time in seconds between UTC and the local + * timezone of the following packet header timestamps. + */ + public int thiszone() { + return thiszone; + } + + /** + * In theory, the accuracy of time stamps in the capture; in + * practice, all tools set it to 0. + */ + public long sigfigs() { + return sigfigs; + } + + /** + * The "snapshot length" for the capture (typically 65535 or + * even more, but might be limited by the user), see: incl_len + * vs. orig_len. + */ + public long snaplen() { + return snaplen; + } + + /** + * Link-layer header type, specifying the type of headers at + * the beginning of the packet. + */ + public long network() { + return network; + } + + public PCAP root() { + return root; + } + + public PCAP parent() { + return parent; + } + } + + /** + * @see <a href= + * "https://wiki.wireshark.org/Development/LibpcapFileFormat#Record_.28Packet.29_Header">Source</a> + */ + public static class Packet { + public ByteBufferInterface io; + + public Packet(ByteBufferInterface io, PCAP parent, PCAP root) { + + this.parent = parent; + this.root = root; + this.io = io; + read(); + } + + public Packet(long tSSec, long tSUsec, long inclLen, long origLen, byte[] rawBody) { + + this.tsSec = tSSec; + this.tsUsec = tSUsec; + this.inclLen = inclLen; + this.origLen = origLen; + this.rawBody = rawBody; + } + + private void read() { + this.tsSec = this.io.readU4le(); + this.tsUsec = this.io.readU4le(); + this.inclLen = this.io.readU4le(); + this.origLen = this.io.readU4le(); + this.rawBody = this.io.readBytes((inclLen() < root().hdr().snaplen() ? inclLen() : root().hdr().snaplen())); Review Comment: Intellij suggests ```suggestion this.rawBody = this.io.readBytes((Math.min(inclLen(), root().hdr().snaplen()))); ``` ########## nifi-extension-bundles/nifi-network-bundle/nifi-network-processors/src/main/java/org/apache/nifi/processors/network/pcap/PCAP.java: ########## @@ -0,0 +1,438 @@ +// MIT License + +// Copyright (c) 2015-2023 Kaitai Project + +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +package org.apache.nifi.processors.network.pcap; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ListIterator; +import java.util.ArrayList; +import java.util.List; + +/** + * PCAP (named after libpcap / winpcap) is a popular format for saving + * network traffic grabbed by network sniffers. It is typically + * produced by tools like [tcpdump](<a href="https://www.tcpdump.org/">...</a>) or + * [Wireshark](<a href="https://www.wireshark.org/">...</a>). + * + * @see <a href= + * "https://wiki.wireshark.org/Development/LibpcapFileFormat">Source</a> + */ +public class PCAP { + private ByteBufferInterface io; + + public PCAP(ByteBufferInterface io) { + this(io, null, null); + } + + public PCAP(ByteBufferInterface io, Object parent, PCAP root) { + + this.parent = parent; + this.root = root == null ? this : root; + this.io = io; + read(); + } + + public PCAP(Header hdr, List<Packet> packets) { + this.hdr = hdr; + this.packets = packets; + } + + public byte[] readBytesFull() { + + int headerBufferSize = 20 + this.hdr().magicNumber().length; + ByteBuffer headerBuffer = ByteBuffer.allocate(headerBufferSize); + headerBuffer.order(ByteOrder.LITTLE_ENDIAN); + + headerBuffer.put(this.hdr().magicNumber()); + headerBuffer.put(this.readIntToNBytes(this.hdr().versionMajor(), 2, false)); + headerBuffer.put(this.readIntToNBytes(this.hdr().versionMinor(), 2, false)); + headerBuffer.put(this.readIntToNBytes(this.hdr().thiszone(), 4, false)); + headerBuffer.put(this.readLongToNBytes(this.hdr().sigfigs(), 4, true)); + headerBuffer.put(this.readLongToNBytes(this.hdr().snaplen(), 4, true)); + headerBuffer.put(this.readLongToNBytes(this.hdr().network(), 4, true)); + + List<byte[]> packetByteArrays = new ArrayList<>(); + + ListIterator<Packet> packetsIterator = packets.listIterator(); + + int packetBufferSize = 0; + + for (int loop = 0; loop < packets.size(); loop++) { + Packet currentPacket = packetsIterator.next(); + ByteBuffer currentPacketBytes = ByteBuffer.allocate(16 + currentPacket.rawBody().length); + currentPacketBytes.put(readLongToNBytes(currentPacket.tsSec, 4, false)); + currentPacketBytes.put(readLongToNBytes(currentPacket.tsUsec, 4, false)); + currentPacketBytes.put(readLongToNBytes(currentPacket.inclLen, 4, false)); + currentPacketBytes.put(readLongToNBytes(currentPacket.origLen, 4, false)); + currentPacketBytes.put(currentPacket.rawBody()); + + packetByteArrays.add(currentPacketBytes.array()); + packetBufferSize += 16 + currentPacket.rawBody().length; + } + + ByteBuffer packetBuffer = ByteBuffer.allocate(packetBufferSize); + packetBuffer.order(ByteOrder.LITTLE_ENDIAN); + + for (byte[] packetByteArray : packetByteArrays) { + packetBuffer.put(packetByteArray); + } + + ByteBuffer allBytes = ByteBuffer.allocate(headerBufferSize + packetBufferSize); + allBytes.order(ByteOrder.LITTLE_ENDIAN); + + allBytes.put(headerBuffer.array()); + allBytes.put(packetBuffer.array()); + + return allBytes.array(); + } + + private byte[] readIntToNBytes(int input, int numberOfBytes, boolean isSigned) { + byte[] output = new byte[numberOfBytes]; + output[0] = (byte) (input & 0xff); + for (int loop = 1; loop < numberOfBytes; loop++) { + if (isSigned) { + output[loop] = (byte) (input >> (8 * loop)); + } else { + output[loop] = (byte) (input >>> (8 * loop)); + } + } + return output; + } + + private byte[] readLongToNBytes(long input, int numberOfBytes, boolean isSigned) { + byte[] output = new byte[numberOfBytes]; + output[0] = (byte) (input & 0xff); + for (int loop = 1; loop < numberOfBytes; loop++) { + if (isSigned) { + output[loop] = (byte) (input >> (8 * loop)); + } else { + output[loop] = (byte) (input >>> (8 * loop)); + } + } + return output; + } + + private void read() { + this.hdr = new Header(this.io, this, root); + this.packets = new ArrayList<>(); + { + while (!this.io.isEof()) { + this.packets.add(new Packet(this.io, this, root)); + } + } + } + + public static class ByteBufferInterface { + + public ByteBufferInterface(byte[] byteArray) { + this.buffer = ByteBuffer.wrap(byteArray); + } + + public static class ValidationNotEqualError extends Exception { + public ValidationNotEqualError(String message) { + super(message); + } + } + + public ByteBuffer buffer; + + public int readU2be() { + buffer.order(ByteOrder.BIG_ENDIAN); + return (buffer.getShort() & 0xffff); + } + + public int readU2le() { + buffer.order(ByteOrder.LITTLE_ENDIAN); + return (buffer.getShort() & 0xffff); + } + + public long readU4be() { + buffer.order(ByteOrder.BIG_ENDIAN); + return ((long) buffer.getInt() & 0xffffffffL); + } + + public long readU4le() { + buffer.order(ByteOrder.LITTLE_ENDIAN); + return ((long) buffer.getInt() & 0xffffffffL); + } + + public int readS4be() { + buffer.order(ByteOrder.BIG_ENDIAN); + return buffer.getInt(); + } + + public int readS4le() { + buffer.order(ByteOrder.LITTLE_ENDIAN); + return buffer.getInt(); + } + + public byte[] readBytes(int n) { + byte[] output = new byte[n]; + buffer.get(output); + return output; + } + + public byte[] readBytes(long n) { + byte[] output = new byte[(int) n]; + buffer.get(output); + return output; + } + + public boolean isEof() { + return !buffer.hasRemaining(); + } + } + + /** + * @see <a href= + * "https://wiki.wireshark.org/Development/LibpcapFileFormat#Global_Header">Source</a> + */ + public static class Header { + private ByteBufferInterface io; + private final Logger logger = LoggerFactory.getLogger(Header.class); + + public Header(ByteBufferInterface io, PCAP parent, PCAP root) { + + this.parent = parent; + this.root = root; + this.io = io; + + try { + read(); + } catch (ByteBufferInterface.ValidationNotEqualError e) { + this.logger.error("PCAP file header could not be parsed due to {}", e); Review Comment: There is no argument to insert so `{}` can be removed ```suggestion this.logger.error("PCAP file header could not be parsed due to ", e); ``` ########## nifi-extension-bundles/nifi-network-bundle/nifi-network-processors/src/main/java/org/apache/nifi/processors/network/pcap/SplitPCAP.java: ########## @@ -0,0 +1,209 @@ +/* + * 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 + * + * http://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.nifi.processors.network.pcap; + +import org.apache.nifi.components.PropertyDescriptor; +import org.apache.nifi.flowfile.FlowFile; +import org.apache.nifi.annotation.behavior.InputRequirement; +import org.apache.nifi.annotation.behavior.InputRequirement.Requirement; +import org.apache.nifi.annotation.behavior.SideEffectFree; +import org.apache.nifi.annotation.behavior.WritesAttribute; +import org.apache.nifi.annotation.behavior.WritesAttributes; +import org.apache.nifi.annotation.documentation.CapabilityDescription; +import org.apache.nifi.annotation.documentation.Tags; +import org.apache.nifi.processor.AbstractProcessor; +import org.apache.nifi.processor.ProcessContext; +import org.apache.nifi.processor.ProcessSession; +import org.apache.nifi.processor.Relationship; +import org.apache.nifi.processor.util.StandardValidators; +import org.apache.nifi.flowfile.attributes.FragmentAttributes; +import org.apache.nifi.flowfile.attributes.CoreAttributes; +import org.apache.nifi.processors.network.pcap.PCAP.ByteBufferInterface; +import org.apache.nifi.processors.network.pcap.PCAP.Packet; + +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.IntStream; + +@SideEffectFree +@InputRequirement(Requirement.INPUT_REQUIRED) +@Tags({"PCAP", "Splitter", "Network", "Packet", "Capture", "Wireshark", "TShark"}) +@CapabilityDescription("Splits a pcap file into multiple pcap files based on a maximum size.") +@WritesAttributes({ + @WritesAttribute(attribute = SplitPCAP.ERROR_REASON, description = "The reason the flowfile was sent to the failure relationship."), + @WritesAttribute(attribute = "fragment.identifier", description = "All split FlowFiles produced from the same parent FlowFile will have the same randomly generated UUID added for this attribute"), + @WritesAttribute(attribute = "fragment.index", description = "A one-up number that indicates the ordering of the split FlowFiles that were created from a single parent FlowFile"), + @WritesAttribute(attribute = "fragment.count", description = "The number of split FlowFiles generated from the parent FlowFile"), + @WritesAttribute(attribute = "segment.original.filename ", description = "The filename of the parent FlowFile") +}) + +public class SplitPCAP extends AbstractProcessor { + + protected static final String ERROR_REASON = "ERROR_REASON"; + public static final String FRAGMENT_ID = FragmentAttributes.FRAGMENT_ID.key(); + public static final String FRAGMENT_INDEX = FragmentAttributes.FRAGMENT_INDEX.key(); + public static final String FRAGMENT_COUNT = FragmentAttributes.FRAGMENT_COUNT.key(); + public static final String SEGMENT_ORIGINAL_FILENAME = FragmentAttributes.SEGMENT_ORIGINAL_FILENAME.key(); + + public static final PropertyDescriptor PCAP_MAX_SIZE = new PropertyDescriptor + .Builder().name("PCAP_MAX_SIZE") + .displayName("PCAP max size (bytes)") + .description("Maximum size of the output pcap file in bytes.") + .required(true) + .addValidator(StandardValidators.POSITIVE_INTEGER_VALIDATOR) + .build(); + + public static final Relationship REL_ORIGINAL = new Relationship.Builder() + .name("original") + .description("The original FlowFile that was split into segments. If the FlowFile fails processing, nothing will be sent to " + + "this relationship") + .build(); + public static final Relationship REL_FAILURE = new Relationship.Builder() + .name("failure") + .description("If a FlowFile cannot be transformed from the configured input format to the configured output format, " + + "the unchanged FlowFile will be routed to this relationship.") + .build(); + public static final Relationship REL_SPLIT = new Relationship.Builder() + .name("split") + .description("The individual 'segments' of the original FlowFile will be routed to this relationship.") + .build(); + + private static final List<PropertyDescriptor> DESCRIPTORS = List.of(PCAP_MAX_SIZE); + + private static final Set<Relationship> RELATIONSHIPS = Set.of(REL_ORIGINAL, REL_FAILURE, REL_SPLIT); + + @Override + public Set<Relationship> getRelationships() { + return RELATIONSHIPS; + } + + @Override + public final List<PropertyDescriptor> getSupportedPropertyDescriptors() { + return DESCRIPTORS; + } + + /** + * This method is called when a trigger event occurs in the processor. + * It processes the incoming flow file, splits it into smaller pcap files based on the maximum size, Review Comment: ```suggestion * It processes the incoming flow file, splits it into smaller pcap files based on the PCAP Max Size, ``` ########## nifi-extension-bundles/nifi-network-bundle/nifi-network-processors/src/main/java/org/apache/nifi/processors/network/pcap/SplitPCAP.java: ########## @@ -0,0 +1,209 @@ +/* + * 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 + * + * http://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.nifi.processors.network.pcap; + +import org.apache.nifi.components.PropertyDescriptor; +import org.apache.nifi.flowfile.FlowFile; +import org.apache.nifi.annotation.behavior.InputRequirement; +import org.apache.nifi.annotation.behavior.InputRequirement.Requirement; +import org.apache.nifi.annotation.behavior.SideEffectFree; +import org.apache.nifi.annotation.behavior.WritesAttribute; +import org.apache.nifi.annotation.behavior.WritesAttributes; +import org.apache.nifi.annotation.documentation.CapabilityDescription; +import org.apache.nifi.annotation.documentation.Tags; +import org.apache.nifi.processor.AbstractProcessor; +import org.apache.nifi.processor.ProcessContext; +import org.apache.nifi.processor.ProcessSession; +import org.apache.nifi.processor.Relationship; +import org.apache.nifi.processor.util.StandardValidators; +import org.apache.nifi.flowfile.attributes.FragmentAttributes; +import org.apache.nifi.flowfile.attributes.CoreAttributes; +import org.apache.nifi.processors.network.pcap.PCAP.ByteBufferInterface; +import org.apache.nifi.processors.network.pcap.PCAP.Packet; + +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.IntStream; + +@SideEffectFree +@InputRequirement(Requirement.INPUT_REQUIRED) +@Tags({"PCAP", "Splitter", "Network", "Packet", "Capture", "Wireshark", "TShark"}) +@CapabilityDescription("Splits a pcap file into multiple pcap files based on a maximum size.") +@WritesAttributes({ + @WritesAttribute(attribute = SplitPCAP.ERROR_REASON, description = "The reason the flowfile was sent to the failure relationship."), + @WritesAttribute(attribute = "fragment.identifier", description = "All split FlowFiles produced from the same parent FlowFile will have the same randomly generated UUID added for this attribute"), + @WritesAttribute(attribute = "fragment.index", description = "A one-up number that indicates the ordering of the split FlowFiles that were created from a single parent FlowFile"), + @WritesAttribute(attribute = "fragment.count", description = "The number of split FlowFiles generated from the parent FlowFile"), + @WritesAttribute(attribute = "segment.original.filename ", description = "The filename of the parent FlowFile") +}) Review Comment: I think it would be a good idea to individualize these descriptions for PCAP ```suggestion @WritesAttribute(attribute = "fragment.identifier", description = "All PCAP split FlowFiles produced from the same parent PCAP FlowFile will have the same randomly generated UUID added for this attribute"), @WritesAttribute(attribute = "fragment.index", description = "A one-up number that indicates the ordering of the split PCAP FlowFiles that were created from a single parent PCAP FlowFile"), @WritesAttribute(attribute = "fragment.count", description = "The number of split PCAP FlowFiles generated from the parent PCAP FlowFile"), @WritesAttribute(attribute = "segment.original.filename ", description = "The filename of the parent PCAP FlowFile") }) ``` ########## nifi-extension-bundles/nifi-network-bundle/nifi-network-processors/src/main/java/org/apache/nifi/processors/network/pcap/SplitPCAP.java: ########## @@ -0,0 +1,209 @@ +/* + * 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 + * + * http://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.nifi.processors.network.pcap; + +import org.apache.nifi.components.PropertyDescriptor; +import org.apache.nifi.flowfile.FlowFile; +import org.apache.nifi.annotation.behavior.InputRequirement; +import org.apache.nifi.annotation.behavior.InputRequirement.Requirement; +import org.apache.nifi.annotation.behavior.SideEffectFree; +import org.apache.nifi.annotation.behavior.WritesAttribute; +import org.apache.nifi.annotation.behavior.WritesAttributes; +import org.apache.nifi.annotation.documentation.CapabilityDescription; +import org.apache.nifi.annotation.documentation.Tags; +import org.apache.nifi.processor.AbstractProcessor; +import org.apache.nifi.processor.ProcessContext; +import org.apache.nifi.processor.ProcessSession; +import org.apache.nifi.processor.Relationship; +import org.apache.nifi.processor.util.StandardValidators; +import org.apache.nifi.flowfile.attributes.FragmentAttributes; +import org.apache.nifi.flowfile.attributes.CoreAttributes; +import org.apache.nifi.processors.network.pcap.PCAP.ByteBufferInterface; +import org.apache.nifi.processors.network.pcap.PCAP.Packet; + +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.IntStream; + +@SideEffectFree +@InputRequirement(Requirement.INPUT_REQUIRED) +@Tags({"PCAP", "Splitter", "Network", "Packet", "Capture", "Wireshark", "TShark"}) +@CapabilityDescription("Splits a pcap file into multiple pcap files based on a maximum size.") +@WritesAttributes({ + @WritesAttribute(attribute = SplitPCAP.ERROR_REASON, description = "The reason the flowfile was sent to the failure relationship."), + @WritesAttribute(attribute = "fragment.identifier", description = "All split FlowFiles produced from the same parent FlowFile will have the same randomly generated UUID added for this attribute"), + @WritesAttribute(attribute = "fragment.index", description = "A one-up number that indicates the ordering of the split FlowFiles that were created from a single parent FlowFile"), + @WritesAttribute(attribute = "fragment.count", description = "The number of split FlowFiles generated from the parent FlowFile"), + @WritesAttribute(attribute = "segment.original.filename ", description = "The filename of the parent FlowFile") +}) + +public class SplitPCAP extends AbstractProcessor { + + protected static final String ERROR_REASON = "ERROR_REASON"; + public static final String FRAGMENT_ID = FragmentAttributes.FRAGMENT_ID.key(); + public static final String FRAGMENT_INDEX = FragmentAttributes.FRAGMENT_INDEX.key(); + public static final String FRAGMENT_COUNT = FragmentAttributes.FRAGMENT_COUNT.key(); + public static final String SEGMENT_ORIGINAL_FILENAME = FragmentAttributes.SEGMENT_ORIGINAL_FILENAME.key(); + + public static final PropertyDescriptor PCAP_MAX_SIZE = new PropertyDescriptor + .Builder().name("PCAP_MAX_SIZE") + .displayName("PCAP max size (bytes)") + .description("Maximum size of the output pcap file in bytes.") + .required(true) + .addValidator(StandardValidators.POSITIVE_INTEGER_VALIDATOR) + .build(); + + public static final Relationship REL_ORIGINAL = new Relationship.Builder() + .name("original") + .description("The original FlowFile that was split into segments. If the FlowFile fails processing, nothing will be sent to " + + "this relationship") + .build(); + public static final Relationship REL_FAILURE = new Relationship.Builder() + .name("failure") + .description("If a FlowFile cannot be transformed from the configured input format to the configured output format, " + + "the unchanged FlowFile will be routed to this relationship.") + .build(); + public static final Relationship REL_SPLIT = new Relationship.Builder() + .name("split") + .description("The individual 'segments' of the original FlowFile will be routed to this relationship.") + .build(); + + private static final List<PropertyDescriptor> DESCRIPTORS = List.of(PCAP_MAX_SIZE); + + private static final Set<Relationship> RELATIONSHIPS = Set.of(REL_ORIGINAL, REL_FAILURE, REL_SPLIT); Review Comment: ```suggestion private static final int PCAP_HEADER_LENGTH = 24; private static final int PACKET_HEADER_LENGTH = 16; private static final List<PropertyDescriptor> DESCRIPTORS = List.of(PCAP_MAX_SIZE); private static final Set<Relationship> RELATIONSHIPS = Set.of(REL_ORIGINAL, REL_FAILURE, REL_SPLIT); ``` ########## nifi-extension-bundles/nifi-network-bundle/nifi-network-processors/src/main/java/org/apache/nifi/processors/network/pcap/SplitPCAP.java: ########## @@ -0,0 +1,209 @@ +/* + * 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 + * + * http://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.nifi.processors.network.pcap; + +import org.apache.nifi.components.PropertyDescriptor; +import org.apache.nifi.flowfile.FlowFile; +import org.apache.nifi.annotation.behavior.InputRequirement; +import org.apache.nifi.annotation.behavior.InputRequirement.Requirement; +import org.apache.nifi.annotation.behavior.SideEffectFree; +import org.apache.nifi.annotation.behavior.WritesAttribute; +import org.apache.nifi.annotation.behavior.WritesAttributes; +import org.apache.nifi.annotation.documentation.CapabilityDescription; +import org.apache.nifi.annotation.documentation.Tags; +import org.apache.nifi.processor.AbstractProcessor; +import org.apache.nifi.processor.ProcessContext; +import org.apache.nifi.processor.ProcessSession; +import org.apache.nifi.processor.Relationship; +import org.apache.nifi.processor.util.StandardValidators; +import org.apache.nifi.flowfile.attributes.FragmentAttributes; +import org.apache.nifi.flowfile.attributes.CoreAttributes; +import org.apache.nifi.processors.network.pcap.PCAP.ByteBufferInterface; +import org.apache.nifi.processors.network.pcap.PCAP.Packet; + +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.IntStream; + +@SideEffectFree +@InputRequirement(Requirement.INPUT_REQUIRED) +@Tags({"PCAP", "Splitter", "Network", "Packet", "Capture", "Wireshark", "TShark"}) +@CapabilityDescription("Splits a pcap file into multiple pcap files based on a maximum size.") +@WritesAttributes({ + @WritesAttribute(attribute = SplitPCAP.ERROR_REASON, description = "The reason the flowfile was sent to the failure relationship."), + @WritesAttribute(attribute = "fragment.identifier", description = "All split FlowFiles produced from the same parent FlowFile will have the same randomly generated UUID added for this attribute"), + @WritesAttribute(attribute = "fragment.index", description = "A one-up number that indicates the ordering of the split FlowFiles that were created from a single parent FlowFile"), + @WritesAttribute(attribute = "fragment.count", description = "The number of split FlowFiles generated from the parent FlowFile"), + @WritesAttribute(attribute = "segment.original.filename ", description = "The filename of the parent FlowFile") +}) + +public class SplitPCAP extends AbstractProcessor { + + protected static final String ERROR_REASON = "ERROR_REASON"; + public static final String FRAGMENT_ID = FragmentAttributes.FRAGMENT_ID.key(); + public static final String FRAGMENT_INDEX = FragmentAttributes.FRAGMENT_INDEX.key(); + public static final String FRAGMENT_COUNT = FragmentAttributes.FRAGMENT_COUNT.key(); + public static final String SEGMENT_ORIGINAL_FILENAME = FragmentAttributes.SEGMENT_ORIGINAL_FILENAME.key(); + + public static final PropertyDescriptor PCAP_MAX_SIZE = new PropertyDescriptor + .Builder().name("PCAP_MAX_SIZE") + .displayName("PCAP max size (bytes)") Review Comment: I believe the suggested standard is to have `displayName` and `name` be the same and use upper case for individual words (This was concurred in the following [PR](https://github.com/apache/nifi/pull/8839#discussion_r1605378398)). `(bytes) ` is not necessary to include in the `displayName` as its detailed in the `description`. ```suggestion .Builder().name("PCAP Max Size") .displayName("PCAP Max Size") ``` ########## nifi-extension-bundles/nifi-network-bundle/nifi-network-processors/src/main/java/org/apache/nifi/processors/network/pcap/SplitPCAP.java: ########## @@ -0,0 +1,209 @@ +/* + * 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 + * + * http://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.nifi.processors.network.pcap; + +import org.apache.nifi.components.PropertyDescriptor; +import org.apache.nifi.flowfile.FlowFile; +import org.apache.nifi.annotation.behavior.InputRequirement; +import org.apache.nifi.annotation.behavior.InputRequirement.Requirement; +import org.apache.nifi.annotation.behavior.SideEffectFree; +import org.apache.nifi.annotation.behavior.WritesAttribute; +import org.apache.nifi.annotation.behavior.WritesAttributes; +import org.apache.nifi.annotation.documentation.CapabilityDescription; +import org.apache.nifi.annotation.documentation.Tags; +import org.apache.nifi.processor.AbstractProcessor; +import org.apache.nifi.processor.ProcessContext; +import org.apache.nifi.processor.ProcessSession; +import org.apache.nifi.processor.Relationship; +import org.apache.nifi.processor.util.StandardValidators; +import org.apache.nifi.flowfile.attributes.FragmentAttributes; +import org.apache.nifi.flowfile.attributes.CoreAttributes; +import org.apache.nifi.processors.network.pcap.PCAP.ByteBufferInterface; +import org.apache.nifi.processors.network.pcap.PCAP.Packet; + +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.IntStream; + +@SideEffectFree +@InputRequirement(Requirement.INPUT_REQUIRED) +@Tags({"PCAP", "Splitter", "Network", "Packet", "Capture", "Wireshark", "TShark"}) +@CapabilityDescription("Splits a pcap file into multiple pcap files based on a maximum size.") +@WritesAttributes({ + @WritesAttribute(attribute = SplitPCAP.ERROR_REASON, description = "The reason the flowfile was sent to the failure relationship."), + @WritesAttribute(attribute = "fragment.identifier", description = "All split FlowFiles produced from the same parent FlowFile will have the same randomly generated UUID added for this attribute"), + @WritesAttribute(attribute = "fragment.index", description = "A one-up number that indicates the ordering of the split FlowFiles that were created from a single parent FlowFile"), + @WritesAttribute(attribute = "fragment.count", description = "The number of split FlowFiles generated from the parent FlowFile"), + @WritesAttribute(attribute = "segment.original.filename ", description = "The filename of the parent FlowFile") +}) + +public class SplitPCAP extends AbstractProcessor { + + protected static final String ERROR_REASON = "ERROR_REASON"; + public static final String FRAGMENT_ID = FragmentAttributes.FRAGMENT_ID.key(); + public static final String FRAGMENT_INDEX = FragmentAttributes.FRAGMENT_INDEX.key(); + public static final String FRAGMENT_COUNT = FragmentAttributes.FRAGMENT_COUNT.key(); + public static final String SEGMENT_ORIGINAL_FILENAME = FragmentAttributes.SEGMENT_ORIGINAL_FILENAME.key(); + + public static final PropertyDescriptor PCAP_MAX_SIZE = new PropertyDescriptor + .Builder().name("PCAP_MAX_SIZE") + .displayName("PCAP max size (bytes)") + .description("Maximum size of the output pcap file in bytes.") + .required(true) + .addValidator(StandardValidators.POSITIVE_INTEGER_VALIDATOR) + .build(); + + public static final Relationship REL_ORIGINAL = new Relationship.Builder() + .name("original") + .description("The original FlowFile that was split into segments. If the FlowFile fails processing, nothing will be sent to " + + "this relationship") + .build(); + public static final Relationship REL_FAILURE = new Relationship.Builder() + .name("failure") + .description("If a FlowFile cannot be transformed from the configured input format to the configured output format, " + + "the unchanged FlowFile will be routed to this relationship.") + .build(); + public static final Relationship REL_SPLIT = new Relationship.Builder() + .name("split") + .description("The individual 'segments' of the original FlowFile will be routed to this relationship.") + .build(); + + private static final List<PropertyDescriptor> DESCRIPTORS = List.of(PCAP_MAX_SIZE); + + private static final Set<Relationship> RELATIONSHIPS = Set.of(REL_ORIGINAL, REL_FAILURE, REL_SPLIT); + + @Override + public Set<Relationship> getRelationships() { + return RELATIONSHIPS; + } + + @Override + public final List<PropertyDescriptor> getSupportedPropertyDescriptors() { + return DESCRIPTORS; + } + + /** + * This method is called when a trigger event occurs in the processor. + * It processes the incoming flow file, splits it into smaller pcap files based on the maximum size, + * and transfers the split pcap files to the success relationship. + * If the flow file is empty or not parseable, it is transferred to the failure relationship. + * + * @param context the process context + * @param session the process session + */ + @Override + public void onTrigger(final ProcessContext context, final ProcessSession session) { + FlowFile flowFile = session.get(); + if (flowFile == null) { + return; + } + + int pcapMaxSize = context.getProperty(PCAP_MAX_SIZE.getName()).asInteger(); + + final ByteArrayOutputStream contentBytes = new ByteArrayOutputStream(); + session.exportTo(flowFile, contentBytes); + final byte[] contentByteArray = contentBytes.toByteArray(); + + if (contentByteArray.length == 0) { + session.putAttribute(flowFile, ERROR_REASON, "PCAP file empty."); + session.transfer(flowFile, REL_FAILURE); + return; + } + + final PCAP parsedPcap; + final PCAP templatePcap; + + // Parse the pcap file and create a template pcap object to borrow the header from. + try { + parsedPcap = new PCAP(new ByteBufferInterface(contentByteArray)); + + // Recreating rather than using deepcopy as recreating is more efficient in this case. Review Comment: ```suggestion // Recreating rather than using deep copy as recreating is more efficient in this case. ``` ########## nifi-extension-bundles/nifi-network-bundle/nifi-network-processors/src/test/java/org/apache/nifi/processors/network/pcap/TestSplitPCAP.java: ########## @@ -0,0 +1,161 @@ +/* + * 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 + * + * http://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.nifi.processors.network; + +import java.io.IOException; +import java.util.ArrayList; + +import org.apache.nifi.util.TestRunner; +import org.apache.nifi.util.TestRunners; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.apache.nifi.processors.network.pcap.SplitPCAP; +import org.apache.nifi.processors.network.pcap.PCAP; +import org.apache.nifi.processors.network.pcap.PCAP.Header; +import org.apache.nifi.processors.network.pcap.PCAP.Packet; Review Comment: Per earlier comment the imports must be changed ```suggestion import org.apache.nifi.processors.network.pcap.Header; import org.apache.nifi.processors.network.pcap.Packet; ``` ########## nifi-extension-bundles/nifi-network-bundle/nifi-network-processors/src/main/java/org/apache/nifi/processors/network/pcap/SplitPCAP.java: ########## @@ -0,0 +1,209 @@ +/* + * 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 + * + * http://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.nifi.processors.network.pcap; + +import org.apache.nifi.components.PropertyDescriptor; +import org.apache.nifi.flowfile.FlowFile; +import org.apache.nifi.annotation.behavior.InputRequirement; +import org.apache.nifi.annotation.behavior.InputRequirement.Requirement; +import org.apache.nifi.annotation.behavior.SideEffectFree; +import org.apache.nifi.annotation.behavior.WritesAttribute; +import org.apache.nifi.annotation.behavior.WritesAttributes; +import org.apache.nifi.annotation.documentation.CapabilityDescription; +import org.apache.nifi.annotation.documentation.Tags; +import org.apache.nifi.processor.AbstractProcessor; +import org.apache.nifi.processor.ProcessContext; +import org.apache.nifi.processor.ProcessSession; +import org.apache.nifi.processor.Relationship; +import org.apache.nifi.processor.util.StandardValidators; +import org.apache.nifi.flowfile.attributes.FragmentAttributes; +import org.apache.nifi.flowfile.attributes.CoreAttributes; +import org.apache.nifi.processors.network.pcap.PCAP.ByteBufferInterface; +import org.apache.nifi.processors.network.pcap.PCAP.Packet; + +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.IntStream; + +@SideEffectFree +@InputRequirement(Requirement.INPUT_REQUIRED) +@Tags({"PCAP", "Splitter", "Network", "Packet", "Capture", "Wireshark", "TShark"}) +@CapabilityDescription("Splits a pcap file into multiple pcap files based on a maximum size.") +@WritesAttributes({ + @WritesAttribute(attribute = SplitPCAP.ERROR_REASON, description = "The reason the flowfile was sent to the failure relationship."), + @WritesAttribute(attribute = "fragment.identifier", description = "All split FlowFiles produced from the same parent FlowFile will have the same randomly generated UUID added for this attribute"), + @WritesAttribute(attribute = "fragment.index", description = "A one-up number that indicates the ordering of the split FlowFiles that were created from a single parent FlowFile"), + @WritesAttribute(attribute = "fragment.count", description = "The number of split FlowFiles generated from the parent FlowFile"), + @WritesAttribute(attribute = "segment.original.filename ", description = "The filename of the parent FlowFile") +}) + +public class SplitPCAP extends AbstractProcessor { + + protected static final String ERROR_REASON = "ERROR_REASON"; + public static final String FRAGMENT_ID = FragmentAttributes.FRAGMENT_ID.key(); + public static final String FRAGMENT_INDEX = FragmentAttributes.FRAGMENT_INDEX.key(); + public static final String FRAGMENT_COUNT = FragmentAttributes.FRAGMENT_COUNT.key(); + public static final String SEGMENT_ORIGINAL_FILENAME = FragmentAttributes.SEGMENT_ORIGINAL_FILENAME.key(); + + public static final PropertyDescriptor PCAP_MAX_SIZE = new PropertyDescriptor + .Builder().name("PCAP_MAX_SIZE") + .displayName("PCAP max size (bytes)") + .description("Maximum size of the output pcap file in bytes.") + .required(true) + .addValidator(StandardValidators.POSITIVE_INTEGER_VALIDATOR) + .build(); + + public static final Relationship REL_ORIGINAL = new Relationship.Builder() + .name("original") + .description("The original FlowFile that was split into segments. If the FlowFile fails processing, nothing will be sent to " + + "this relationship") + .build(); + public static final Relationship REL_FAILURE = new Relationship.Builder() + .name("failure") + .description("If a FlowFile cannot be transformed from the configured input format to the configured output format, " + + "the unchanged FlowFile will be routed to this relationship.") + .build(); + public static final Relationship REL_SPLIT = new Relationship.Builder() + .name("split") + .description("The individual 'segments' of the original FlowFile will be routed to this relationship.") + .build(); + + private static final List<PropertyDescriptor> DESCRIPTORS = List.of(PCAP_MAX_SIZE); + + private static final Set<Relationship> RELATIONSHIPS = Set.of(REL_ORIGINAL, REL_FAILURE, REL_SPLIT); + + @Override + public Set<Relationship> getRelationships() { + return RELATIONSHIPS; + } + + @Override + public final List<PropertyDescriptor> getSupportedPropertyDescriptors() { + return DESCRIPTORS; + } + + /** + * This method is called when a trigger event occurs in the processor. + * It processes the incoming flow file, splits it into smaller pcap files based on the maximum size, + * and transfers the split pcap files to the success relationship. + * If the flow file is empty or not parseable, it is transferred to the failure relationship. + * + * @param context the process context + * @param session the process session + */ + @Override + public void onTrigger(final ProcessContext context, final ProcessSession session) { + FlowFile flowFile = session.get(); + if (flowFile == null) { + return; + } + + int pcapMaxSize = context.getProperty(PCAP_MAX_SIZE.getName()).asInteger(); + + final ByteArrayOutputStream contentBytes = new ByteArrayOutputStream(); + session.exportTo(flowFile, contentBytes); + final byte[] contentByteArray = contentBytes.toByteArray(); + + if (contentByteArray.length == 0) { + session.putAttribute(flowFile, ERROR_REASON, "PCAP file empty."); + session.transfer(flowFile, REL_FAILURE); + return; + } + + final PCAP parsedPcap; + final PCAP templatePcap; + + // Parse the pcap file and create a template pcap object to borrow the header from. + try { + parsedPcap = new PCAP(new ByteBufferInterface(contentByteArray)); + + // Recreating rather than using deepcopy as recreating is more efficient in this case. + templatePcap = new PCAP(new ByteBufferInterface(contentByteArray)); + + } catch (Exception e) { + session.putAttribute(flowFile, ERROR_REASON, "PCAP file not parseable."); + session.transfer(flowFile, REL_FAILURE); + return; + } + + final List<Packet> unprocessedPackets = parsedPcap.packets(); + final int pcapHeaderLength = 24; + final int packetHeaderLength = 16; + + int currentPacketCollectionSize = pcapHeaderLength; + List<FlowFile> splitFilesList = new ArrayList<>(); + + List<Packet> newPackets = new ArrayList<>(); + templatePcap.packets().clear(); + + // Loop through all packets in the pcap file and split them into smaller pcap files. + while (!unprocessedPackets.isEmpty()) { + Packet packet = unprocessedPackets.getFirst(); + + if (packet.inclLen() > pcapMaxSize) { + session.putAttribute(flowFile, ERROR_REASON, "PCAP contains a packet larger than the max size."); + session.transfer(flowFile, REL_FAILURE); + return; + } + + if (currentPacketCollectionSize + (packet.inclLen() + packetHeaderLength) > pcapMaxSize && currentPacketCollectionSize > 0) { + templatePcap.packets().addAll(newPackets); + var newFlowFile = session.create(flowFile); + session.write(newFlowFile, out -> out.write(templatePcap.readBytesFull())); + splitFilesList.add(newFlowFile); + + newPackets = new ArrayList<>(); + currentPacketCollectionSize = pcapHeaderLength; + templatePcap.packets().clear(); + } else { + newPackets.add(packet); + currentPacketCollectionSize += ((int) packet.inclLen() + packetHeaderLength); Review Comment: ```suggestion currentPacketCollectionSize += ((int) packet.inclLen() + PACKET_HEADER_LENGTH); ``` ########## nifi-extension-bundles/nifi-network-bundle/nifi-network-processors/src/main/java/org/apache/nifi/processors/network/pcap/SplitPCAP.java: ########## @@ -0,0 +1,209 @@ +/* + * 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 + * + * http://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.nifi.processors.network.pcap; + +import org.apache.nifi.components.PropertyDescriptor; +import org.apache.nifi.flowfile.FlowFile; +import org.apache.nifi.annotation.behavior.InputRequirement; +import org.apache.nifi.annotation.behavior.InputRequirement.Requirement; +import org.apache.nifi.annotation.behavior.SideEffectFree; +import org.apache.nifi.annotation.behavior.WritesAttribute; +import org.apache.nifi.annotation.behavior.WritesAttributes; +import org.apache.nifi.annotation.documentation.CapabilityDescription; +import org.apache.nifi.annotation.documentation.Tags; +import org.apache.nifi.processor.AbstractProcessor; +import org.apache.nifi.processor.ProcessContext; +import org.apache.nifi.processor.ProcessSession; +import org.apache.nifi.processor.Relationship; +import org.apache.nifi.processor.util.StandardValidators; +import org.apache.nifi.flowfile.attributes.FragmentAttributes; +import org.apache.nifi.flowfile.attributes.CoreAttributes; +import org.apache.nifi.processors.network.pcap.PCAP.ByteBufferInterface; +import org.apache.nifi.processors.network.pcap.PCAP.Packet; + +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.IntStream; + +@SideEffectFree +@InputRequirement(Requirement.INPUT_REQUIRED) +@Tags({"PCAP", "Splitter", "Network", "Packet", "Capture", "Wireshark", "TShark"}) Review Comment: Does it make sense to add TcpDump and WinDump as they are producers of PCAP like Wireshark and sniffers as that seems to be a keyword as seen in the javadoc on PCAP. ```suggestion @Tags({"PCAP", "Splitter", "Network", "Packet", "Capture", "Wireshark", "TShark", "TcpDump", "WinDump", "sniffers"}) ``` ########## nifi-extension-bundles/nifi-network-bundle/nifi-network-processors/src/test/java/org/apache/nifi/processors/network/pcap/TestPCAP.java: ########## @@ -0,0 +1,94 @@ +/* + * 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 + * + * http://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.nifi.processors.network.pcap; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.ArrayList; + +import org.apache.nifi.processors.network.pcap.PCAP.Packet; +import org.apache.nifi.processors.network.pcap.PCAP.Header; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestPCAP { + @Test + public void testReadBytesFull() { + + // Create a header for the test PCAP + Header hdr = new Header( + new byte[]{(byte) 0xa1, (byte) 0xb2, (byte) 0xc3, (byte) 0xd4}, + 2, + 4, + 0, + (long) 0, + (long) 40, + (long) 1 // ETHERNET + ); + + // Create a sample packet + ArrayList<Packet> packets = new ArrayList<>(); Review Comment: ```suggestion List<Packet> packets = new ArrayList<>(); ``` ########## nifi-extension-bundles/nifi-network-bundle/nifi-network-processors/src/test/java/org/apache/nifi/processors/network/pcap/TestSplitPCAP.java: ########## @@ -0,0 +1,161 @@ +/* + * 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 + * + * http://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.nifi.processors.network; + +import java.io.IOException; +import java.util.ArrayList; + +import org.apache.nifi.util.TestRunner; +import org.apache.nifi.util.TestRunners; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.apache.nifi.processors.network.pcap.SplitPCAP; +import org.apache.nifi.processors.network.pcap.PCAP; +import org.apache.nifi.processors.network.pcap.PCAP.Header; +import org.apache.nifi.processors.network.pcap.PCAP.Packet; + + +public class TestSplitPCAP { + + private Header hdr; + private Packet validPacket; + private Packet invalidPacket; + + @BeforeEach + public void init() { + // Create a header for the test PCAP + this.hdr = new Header( + new byte[]{(byte) 0xa1, (byte) 0xb2, (byte) 0xc3, (byte) 0xd4}, + 2, + 4, + 0, + (long) 0, + (long) 40, + (long) 1 // ETHERNET + ); + + this.validPacket = new Packet( + (long) 1713184965, + (long) 1000, + (long) 30, + (long) 30, + new byte[]{ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, + 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, + } + ); + + this.invalidPacket = new Packet( + (long) 1713184965, + (long) 1000, + (long) 10, + (long) 10, + new byte[]{ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, + 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, + } + ); + + } + + @Test + public void testValidPackets() throws IOException { + TestRunner runner = TestRunners.newTestRunner(SplitPCAP.class); + runner.setProperty(SplitPCAP.PCAP_MAX_SIZE, "100"); + + ArrayList<Packet> packets = new ArrayList<>(); + for (var loop = 0; loop < 3; loop++) { + packets.add(this.validPacket); + } + + PCAP testPcap = new PCAP(this.hdr, packets); + + runner.enqueue(testPcap.readBytesFull()); + + runner.run(); + + runner.assertTransferCount(SplitPCAP.REL_SPLIT, 3); + runner.assertTransferCount(SplitPCAP.REL_ORIGINAL, 1); + runner.assertQueueEmpty(); + } + + @Test + public void testInvalidPackets() throws IOException { + TestRunner runner = TestRunners.newTestRunner(SplitPCAP.class); + runner.setProperty(SplitPCAP.PCAP_MAX_SIZE, "50"); + + ArrayList<Packet> packets = new ArrayList<>(); + for (var loop = 0; loop < 3; loop++) { + packets.add(this.invalidPacket); + } + + PCAP testPcap = new PCAP(this.hdr, packets); + + runner.enqueue(testPcap.readBytesFull()); + + runner.run(); + + runner.assertAllFlowFilesTransferred(SplitPCAP.REL_FAILURE, 1); + runner.assertQueueEmpty(); + } + + @Test + public void testPacketsTooBig() throws IOException { + TestRunner runner = TestRunners.newTestRunner(SplitPCAP.class); + runner.setProperty(SplitPCAP.PCAP_MAX_SIZE, "10"); + + ArrayList<Packet> packets = new ArrayList<>(); Review Comment: ```suggestion List<Packet> packets = new ArrayList<>(); ``` ########## nifi-extension-bundles/nifi-network-bundle/nifi-network-processors/src/test/java/org/apache/nifi/processors/network/pcap/TestSplitPCAP.java: ########## @@ -0,0 +1,161 @@ +/* + * 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 + * + * http://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.nifi.processors.network; + +import java.io.IOException; +import java.util.ArrayList; + +import org.apache.nifi.util.TestRunner; +import org.apache.nifi.util.TestRunners; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.apache.nifi.processors.network.pcap.SplitPCAP; +import org.apache.nifi.processors.network.pcap.PCAP; +import org.apache.nifi.processors.network.pcap.PCAP.Header; +import org.apache.nifi.processors.network.pcap.PCAP.Packet; + + +public class TestSplitPCAP { + + private Header hdr; + private Packet validPacket; + private Packet invalidPacket; + + @BeforeEach + public void init() { + // Create a header for the test PCAP + this.hdr = new Header( + new byte[]{(byte) 0xa1, (byte) 0xb2, (byte) 0xc3, (byte) 0xd4}, + 2, + 4, + 0, + (long) 0, + (long) 40, + (long) 1 // ETHERNET + ); + + this.validPacket = new Packet( + (long) 1713184965, + (long) 1000, + (long) 30, + (long) 30, + new byte[]{ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, + 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, + } + ); + + this.invalidPacket = new Packet( + (long) 1713184965, + (long) 1000, + (long) 10, + (long) 10, + new byte[]{ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, + 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, + } + ); + + } + + @Test + public void testValidPackets() throws IOException { + TestRunner runner = TestRunners.newTestRunner(SplitPCAP.class); + runner.setProperty(SplitPCAP.PCAP_MAX_SIZE, "100"); + + ArrayList<Packet> packets = new ArrayList<>(); + for (var loop = 0; loop < 3; loop++) { + packets.add(this.validPacket); + } + + PCAP testPcap = new PCAP(this.hdr, packets); + + runner.enqueue(testPcap.readBytesFull()); + + runner.run(); + + runner.assertTransferCount(SplitPCAP.REL_SPLIT, 3); + runner.assertTransferCount(SplitPCAP.REL_ORIGINAL, 1); + runner.assertQueueEmpty(); + } + + @Test + public void testInvalidPackets() throws IOException { + TestRunner runner = TestRunners.newTestRunner(SplitPCAP.class); + runner.setProperty(SplitPCAP.PCAP_MAX_SIZE, "50"); + + ArrayList<Packet> packets = new ArrayList<>(); Review Comment: ```suggestion List<Packet> packets = new ArrayList<>(); ``` ########## nifi-extension-bundles/nifi-network-bundle/nifi-network-processors/src/test/java/org/apache/nifi/processors/network/pcap/TestSplitPCAP.java: ########## @@ -0,0 +1,161 @@ +/* + * 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 + * + * http://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.nifi.processors.network; + +import java.io.IOException; +import java.util.ArrayList; + +import org.apache.nifi.util.TestRunner; +import org.apache.nifi.util.TestRunners; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.apache.nifi.processors.network.pcap.SplitPCAP; +import org.apache.nifi.processors.network.pcap.PCAP; +import org.apache.nifi.processors.network.pcap.PCAP.Header; +import org.apache.nifi.processors.network.pcap.PCAP.Packet; + + +public class TestSplitPCAP { + + private Header hdr; + private Packet validPacket; + private Packet invalidPacket; + + @BeforeEach + public void init() { + // Create a header for the test PCAP + this.hdr = new Header( + new byte[]{(byte) 0xa1, (byte) 0xb2, (byte) 0xc3, (byte) 0xd4}, + 2, + 4, + 0, + (long) 0, + (long) 40, + (long) 1 // ETHERNET + ); + + this.validPacket = new Packet( + (long) 1713184965, + (long) 1000, + (long) 30, + (long) 30, + new byte[]{ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, + 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, + } + ); + + this.invalidPacket = new Packet( + (long) 1713184965, + (long) 1000, + (long) 10, + (long) 10, + new byte[]{ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, + 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, + } + ); + + } + + @Test + public void testValidPackets() throws IOException { + TestRunner runner = TestRunners.newTestRunner(SplitPCAP.class); + runner.setProperty(SplitPCAP.PCAP_MAX_SIZE, "100"); + + ArrayList<Packet> packets = new ArrayList<>(); Review Comment: ```suggestion List<Packet> packets = new ArrayList<>(); ``` ########## nifi-extension-bundles/nifi-network-bundle/nifi-network-processors/src/main/java/org/apache/nifi/processors/network/pcap/SplitPCAP.java: ########## @@ -0,0 +1,209 @@ +/* + * 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 + * + * http://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.nifi.processors.network.pcap; + +import org.apache.nifi.components.PropertyDescriptor; +import org.apache.nifi.flowfile.FlowFile; +import org.apache.nifi.annotation.behavior.InputRequirement; +import org.apache.nifi.annotation.behavior.InputRequirement.Requirement; +import org.apache.nifi.annotation.behavior.SideEffectFree; +import org.apache.nifi.annotation.behavior.WritesAttribute; +import org.apache.nifi.annotation.behavior.WritesAttributes; +import org.apache.nifi.annotation.documentation.CapabilityDescription; +import org.apache.nifi.annotation.documentation.Tags; +import org.apache.nifi.processor.AbstractProcessor; +import org.apache.nifi.processor.ProcessContext; +import org.apache.nifi.processor.ProcessSession; +import org.apache.nifi.processor.Relationship; +import org.apache.nifi.processor.util.StandardValidators; +import org.apache.nifi.flowfile.attributes.FragmentAttributes; +import org.apache.nifi.flowfile.attributes.CoreAttributes; +import org.apache.nifi.processors.network.pcap.PCAP.ByteBufferInterface; +import org.apache.nifi.processors.network.pcap.PCAP.Packet; + +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.IntStream; + +@SideEffectFree +@InputRequirement(Requirement.INPUT_REQUIRED) +@Tags({"PCAP", "Splitter", "Network", "Packet", "Capture", "Wireshark", "TShark"}) +@CapabilityDescription("Splits a pcap file into multiple pcap files based on a maximum size.") +@WritesAttributes({ + @WritesAttribute(attribute = SplitPCAP.ERROR_REASON, description = "The reason the flowfile was sent to the failure relationship."), + @WritesAttribute(attribute = "fragment.identifier", description = "All split FlowFiles produced from the same parent FlowFile will have the same randomly generated UUID added for this attribute"), + @WritesAttribute(attribute = "fragment.index", description = "A one-up number that indicates the ordering of the split FlowFiles that were created from a single parent FlowFile"), + @WritesAttribute(attribute = "fragment.count", description = "The number of split FlowFiles generated from the parent FlowFile"), + @WritesAttribute(attribute = "segment.original.filename ", description = "The filename of the parent FlowFile") +}) + +public class SplitPCAP extends AbstractProcessor { + + protected static final String ERROR_REASON = "ERROR_REASON"; + public static final String FRAGMENT_ID = FragmentAttributes.FRAGMENT_ID.key(); + public static final String FRAGMENT_INDEX = FragmentAttributes.FRAGMENT_INDEX.key(); + public static final String FRAGMENT_COUNT = FragmentAttributes.FRAGMENT_COUNT.key(); + public static final String SEGMENT_ORIGINAL_FILENAME = FragmentAttributes.SEGMENT_ORIGINAL_FILENAME.key(); + + public static final PropertyDescriptor PCAP_MAX_SIZE = new PropertyDescriptor + .Builder().name("PCAP_MAX_SIZE") + .displayName("PCAP max size (bytes)") + .description("Maximum size of the output pcap file in bytes.") + .required(true) + .addValidator(StandardValidators.POSITIVE_INTEGER_VALIDATOR) + .build(); + + public static final Relationship REL_ORIGINAL = new Relationship.Builder() + .name("original") + .description("The original FlowFile that was split into segments. If the FlowFile fails processing, nothing will be sent to " + + "this relationship") + .build(); + public static final Relationship REL_FAILURE = new Relationship.Builder() + .name("failure") + .description("If a FlowFile cannot be transformed from the configured input format to the configured output format, " + + "the unchanged FlowFile will be routed to this relationship.") + .build(); + public static final Relationship REL_SPLIT = new Relationship.Builder() + .name("split") + .description("The individual 'segments' of the original FlowFile will be routed to this relationship.") + .build(); + + private static final List<PropertyDescriptor> DESCRIPTORS = List.of(PCAP_MAX_SIZE); + + private static final Set<Relationship> RELATIONSHIPS = Set.of(REL_ORIGINAL, REL_FAILURE, REL_SPLIT); + + @Override + public Set<Relationship> getRelationships() { + return RELATIONSHIPS; + } + + @Override + public final List<PropertyDescriptor> getSupportedPropertyDescriptors() { + return DESCRIPTORS; + } + + /** + * This method is called when a trigger event occurs in the processor. + * It processes the incoming flow file, splits it into smaller pcap files based on the maximum size, + * and transfers the split pcap files to the success relationship. + * If the flow file is empty or not parseable, it is transferred to the failure relationship. + * + * @param context the process context + * @param session the process session + */ + @Override + public void onTrigger(final ProcessContext context, final ProcessSession session) { + FlowFile flowFile = session.get(); + if (flowFile == null) { + return; + } + + int pcapMaxSize = context.getProperty(PCAP_MAX_SIZE.getName()).asInteger(); + + final ByteArrayOutputStream contentBytes = new ByteArrayOutputStream(); + session.exportTo(flowFile, contentBytes); + final byte[] contentByteArray = contentBytes.toByteArray(); + + if (contentByteArray.length == 0) { + session.putAttribute(flowFile, ERROR_REASON, "PCAP file empty."); + session.transfer(flowFile, REL_FAILURE); + return; + } + + final PCAP parsedPcap; + final PCAP templatePcap; + + // Parse the pcap file and create a template pcap object to borrow the header from. + try { + parsedPcap = new PCAP(new ByteBufferInterface(contentByteArray)); + + // Recreating rather than using deepcopy as recreating is more efficient in this case. + templatePcap = new PCAP(new ByteBufferInterface(contentByteArray)); + + } catch (Exception e) { + session.putAttribute(flowFile, ERROR_REASON, "PCAP file not parseable."); + session.transfer(flowFile, REL_FAILURE); + return; + } + + final List<Packet> unprocessedPackets = parsedPcap.packets(); + final int pcapHeaderLength = 24; + final int packetHeaderLength = 16; + + int currentPacketCollectionSize = pcapHeaderLength; + List<FlowFile> splitFilesList = new ArrayList<>(); + + List<Packet> newPackets = new ArrayList<>(); + templatePcap.packets().clear(); + + // Loop through all packets in the pcap file and split them into smaller pcap files. + while (!unprocessedPackets.isEmpty()) { + Packet packet = unprocessedPackets.getFirst(); + + if (packet.inclLen() > pcapMaxSize) { + session.putAttribute(flowFile, ERROR_REASON, "PCAP contains a packet larger than the max size."); + session.transfer(flowFile, REL_FAILURE); + return; + } + + if (currentPacketCollectionSize + (packet.inclLen() + packetHeaderLength) > pcapMaxSize && currentPacketCollectionSize > 0) { Review Comment: ```suggestion if (currentPacketCollectionSize + (packet.inclLen() + PACKET_HEADER_LENGTH) > pcapMaxSize && currentPacketCollectionSize > 0) { ``` ########## nifi-extension-bundles/nifi-network-bundle/nifi-network-processors/src/main/java/org/apache/nifi/processors/network/pcap/SplitPCAP.java: ########## @@ -0,0 +1,209 @@ +/* + * 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 + * + * http://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.nifi.processors.network.pcap; + +import org.apache.nifi.components.PropertyDescriptor; +import org.apache.nifi.flowfile.FlowFile; +import org.apache.nifi.annotation.behavior.InputRequirement; +import org.apache.nifi.annotation.behavior.InputRequirement.Requirement; +import org.apache.nifi.annotation.behavior.SideEffectFree; +import org.apache.nifi.annotation.behavior.WritesAttribute; +import org.apache.nifi.annotation.behavior.WritesAttributes; +import org.apache.nifi.annotation.documentation.CapabilityDescription; +import org.apache.nifi.annotation.documentation.Tags; +import org.apache.nifi.processor.AbstractProcessor; +import org.apache.nifi.processor.ProcessContext; +import org.apache.nifi.processor.ProcessSession; +import org.apache.nifi.processor.Relationship; +import org.apache.nifi.processor.util.StandardValidators; +import org.apache.nifi.flowfile.attributes.FragmentAttributes; +import org.apache.nifi.flowfile.attributes.CoreAttributes; +import org.apache.nifi.processors.network.pcap.PCAP.ByteBufferInterface; +import org.apache.nifi.processors.network.pcap.PCAP.Packet; + +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.IntStream; + +@SideEffectFree +@InputRequirement(Requirement.INPUT_REQUIRED) +@Tags({"PCAP", "Splitter", "Network", "Packet", "Capture", "Wireshark", "TShark"}) +@CapabilityDescription("Splits a pcap file into multiple pcap files based on a maximum size.") +@WritesAttributes({ + @WritesAttribute(attribute = SplitPCAP.ERROR_REASON, description = "The reason the flowfile was sent to the failure relationship."), + @WritesAttribute(attribute = "fragment.identifier", description = "All split FlowFiles produced from the same parent FlowFile will have the same randomly generated UUID added for this attribute"), + @WritesAttribute(attribute = "fragment.index", description = "A one-up number that indicates the ordering of the split FlowFiles that were created from a single parent FlowFile"), + @WritesAttribute(attribute = "fragment.count", description = "The number of split FlowFiles generated from the parent FlowFile"), + @WritesAttribute(attribute = "segment.original.filename ", description = "The filename of the parent FlowFile") +}) + +public class SplitPCAP extends AbstractProcessor { + + protected static final String ERROR_REASON = "ERROR_REASON"; + public static final String FRAGMENT_ID = FragmentAttributes.FRAGMENT_ID.key(); + public static final String FRAGMENT_INDEX = FragmentAttributes.FRAGMENT_INDEX.key(); + public static final String FRAGMENT_COUNT = FragmentAttributes.FRAGMENT_COUNT.key(); + public static final String SEGMENT_ORIGINAL_FILENAME = FragmentAttributes.SEGMENT_ORIGINAL_FILENAME.key(); + + public static final PropertyDescriptor PCAP_MAX_SIZE = new PropertyDescriptor + .Builder().name("PCAP_MAX_SIZE") + .displayName("PCAP max size (bytes)") + .description("Maximum size of the output pcap file in bytes.") + .required(true) + .addValidator(StandardValidators.POSITIVE_INTEGER_VALIDATOR) + .build(); + + public static final Relationship REL_ORIGINAL = new Relationship.Builder() + .name("original") + .description("The original FlowFile that was split into segments. If the FlowFile fails processing, nothing will be sent to " + + "this relationship") + .build(); + public static final Relationship REL_FAILURE = new Relationship.Builder() + .name("failure") + .description("If a FlowFile cannot be transformed from the configured input format to the configured output format, " + + "the unchanged FlowFile will be routed to this relationship.") + .build(); + public static final Relationship REL_SPLIT = new Relationship.Builder() + .name("split") + .description("The individual 'segments' of the original FlowFile will be routed to this relationship.") Review Comment: ```suggestion .description("The individual PCAP 'segments' of the original PCAP FlowFile will be routed to this relationship.") ``` ########## nifi-extension-bundles/nifi-network-bundle/nifi-network-processors/src/main/java/org/apache/nifi/processors/network/pcap/SplitPCAP.java: ########## @@ -0,0 +1,209 @@ +/* + * 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 + * + * http://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.nifi.processors.network.pcap; + +import org.apache.nifi.components.PropertyDescriptor; +import org.apache.nifi.flowfile.FlowFile; +import org.apache.nifi.annotation.behavior.InputRequirement; +import org.apache.nifi.annotation.behavior.InputRequirement.Requirement; +import org.apache.nifi.annotation.behavior.SideEffectFree; +import org.apache.nifi.annotation.behavior.WritesAttribute; +import org.apache.nifi.annotation.behavior.WritesAttributes; +import org.apache.nifi.annotation.documentation.CapabilityDescription; +import org.apache.nifi.annotation.documentation.Tags; +import org.apache.nifi.processor.AbstractProcessor; +import org.apache.nifi.processor.ProcessContext; +import org.apache.nifi.processor.ProcessSession; +import org.apache.nifi.processor.Relationship; +import org.apache.nifi.processor.util.StandardValidators; +import org.apache.nifi.flowfile.attributes.FragmentAttributes; +import org.apache.nifi.flowfile.attributes.CoreAttributes; +import org.apache.nifi.processors.network.pcap.PCAP.ByteBufferInterface; +import org.apache.nifi.processors.network.pcap.PCAP.Packet; + +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.IntStream; + +@SideEffectFree +@InputRequirement(Requirement.INPUT_REQUIRED) +@Tags({"PCAP", "Splitter", "Network", "Packet", "Capture", "Wireshark", "TShark"}) +@CapabilityDescription("Splits a pcap file into multiple pcap files based on a maximum size.") +@WritesAttributes({ + @WritesAttribute(attribute = SplitPCAP.ERROR_REASON, description = "The reason the flowfile was sent to the failure relationship."), + @WritesAttribute(attribute = "fragment.identifier", description = "All split FlowFiles produced from the same parent FlowFile will have the same randomly generated UUID added for this attribute"), + @WritesAttribute(attribute = "fragment.index", description = "A one-up number that indicates the ordering of the split FlowFiles that were created from a single parent FlowFile"), + @WritesAttribute(attribute = "fragment.count", description = "The number of split FlowFiles generated from the parent FlowFile"), + @WritesAttribute(attribute = "segment.original.filename ", description = "The filename of the parent FlowFile") +}) + +public class SplitPCAP extends AbstractProcessor { + + protected static final String ERROR_REASON = "ERROR_REASON"; + public static final String FRAGMENT_ID = FragmentAttributes.FRAGMENT_ID.key(); + public static final String FRAGMENT_INDEX = FragmentAttributes.FRAGMENT_INDEX.key(); + public static final String FRAGMENT_COUNT = FragmentAttributes.FRAGMENT_COUNT.key(); + public static final String SEGMENT_ORIGINAL_FILENAME = FragmentAttributes.SEGMENT_ORIGINAL_FILENAME.key(); + + public static final PropertyDescriptor PCAP_MAX_SIZE = new PropertyDescriptor + .Builder().name("PCAP_MAX_SIZE") + .displayName("PCAP max size (bytes)") + .description("Maximum size of the output pcap file in bytes.") + .required(true) + .addValidator(StandardValidators.POSITIVE_INTEGER_VALIDATOR) + .build(); + + public static final Relationship REL_ORIGINAL = new Relationship.Builder() + .name("original") + .description("The original FlowFile that was split into segments. If the FlowFile fails processing, nothing will be sent to " + + "this relationship") + .build(); + public static final Relationship REL_FAILURE = new Relationship.Builder() + .name("failure") + .description("If a FlowFile cannot be transformed from the configured input format to the configured output format, " + + "the unchanged FlowFile will be routed to this relationship.") + .build(); + public static final Relationship REL_SPLIT = new Relationship.Builder() + .name("split") + .description("The individual 'segments' of the original FlowFile will be routed to this relationship.") + .build(); + + private static final List<PropertyDescriptor> DESCRIPTORS = List.of(PCAP_MAX_SIZE); + + private static final Set<Relationship> RELATIONSHIPS = Set.of(REL_ORIGINAL, REL_FAILURE, REL_SPLIT); + + @Override + public Set<Relationship> getRelationships() { + return RELATIONSHIPS; + } + + @Override + public final List<PropertyDescriptor> getSupportedPropertyDescriptors() { + return DESCRIPTORS; + } + + /** + * This method is called when a trigger event occurs in the processor. + * It processes the incoming flow file, splits it into smaller pcap files based on the maximum size, + * and transfers the split pcap files to the success relationship. + * If the flow file is empty or not parseable, it is transferred to the failure relationship. + * + * @param context the process context + * @param session the process session + */ + @Override + public void onTrigger(final ProcessContext context, final ProcessSession session) { + FlowFile flowFile = session.get(); + if (flowFile == null) { + return; + } + + int pcapMaxSize = context.getProperty(PCAP_MAX_SIZE.getName()).asInteger(); + + final ByteArrayOutputStream contentBytes = new ByteArrayOutputStream(); + session.exportTo(flowFile, contentBytes); + final byte[] contentByteArray = contentBytes.toByteArray(); + + if (contentByteArray.length == 0) { + session.putAttribute(flowFile, ERROR_REASON, "PCAP file empty."); + session.transfer(flowFile, REL_FAILURE); + return; + } + + final PCAP parsedPcap; + final PCAP templatePcap; + + // Parse the pcap file and create a template pcap object to borrow the header from. + try { + parsedPcap = new PCAP(new ByteBufferInterface(contentByteArray)); + + // Recreating rather than using deepcopy as recreating is more efficient in this case. + templatePcap = new PCAP(new ByteBufferInterface(contentByteArray)); + + } catch (Exception e) { + session.putAttribute(flowFile, ERROR_REASON, "PCAP file not parseable."); + session.transfer(flowFile, REL_FAILURE); + return; + } + + final List<Packet> unprocessedPackets = parsedPcap.packets(); + final int pcapHeaderLength = 24; + final int packetHeaderLength = 16; + + int currentPacketCollectionSize = pcapHeaderLength; + List<FlowFile> splitFilesList = new ArrayList<>(); + + List<Packet> newPackets = new ArrayList<>(); + templatePcap.packets().clear(); Review Comment: Per earlier comment remove `pcapHeaderLength` and `packetHeaderLength` and use the declared static final equivalents which makes this method more readable. ```suggestion final List<Packet> unprocessedPackets = parsedPcap.packets(); final List<FlowFile> splitFilesList = new ArrayList<>(); int currentPacketCollectionSize = PCAP_HEADER_LENGTH; List<Packet> newPackets = new ArrayList<>(); templatePcap.packets().clear(); ``` ########## nifi-extension-bundles/nifi-network-bundle/nifi-network-processors/src/main/java/org/apache/nifi/processors/network/pcap/SplitPCAP.java: ########## @@ -0,0 +1,209 @@ +/* + * 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 + * + * http://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.nifi.processors.network.pcap; + +import org.apache.nifi.components.PropertyDescriptor; +import org.apache.nifi.flowfile.FlowFile; +import org.apache.nifi.annotation.behavior.InputRequirement; +import org.apache.nifi.annotation.behavior.InputRequirement.Requirement; +import org.apache.nifi.annotation.behavior.SideEffectFree; +import org.apache.nifi.annotation.behavior.WritesAttribute; +import org.apache.nifi.annotation.behavior.WritesAttributes; +import org.apache.nifi.annotation.documentation.CapabilityDescription; +import org.apache.nifi.annotation.documentation.Tags; +import org.apache.nifi.processor.AbstractProcessor; +import org.apache.nifi.processor.ProcessContext; +import org.apache.nifi.processor.ProcessSession; +import org.apache.nifi.processor.Relationship; +import org.apache.nifi.processor.util.StandardValidators; +import org.apache.nifi.flowfile.attributes.FragmentAttributes; +import org.apache.nifi.flowfile.attributes.CoreAttributes; +import org.apache.nifi.processors.network.pcap.PCAP.ByteBufferInterface; +import org.apache.nifi.processors.network.pcap.PCAP.Packet; + +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.IntStream; + +@SideEffectFree +@InputRequirement(Requirement.INPUT_REQUIRED) +@Tags({"PCAP", "Splitter", "Network", "Packet", "Capture", "Wireshark", "TShark"}) +@CapabilityDescription("Splits a pcap file into multiple pcap files based on a maximum size.") +@WritesAttributes({ + @WritesAttribute(attribute = SplitPCAP.ERROR_REASON, description = "The reason the flowfile was sent to the failure relationship."), + @WritesAttribute(attribute = "fragment.identifier", description = "All split FlowFiles produced from the same parent FlowFile will have the same randomly generated UUID added for this attribute"), + @WritesAttribute(attribute = "fragment.index", description = "A one-up number that indicates the ordering of the split FlowFiles that were created from a single parent FlowFile"), + @WritesAttribute(attribute = "fragment.count", description = "The number of split FlowFiles generated from the parent FlowFile"), + @WritesAttribute(attribute = "segment.original.filename ", description = "The filename of the parent FlowFile") +}) + +public class SplitPCAP extends AbstractProcessor { + + protected static final String ERROR_REASON = "ERROR_REASON"; + public static final String FRAGMENT_ID = FragmentAttributes.FRAGMENT_ID.key(); + public static final String FRAGMENT_INDEX = FragmentAttributes.FRAGMENT_INDEX.key(); + public static final String FRAGMENT_COUNT = FragmentAttributes.FRAGMENT_COUNT.key(); + public static final String SEGMENT_ORIGINAL_FILENAME = FragmentAttributes.SEGMENT_ORIGINAL_FILENAME.key(); + + public static final PropertyDescriptor PCAP_MAX_SIZE = new PropertyDescriptor + .Builder().name("PCAP_MAX_SIZE") + .displayName("PCAP max size (bytes)") + .description("Maximum size of the output pcap file in bytes.") + .required(true) + .addValidator(StandardValidators.POSITIVE_INTEGER_VALIDATOR) + .build(); + + public static final Relationship REL_ORIGINAL = new Relationship.Builder() + .name("original") + .description("The original FlowFile that was split into segments. If the FlowFile fails processing, nothing will be sent to " + + "this relationship") + .build(); + public static final Relationship REL_FAILURE = new Relationship.Builder() + .name("failure") + .description("If a FlowFile cannot be transformed from the configured input format to the configured output format, " + + "the unchanged FlowFile will be routed to this relationship.") + .build(); + public static final Relationship REL_SPLIT = new Relationship.Builder() + .name("split") + .description("The individual 'segments' of the original FlowFile will be routed to this relationship.") + .build(); + + private static final List<PropertyDescriptor> DESCRIPTORS = List.of(PCAP_MAX_SIZE); + + private static final Set<Relationship> RELATIONSHIPS = Set.of(REL_ORIGINAL, REL_FAILURE, REL_SPLIT); + + @Override + public Set<Relationship> getRelationships() { + return RELATIONSHIPS; + } + + @Override + public final List<PropertyDescriptor> getSupportedPropertyDescriptors() { + return DESCRIPTORS; + } + + /** + * This method is called when a trigger event occurs in the processor. + * It processes the incoming flow file, splits it into smaller pcap files based on the maximum size, + * and transfers the split pcap files to the success relationship. + * If the flow file is empty or not parseable, it is transferred to the failure relationship. + * + * @param context the process context + * @param session the process session + */ + @Override + public void onTrigger(final ProcessContext context, final ProcessSession session) { + FlowFile flowFile = session.get(); + if (flowFile == null) { + return; + } + + int pcapMaxSize = context.getProperty(PCAP_MAX_SIZE.getName()).asInteger(); + + final ByteArrayOutputStream contentBytes = new ByteArrayOutputStream(); + session.exportTo(flowFile, contentBytes); + final byte[] contentByteArray = contentBytes.toByteArray(); + + if (contentByteArray.length == 0) { + session.putAttribute(flowFile, ERROR_REASON, "PCAP file empty."); + session.transfer(flowFile, REL_FAILURE); + return; + } + + final PCAP parsedPcap; + final PCAP templatePcap; + + // Parse the pcap file and create a template pcap object to borrow the header from. + try { + parsedPcap = new PCAP(new ByteBufferInterface(contentByteArray)); + + // Recreating rather than using deepcopy as recreating is more efficient in this case. + templatePcap = new PCAP(new ByteBufferInterface(contentByteArray)); + + } catch (Exception e) { + session.putAttribute(flowFile, ERROR_REASON, "PCAP file not parseable."); + session.transfer(flowFile, REL_FAILURE); + return; + } + + final List<Packet> unprocessedPackets = parsedPcap.packets(); + final int pcapHeaderLength = 24; + final int packetHeaderLength = 16; + + int currentPacketCollectionSize = pcapHeaderLength; + List<FlowFile> splitFilesList = new ArrayList<>(); + + List<Packet> newPackets = new ArrayList<>(); + templatePcap.packets().clear(); + + // Loop through all packets in the pcap file and split them into smaller pcap files. + while (!unprocessedPackets.isEmpty()) { + Packet packet = unprocessedPackets.getFirst(); + + if (packet.inclLen() > pcapMaxSize) { + session.putAttribute(flowFile, ERROR_REASON, "PCAP contains a packet larger than the max size."); + session.transfer(flowFile, REL_FAILURE); + return; + } + + if (currentPacketCollectionSize + (packet.inclLen() + packetHeaderLength) > pcapMaxSize && currentPacketCollectionSize > 0) { + templatePcap.packets().addAll(newPackets); + var newFlowFile = session.create(flowFile); + session.write(newFlowFile, out -> out.write(templatePcap.readBytesFull())); + splitFilesList.add(newFlowFile); + + newPackets = new ArrayList<>(); + currentPacketCollectionSize = pcapHeaderLength; Review Comment: ```suggestion currentPacketCollectionSize = PCAP_HEADER_LENGTH; ``` ########## nifi-extension-bundles/nifi-network-bundle/nifi-network-processors/src/test/java/org/apache/nifi/processors/network/pcap/TestPCAP.java: ########## @@ -0,0 +1,94 @@ +/* + * 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 + * + * http://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.nifi.processors.network.pcap; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.ArrayList; + +import org.apache.nifi.processors.network.pcap.PCAP.Packet; +import org.apache.nifi.processors.network.pcap.PCAP.Header; Review Comment: Per earlier request these imports will need to be changed ```suggestion import org.apache.nifi.processors.network.pcap.Packet; import org.apache.nifi.processors.network.pcap.Header; ``` ########## nifi-extension-bundles/nifi-network-bundle/nifi-network-processors/src/test/java/org/apache/nifi/processors/network/pcap/TestSplitPCAP.java: ########## @@ -0,0 +1,161 @@ +/* + * 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 + * + * http://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.nifi.processors.network; + +import java.io.IOException; +import java.util.ArrayList; + +import org.apache.nifi.util.TestRunner; +import org.apache.nifi.util.TestRunners; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.apache.nifi.processors.network.pcap.SplitPCAP; +import org.apache.nifi.processors.network.pcap.PCAP; +import org.apache.nifi.processors.network.pcap.PCAP.Header; +import org.apache.nifi.processors.network.pcap.PCAP.Packet; + + +public class TestSplitPCAP { + + private Header hdr; + private Packet validPacket; + private Packet invalidPacket; + + @BeforeEach + public void init() { + // Create a header for the test PCAP + this.hdr = new Header( + new byte[]{(byte) 0xa1, (byte) 0xb2, (byte) 0xc3, (byte) 0xd4}, + 2, + 4, + 0, + (long) 0, + (long) 40, + (long) 1 // ETHERNET + ); + + this.validPacket = new Packet( + (long) 1713184965, + (long) 1000, + (long) 30, + (long) 30, + new byte[]{ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, + 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, + } + ); + + this.invalidPacket = new Packet( + (long) 1713184965, + (long) 1000, + (long) 10, + (long) 10, + new byte[]{ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, + 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, + } + ); + + } + + @Test + public void testValidPackets() throws IOException { + TestRunner runner = TestRunners.newTestRunner(SplitPCAP.class); + runner.setProperty(SplitPCAP.PCAP_MAX_SIZE, "100"); + + ArrayList<Packet> packets = new ArrayList<>(); + for (var loop = 0; loop < 3; loop++) { + packets.add(this.validPacket); + } + + PCAP testPcap = new PCAP(this.hdr, packets); + + runner.enqueue(testPcap.readBytesFull()); + + runner.run(); + + runner.assertTransferCount(SplitPCAP.REL_SPLIT, 3); + runner.assertTransferCount(SplitPCAP.REL_ORIGINAL, 1); + runner.assertQueueEmpty(); + } + + @Test + public void testInvalidPackets() throws IOException { + TestRunner runner = TestRunners.newTestRunner(SplitPCAP.class); + runner.setProperty(SplitPCAP.PCAP_MAX_SIZE, "50"); + + ArrayList<Packet> packets = new ArrayList<>(); + for (var loop = 0; loop < 3; loop++) { + packets.add(this.invalidPacket); + } + + PCAP testPcap = new PCAP(this.hdr, packets); + + runner.enqueue(testPcap.readBytesFull()); + + runner.run(); + + runner.assertAllFlowFilesTransferred(SplitPCAP.REL_FAILURE, 1); + runner.assertQueueEmpty(); + } + + @Test + public void testPacketsTooBig() throws IOException { + TestRunner runner = TestRunners.newTestRunner(SplitPCAP.class); + runner.setProperty(SplitPCAP.PCAP_MAX_SIZE, "10"); + + ArrayList<Packet> packets = new ArrayList<>(); + for (var loop = 0; loop < 3; loop++) { + packets.add(this.validPacket); + } + + PCAP testPcap = new PCAP(this.hdr, packets); + + runner.enqueue(testPcap.readBytesFull()); + + runner.run(); + + runner.assertAllFlowFilesTransferred(SplitPCAP.REL_FAILURE, 1); + runner.assertQueueEmpty(); + } + + @Test + public void testOneInvalidPacket() throws IOException { + TestRunner runner = TestRunners.newTestRunner(SplitPCAP.class); + runner.setProperty(SplitPCAP.PCAP_MAX_SIZE, "10"); + + ArrayList<Packet> packets = new ArrayList<>(); Review Comment: ```suggestion List<Packet> packets = new ArrayList<>(); ``` -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
