diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..4a38d0d
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,23 @@
+name: CI
+
+on:
+ push:
+ branches: [master, main, "v0.*"]
+ pull_request:
+
+jobs:
+ test:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ python-version: ["3.11", "3.12", "3.13", "3.14"]
+
+ steps:
+ - uses: actions/checkout@v4
+ - uses: astral-sh/setup-uv@v5
+ with:
+ python-version: ${{ matrix.python-version }}
+ - run: uv sync --group dev
+ - run: uv run ruff check ipfix tests scripts
+ - run: uv run pytest
diff --git a/.gitignore b/.gitignore
index 74d5af6..3b37697 100644
--- a/.gitignore
+++ b/.gitignore
@@ -39,3 +39,11 @@ nosetests.xml
# Sphinx tempfiles
sphinx/_build
+# Modern Python tooling
+.venv/
+.pytest_cache/
+.ruff_cache/
+__pycache__/
+uv.lock
+
+
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index 6dd4abd..0000000
--- a/.travis.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-notifications:
- email: false
-
-language: python
-python:
- - "2.7"
- - "3.3"
- - "3.4"
-install:
- - if [[ $TRAVIS_PYTHON_VERSION == 2* ]]; then
- pip install functools32;
- pip install py2-ipaddress;
- pip install pytz;
- fi
- - pip install doctest-ignore-unicode
- - pip install svgwrite
- - pip install python-coveralls
-script:
- - nosetests
-after_success:
- - coveralls
diff --git a/CHANGES.txt b/CHANGES.txt
index bfa6acf..deffb86 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -19,4 +19,26 @@ v0.9.6, 2014-06-06 -- Test coverage improvements, consolidation of scripts,
bugfixes (export time, reduced-length encoding),
update to latest IANA Information Element registry.
-v0.9.7, 2014-07-04 -- Bugfix (export time and sequence number reversed)
\ No newline at end of file
+v0.9.7, 2014-07-04 -- Bugfix (export time and sequence number reversed)
+
+v0.10.0, 2026-11-22 -- Modernize packaging (pyproject.toml with PEP 639, Python
+ 3.11+, drop Python 2 compat and vis-package); refresh IANA
+ IE registry (up to ID 533; note ID 278 renamed from
+ connectionCountNew to newConnectionDeltaCount, and ID 263
+ messageScope changed from unsigned64 to unsigned8) and
+ RFC 5103 reverse IEs; add unsigned256 (RFC 9740) and
+ arbitrary-width integer RLE; harden IPFIX and NetFlow v9
+ decoders against malformed packets (setlen < 4, zero-
+ length templates, bounds checks, template set padding,
+ template withdrawals, unbounded unknown IE cache); fix
+ varlen-first templates, strict RLE validation and fixed-
+ length string parse/unparse/resizing, use_integer_ipv4,
+ IE hashing, accepted_tids caching, empty set emission and
+ delete_template atomicity, export_record error propagation,
+ begin_export(0), writer default domain and flush/template
+ bugs, reader msgcount, and v9pdu Options Templates, stream
+ version check, and sequence accounting; accept timezone-
+ aware datetimes on encode/parse/unparse while eliminating
+ Python 3.12+ deprecation warnings (note:
+ template_record_hook now also fires on template
+ withdrawals with tmpl.count() == 0); expand pytest suite.
diff --git a/MANIFEST.in b/MANIFEST.in
deleted file mode 100644
index 9203697..0000000
--- a/MANIFEST.in
+++ /dev/null
@@ -1,2 +0,0 @@
-include *.txt
-recursive-include docs *.txt
\ No newline at end of file
diff --git a/README.md b/README.md
index 7bfa99a..8d22bd7 100644
--- a/README.md
+++ b/README.md
@@ -1,17 +1,55 @@
-python-ipfix
-============
+# python-ipfix
-IPFIX implementation for Python 3.3.
+IPFIX (RFC 7011) implementation for Python 3.11+.
-This module provides a Python interface to IPFIX message streams, and
-provides tools for building IPFIX Exporting and Collecting Processes.
-It handles message framing and deframing, encoding and decoding IPFIX
-data records using templates, and a bridge between IPFIX ADTs and
-appropriate Python data types.
+This package provides a Python interface to IPFIX message streams, and tools
+for building IPFIX Exporting and Collecting Processes. It handles message
+framing and deframing, encoding and decoding IPFIX data records using
+templates, a bridge between IPFIX abstract data types (ADTs) and native Python
+data types, and a read-only NetFlow v9 PDU decoder.
-It should work on Python 2.7 as well; your mileage may vary. To install on
-Python 2.7, the following additional dependencies must be manually installed:
+## Installation
-- pip install functools32
-- pip install py2-ipaddress
-- pip install pytz
+```bash
+pip install ipfix
+```
+
+Requires Python 3.11 or later, with no mandatory runtime dependencies.
+
+## Quick Start
+
+```python
+import ipfix.ie
+import ipfix.message
+import ipfix.template
+
+ipfix.ie.use_iana_default()
+ipfix.ie.use_5103_default()
+
+msg = ipfix.message.MessageBuffer()
+msg.begin_export(8304)
+tmpl = ipfix.template.for_specs(
+ 256,
+ "flowStartMilliseconds",
+ "sourceIPv4Address",
+ "destinationIPv4Address",
+ "packetDeltaCount",
+)
+msg.add_template(tmpl)
+msg.export_ensure_set(256)
+```
+
+Command-line utilities `ipfix2csv` and `ipfixstat` are installed as console
+scripts.
+
+## Development
+
+```bash
+uv sync --group dev
+uv run ruff check ipfix tests scripts
+uv run pytest
+```
+
+## License
+
+GNU Lesser General Public License v3 or later (LGPLv3+).
diff --git a/README.txt b/README.txt
deleted file mode 100644
index cd4c37e..0000000
--- a/README.txt
+++ /dev/null
@@ -1,10 +0,0 @@
-python-ipfix
-============
-
-IPFIX implementation for Python 3.3.
-
-This module provides a Python interface to IPFIX message streams, and
-provides tools for building IPFIX Exporting and Collecting Processes.
-It handles message framing and deframing, encoding and decoding IPFIX
-data records using templates, and a bridge between IPFIX ADTs and
-appopriate Python data types.
diff --git a/ipfix/__init__.py b/ipfix/__init__.py
index 86f0cc8..ce0c781 100644
--- a/ipfix/__init__.py
+++ b/ipfix/__init__.py
@@ -1,6 +1,5 @@
-# coding: utf8
#
-# python-ipfix (c) 2013 Brian Trammell.
+# python-ipfix (c) 2013-2026 Brian Trammell.
#
# Many thanks to the mPlane consortium (http://www.ict-mplane.eu) for
# its material support of this effort.
@@ -19,10 +18,8 @@
# this program. If not, see .
#
-from __future__ import unicode_literals
-
"""
-IPFIX implementation for Python 3.3.
+IPFIX (RFC 7011) implementation for Python 3.11+.
.. moduleauthor:: Brian Trammell
@@ -47,14 +44,15 @@
messages, see :mod:`ipfix.message`. In any case, exporters will need to define
templates; see :mod:`ipfix.template`.
-This module is copyright 2013 Brian Trammell. It is made available under the
-terms of the
+This module is copyright 2013-2026 Brian Trammell. It is made available under
+the terms of the
`GNU Lesser General Public License `_,
version 3 or, at your option, any later version.
"""
-from . import types
-from . import ie
-from . import template
-from . import message
+from . import ie, message, template, types
+
+__version__ = "0.10.0"
+
+__all__ = ["types", "ie", "template", "message", "__version__"]
diff --git a/ipfix/cli.py b/ipfix/cli.py
new file mode 100644
index 0000000..3d961e9
--- /dev/null
+++ b/ipfix/cli.py
@@ -0,0 +1,285 @@
+#
+# python-ipfix (c) 2013-2026 Brian Trammell.
+#
+# Many thanks to the mPlane consortium (http://www.ict-mplane.eu) for
+# its material support of this effort.
+#
+# This program is free software: you can redistribute it and/or modify it under
+# the terms of the GNU Lesser General Public License as published by the Free
+# Software Foundation, either version 3 of the License, or (at your option) any
+# later version.
+#
+# This program is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
+# details.
+#
+# You should have received a copy of the GNU General Public License along with
+# this program. If not, see .
+#
+
+"""Command-line entry points for ipfix2csv and ipfixstat."""
+
+import argparse
+import bz2
+import csv
+import gzip
+import socketserver
+import sys
+
+from . import ie, message, reader, v9pdu
+
+
+def _init_ipfix(specfiles=None):
+ ie.use_iana_default()
+ ie.use_5103_default()
+ if specfiles:
+ for sf in specfiles:
+ ie.use_specfile(sf)
+
+
+def _open_input(filename, use_gzip=False, use_bzip2=False):
+ if use_bzip2:
+ return bz2.open(filename, mode="rb")
+ if use_gzip:
+ return gzip.open(filename, mode="rb")
+ return open(filename, mode="rb")
+
+
+def stream_to_csv(instream, ienames, outstream=None, reader_fn=reader.from_stream):
+ """Read an IPFIX or NetFlow v9 stream and write selected IEs as CSV."""
+ if outstream is None:
+ outstream = sys.stdout
+ cols = ie.spec_list(ienames)
+ r = reader_fn(instream)
+ w = csv.writer(outstream, dialect="unix")
+ w.writerow([e.name for e in cols])
+ for rec in r.tuple_iterator(cols):
+ w.writerow([col.unparse(val) for val, col in zip(rec, cols, strict=True)])
+
+
+def main_ipfix2csv(argv=None):
+ parser = argparse.ArgumentParser(
+ description="Convert an IPFIX file or stream to CSV"
+ )
+ parser.add_argument("ienames", metavar="ie", nargs="+", help="column(s) by IE name")
+ parser.add_argument(
+ "--spec", "-s", metavar="specfile", action="append",
+ help="file to load additional IESpecs from",
+ )
+ parser.add_argument(
+ "--file", "-f", metavar="file", nargs="?",
+ help="IPFIX file to read (default stdin)",
+ )
+ comp_group = parser.add_mutually_exclusive_group()
+ comp_group.add_argument(
+ "--gzip", "-z", action="store_true",
+ help="Decompress gzip-compressed IPFIX file",
+ )
+ comp_group.add_argument(
+ "--bzip2", "-j", action="store_true",
+ help="Decompress bz2-compressed IPFIX file",
+ )
+ parser.add_argument(
+ "--netflow9", "-9", action="store_true",
+ help="Decode as NetFlow version 9 instead of IPFIX (with --file or stdin only)",
+ )
+ parser.add_argument(
+ "--collect", "-c", metavar="transport", nargs="?",
+ help="run CP on specified transport",
+ )
+ parser.add_argument(
+ "--bind", "-b", metavar="bind", nargs="?", default="",
+ help="address to bind to as CP (default all)",
+ )
+ parser.add_argument(
+ "--port", "-p", metavar="port", nargs="?", type=int, default=4739,
+ help="port to bind to as CP (default 4739)",
+ )
+ args = parser.parse_args(argv)
+
+ if args.file is None and (args.bzip2 or args.gzip):
+ raise ValueError("Decompression only supported from file input")
+
+ _init_ipfix(args.spec)
+ reader_fn = v9pdu.from_stream if args.netflow9 else reader.from_stream
+
+ if args.netflow9 and args.collect:
+ raise ValueError("NetFlow9 only supported from files or stdin")
+
+ if args.collect == "tcp":
+ sys.stderr.write(
+ f"starting TCP CP on {args.bind}:{args.port}; Ctrl-C to stop\n"
+ )
+ sys.stderr.flush()
+
+ class TcpCsvHandler(socketserver.StreamRequestHandler):
+ def handle(self):
+ sys.stderr.write(f"connection from {self.client_address}\n")
+ stream_to_csv(self.rfile, args.ienames)
+
+ with socketserver.TCPServer((args.bind, args.port), TcpCsvHandler) as ss:
+ ss.serve_forever()
+ elif args.collect:
+ raise ValueError(
+ f"Unsupported transport {args.collect}; must be 'tcp' in this revision"
+ )
+ elif args.file:
+ with _open_input(args.file, args.gzip, args.bzip2) as f:
+ stream_to_csv(f, args.ienames, reader_fn=reader_fn)
+ else:
+ stream_to_csv(sys.stdin.buffer, args.ienames, reader_fn=reader_fn)
+
+
+class TemplateStatsSession:
+ """Collect template and dataset statistics over an IPFIX or NetFlow v9 stream."""
+
+ def __init__(self, instream, netflow9=False):
+ self._netflow9 = netflow9
+ self.templates = {}
+ self.template_count = {}
+ self.template_replcount = {}
+ self.template_setcount = {}
+ self.template_bytecount = {}
+ self.missing_setcount = {}
+ self.missing_bytecount = {}
+
+ if netflow9:
+ self.r = v9pdu.from_stream(instream)
+ self.r.template_record_hook = self.handle_template_record
+ self.r.ignored_data_set_hook = self.handle_data_set
+ self.r.unknown_data_set_hook = self.handle_unknown_set
+ else:
+ self.r = reader.from_stream(instream)
+ self.r.msg.template_record_hook = self.handle_template_record
+ self.r.msg.ignored_data_set_hook = self.handle_data_set
+ self.r.msg.unknown_data_set_hook = self.handle_unknown_set
+
+ def handle_template_record(self, msg, tmpl):
+ if tmpl.count() == 0:
+ return
+ tkey = (msg.odid, tmpl.tid)
+ if tkey in self.templates:
+ self.template_count[tkey] += 1
+ if not self.templates[tkey].identical_to(tmpl):
+ self.template_replcount[tkey] += 1
+ self.templates[tkey] = tmpl
+ else:
+ self.templates[tkey] = tmpl
+ self.template_count[tkey] = 1
+ self.template_replcount[tkey] = 0
+ self.template_setcount[tkey] = 0
+ self.template_bytecount[tkey] = 0
+
+ def handle_data_set(self, msg, tmpl, setbuf):
+ tkey = (msg.odid, tmpl.tid)
+ self.template_setcount[tkey] += 1
+ self.template_bytecount[tkey] += len(setbuf)
+
+ def handle_unknown_set(self, msg, setbuf):
+ setid, setlen = message._sethdr_st.unpack_from(setbuf)
+ tkey = (msg.odid, setid)
+ self.missing_setcount[tkey] = self.missing_setcount.get(tkey, 0) + 1
+ self.missing_bytecount[tkey] = self.missing_bytecount.get(tkey, 0) + setlen
+
+ def run(self):
+ if self._netflow9:
+ for _ in self.r.record_iterator(tmplaccept_fn=lambda _tmpl: False):
+ pass
+ else:
+ try:
+ while True:
+ self.r.msg.read_message(self.r.stream)
+ self.r.msgcount += 1
+ for _ in self.r.msg.record_iterator(tmplaccept_fn=lambda _tmpl: False):
+ pass
+ except EOFError:
+ return
+
+ def print_report(self, outstream=None):
+ if outstream is None:
+ outstream = sys.stdout
+ missing_setcount = self.missing_setcount.copy()
+
+ total_tsets = sum(self.template_count.values())
+ total_dsets = sum(self.template_setcount.values())
+ total_repl = sum(self.template_replcount.values())
+ total_miss = sum(self.missing_setcount.values())
+
+ outstream.write(
+ f"#\n# {len(self.templates)} templates, {total_tsets} template sets, "
+ f"{total_dsets} decodable sets, {total_repl} replacements, "
+ f"{total_miss} missing sets total\n"
+ )
+
+ for tkey in sorted(self.templates.keys()):
+ odid, _ = tkey
+ tmpl = self.templates[tkey]
+ kind = "Options Template" if tmpl.scopecount else "Template"
+ outstream.write(
+ f"#\n# {kind} {tmpl.tid} in domain {odid} ({len(tmpl.ies)} IEs)\n#\n"
+ )
+ for i, elem in enumerate(tmpl.ies):
+ addl = "{scope}" if i < tmpl.scopecount else ""
+ outstream.write(f"{elem}{addl}\n")
+ outstream.write(
+ f"# {self.template_count[tkey]} instances "
+ f"{self.template_replcount[tkey]} replacements "
+ f"{self.template_setcount[tkey]} sets "
+ f"{self.template_bytecount[tkey]} bytes \n"
+ )
+ if tkey in missing_setcount:
+ outstream.write(
+ f"# {missing_setcount[tkey]} sets missing template with this ID\n"
+ )
+ del missing_setcount[tkey]
+
+ if missing_setcount:
+ outstream.write("#\n# Sets without templates\n")
+ for tkey, count in missing_setcount.items():
+ outstream.write(
+ f"# {count} sets missing template with ID {tkey[1]} in domain {tkey[0]}\n"
+ )
+
+
+def main_ipfixstat(argv=None):
+ parser = argparse.ArgumentParser(
+ description="Dump statistics about templates and data sets in an IPFIX file"
+ )
+ parser.add_argument(
+ "--spec", "-s", metavar="specfile", action="append",
+ help="file to load additional IESpecs from",
+ )
+ parser.add_argument(
+ "--file", "-f", metavar="file", nargs="?",
+ help="IPFIX file to read (default stdin)",
+ )
+ comp_group = parser.add_mutually_exclusive_group()
+ comp_group.add_argument(
+ "--gzip", "-z", action="store_true",
+ help="Decompress gzip-compressed IPFIX file",
+ )
+ comp_group.add_argument(
+ "--bzip2", "-j", action="store_true",
+ help="Decompress bz2-compressed IPFIX file",
+ )
+ parser.add_argument(
+ "--netflow9", "-9", action="store_true",
+ help="Decode as NetFlow version 9 instead of IPFIX",
+ )
+ args = parser.parse_args(argv)
+
+ if args.file is None and (args.bzip2 or args.gzip):
+ raise ValueError("Decompression only supported from file input")
+
+ _init_ipfix(args.spec)
+
+ if args.file:
+ with _open_input(args.file, args.gzip, args.bzip2) as f:
+ tss = TemplateStatsSession(f, args.netflow9)
+ tss.run()
+ else:
+ tss = TemplateStatsSession(sys.stdin.buffer, args.netflow9)
+ tss.run()
+
+ tss.print_report()
diff --git a/ipfix/compat.py b/ipfix/compat.py
deleted file mode 100644
index bca0dd3..0000000
--- a/ipfix/compat.py
+++ /dev/null
@@ -1,75 +0,0 @@
-try:
- # Python 3 imports
- from datetime import timezone
- import urllib.request as urlreq
- from functools import lru_cache
-
- # These will succeed in Python 2, but we won't get here due to
- # ImportError from the previous lines.
- izip = zip
- xrange = range
- ifilter = filter
- from functools import reduce
-except ImportError:
- import pytz as timezone
- import urllib2 as urlreq
- from functools32 import lru_cache
-
- from itertools import izip, ifilter
- xrange = xrange
- reduce = reduce
-
-def _get_memoryview_buffer(bufsize):
- return memoryview(bytearray(bufsize))
-
-
-def _get_fake_memoryview_buffer(bufsize):
- return _FakeMemoryView(bufsize)
-
-
-class _FakeMemoryView(bytearray):
- """
- Python 2.7.8 has a bug that prevents struct.pack_into from
- working with a memoryview: http://bugs.python.org/issue22113
-
- This class just acts like a memoryview from the perspective
- of the rest of the library (though it lacks the performance benefits).
- It can and should go away if this bug gets fixed in a later 2.7 version.
- """
-
- def __getitem__(self, key):
- _slice = bytearray.__getitem__(self, key)
- return _FakeMemoryView(_slice)
-
- def tobytes(self):
- return self
-
- def tolist(self):
- return list(self)
-
-try:
- length = 10
- mv = memoryview(bytearray(length))
- mv[0:length] = bytearray([0] * length)
- import struct
- struct.pack_into("!HLL", mv, 0, 42, 17, 21)
-
- # if slice assignment succeeded, no bug.
- get_buffer = _get_memoryview_buffer
-except TypeError:
- # slice assignment bug exists.
- # return a bytearray with the few extra methods that
- # the MessageBuffer wants. Less efficient, but not broken.
- get_buffer = _get_fake_memoryview_buffer
-
-
-def _datetime_to_timestamp_by_duration(datetime_):
- # from python3 docs
- dur = (datetime_ - datetime.datetime(1970, 1, 1, tzinfo=timezone.utc))
- return dur.total_seconds()
-
-import datetime
-if hasattr(datetime.datetime, 'timestamp'):
- datetime_to_timestamp = getattr(datetime.datetime, 'timestamp')
-else:
- datetime_to_timestamp = _datetime_to_timestamp_by_duration
diff --git a/ipfix/iana.iespec b/ipfix/iana.iespec
index ba268bd..d21596c 100644
--- a/ipfix/iana.iespec
+++ b/ipfix/iana.iespec
@@ -231,7 +231,7 @@ exportSctpStreamId(259)[2]
maxExportSeconds(260)[4]
maxFlowEndSeconds(261)[4]
messageMD5Checksum(262)[65535]
-messageScope(263)[8]
+messageScope(263)[1]
minExportSeconds(264)[4]
minFlowStartSeconds(265)[4]
opaqueOctets(266)[65535]
@@ -246,7 +246,7 @@ collectorCertificate(274)[65535]
exporterCertificate(275)[65535]
dataRecordsReliability(276)[1]
observationPointType(277)[1]
-connectionCountNew(278)[4]
+newConnectionDeltaCount(278)[4]
connectionSumDurationSeconds(279)[8]
connectionTransactionId(280)[8]
postNATSourceIPv6Address(281)[16]
@@ -396,4 +396,87 @@ layer2OctetTotalSumOfSquares(429)[8]
layer2FrameDeltaCount(430)[8]
layer2FrameTotalCount(431)[8]
pseudoWireDestinationIPv4Address(432)[4]
-ignoredLayer2FrameTotalCount(433)[8]
\ No newline at end of file
+ignoredLayer2FrameTotalCount(433)[8]
+mibObjectValueInteger(434)[4]
+mibObjectValueOctetString(435)[65535]
+mibObjectValueOID(436)[65535]
+mibObjectValueBits(437)[65535]
+mibObjectValueIPAddress(438)[4]
+mibObjectValueCounter(439)[8]
+mibObjectValueGauge(440)[4]
+mibObjectValueTimeTicks(441)[4]
+mibObjectValueUnsigned(442)[4]
+mibObjectIdentifier(445)[65535]
+mibSubIdentifier(446)[4]
+mibIndexIndicator(447)[8]
+mibCaptureTimeSemantics(448)[1]
+mibContextEngineID(449)[65535]
+mibContextName(450)[65535]
+mibObjectName(451)[65535]
+mibObjectDescription(452)[65535]
+mibObjectSyntax(453)[65535]
+mibModuleName(454)[65535]
+mobileIMSI(455)[65535]
+mobileMSISDN(456)[65535]
+httpStatusCode(457)[2]
+sourceTransportPortsLimit(458)[2]
+httpRequestMethod(459)[65535]
+httpRequestHost(460)[65535]
+httpRequestTarget(461)[65535]
+httpMessageVersion(462)[65535]
+natInstanceID(463)[4]
+internalAddressRealm(464)[65535]
+externalAddressRealm(465)[65535]
+natQuotaExceededEvent(466)[4]
+natThresholdEvent(467)[4]
+httpUserAgent(468)[65535]
+httpContentType(469)[65535]
+httpReasonPhrase(470)[65535]
+maxSessionEntries(471)[4]
+maxBIBEntries(472)[4]
+maxEntriesPerUser(473)[4]
+maxSubscribers(474)[4]
+maxFragmentsPendingReassembly(475)[4]
+addressPoolHighThreshold(476)[4]
+addressPoolLowThreshold(477)[4]
+addressPortMappingHighThreshold(478)[4]
+addressPortMappingLowThreshold(479)[4]
+addressPortMappingPerUserHighThreshold(480)[4]
+globalAddressMappingHighThreshold(481)[4]
+vpnIdentifier(482)[65535]
+bgpCommunity(483)[4]
+bgpExtendedCommunity(486)[65535]
+bgpLargeCommunity(489)[65535]
+srhFlagsIPv6(492)[1]
+srhTagIPv6(493)[2]
+srhSegmentIPv6(494)[16]
+srhActiveSegmentIPv6(495)[16]
+srhSegmentIPv6ListSection(497)[65535]
+srhSegmentsIPv6Left(498)[1]
+srhIPv6Section(499)[65535]
+srhIPv6ActiveSegmentType(500)[1]
+srhSegmentIPv6LocatorLength(501)[1]
+srhSegmentIPv6EndpointBehavior(502)[2]
+transportChecksum(503)[2]
+icmpHeaderPacketSection(504)[65535]
+gtpuFlags(505)[1]
+gtpuMsgType(506)[1]
+gtpuTEid(507)[4]
+gtpuSequenceNum(508)[2]
+gtpuQFI(509)[1]
+gtpuPduType(510)[1]
+ipv6ExtensionHeaderType(513)[1]
+ipv6ExtensionHeaderCount(514)[1]
+ipv6ExtensionHeadersFull(515)[32]
+ipv6ExtensionHeadersLimit(517)[1]
+ipv6ExtensionHeadersChainLength(518)[4]
+tcpOptionsFull(520)[32]
+tcpSharedOptionExID16(521)[2]
+tcpSharedOptionExID32(522)[4]
+udpSafeOptions(525)[32]
+udpUnsafeOptions(526)[8]
+udpExID(527)[2]
+pathDelayMeanDeltaMicroseconds(530)[4]
+pathDelayMinDeltaMicroseconds(531)[4]
+pathDelayMaxDeltaMicroseconds(532)[4]
+pathDelaySumDeltaMicroseconds(533)[8]
diff --git a/ipfix/ie.py b/ipfix/ie.py
index 1757460..fcbf0d8 100644
--- a/ipfix/ie.py
+++ b/ipfix/ie.py
@@ -1,5 +1,5 @@
#
-# python-ipfix (c) 2013 Brian Trammell.
+# python-ipfix (c) 2013-2026 Brian Trammell.
#
# Many thanks to the mPlane consortium (http://www.ict-mplane.eu) for
# its material support of this effort.
@@ -20,12 +20,11 @@
"""
IESpec-based interface to IPFIX information elements,
-and interface to use the default IPFIX IANA Information Model
+and interface to use the default IPFIX IANA Information Model.
An IESpec is a string representation of an IPFIX information element,
including all the information required to define it, as documented in
-Section 9 of http://tools.ietf.org/html/draft-ietf-ipfix-ie-doctors.
-It has the format:
+Section 10.1 of RFC 7013. It has the format:
name(pen/num)[size]
@@ -34,7 +33,7 @@
>>> import ipfix.ie
>>> e = ipfix.ie.for_spec("myNewInformationElement(35566/1)")
->>> e #doctest: +IGNORE_UNICODE
+>>> e
InformationElement('myNewInformationElement', 35566, 1, ipfix.types.for_name('string'), 65535)
The string representation of an InformationElement is its IESpec:
@@ -64,40 +63,39 @@
>>> ipfix.ie.for_spec("sourceIPv4Address").parse("192.0.2.19")
IPv4Address('192.0.2.19')
>>> from datetime import datetime
->>> ipfix.ie.for_spec("flowEndMilliseconds").unparse(datetime(2013,6,21,14)) #doctest: +IGNORE_UNICODE
+>>> ipfix.ie.for_spec("flowEndMilliseconds").unparse(datetime(2013, 6, 21, 14))
'2013-06-21 14:00:00.000'
-
Most client code will only need the :func:`use_iana_default`,
:func:`use_5103_default`, and :func:`use_specfile` functions;
client code using tuple interfaces will need :func:`spec_list` as well.
"""
-from __future__ import with_statement, unicode_literals
+
+import importlib.resources
import re
-import os.path
-from . import types, compat
-from .compat import reduce
from functools import total_ordering
-import operator
-from io import open
-_iespec_re = re.compile('^([^\s\[\<\(]+)?(\(((\d+)\/)?(\d+)\))?'
- '(\<(\S+)\>)?(\[(\S+)\])?')
+from . import types
+
+_iespec_re = re.compile(
+ r"^([^\s\[\<\(]+)?(\(((\d+)\/)?(\d+)\))?"
+ r"(\<(\S+)\>)?(\[(\S+)\])?"
+)
# Internal information element registry
_ieForName = {}
_ieForNum = {}
+
def _register_ie(ie):
_ieForName[ie.name] = ie
_ieForNum[(ie.pen, ie.num)] = ie
-
return ie
@total_ordering
-class InformationElement(object):
+class InformationElement:
"""
An IPFIX Information Element (IE). This is essentially a five-tuple of
name, element number (num), a private enterprise number (pen; 0 if it
@@ -105,51 +103,57 @@ class InformationElement(object):
Information Elements may also have value string and parser functions,
for representing the values as strings; if not set, these default to
+ the type's valstr/valparse functions.
InformationElement instances should be obtained using the :func:`for_spec`
or :func:`for_template_entry` functions.
"""
- def __init__(self, name, pen, num, ietype=types._roottypes[0], length=None, valstr=None, valparse=None):
- if name:
- self.name = name
- else:
- self.name = "_ipfix_%u_%u" % (pen, num)
-
- if length:
- self.length = length
- else:
- self.length = ietype.length
-
+ def __init__(
+ self,
+ name,
+ pen,
+ num,
+ ietype=types._roottypes[0],
+ length=None,
+ valstr=None,
+ valparse=None,
+ ):
+ self.name = name if name else f"_ipfix_{pen}_{num}"
+ self.length = length if length else ietype.length
self.pen = pen
self.num = num
self.type = ietype.for_length(self.length)
-
self.valparse = valparse
self.valstr = valstr
def __eq__(self, other):
"""
Determine if an IE is equal to another IE.
- Two IEs are considered equal if they share a PEN, number, and length.
-
+ Two IEs are considered equal if they share a PEN and element number
+ (regardless of reduced-size encoding length).
"""
- return ((self.pen, self.num) == (other.pen, other.num))
+ if not isinstance(other, InformationElement):
+ return NotImplemented
+ return (self.pen, self.num) == (other.pen, other.num)
def __lt__(self, other):
- return ((self.pen, self.num) < (other.pen, other.num))
+ if not isinstance(other, InformationElement):
+ return NotImplemented
+ return (self.pen, self.num) < (other.pen, other.num)
def __repr__(self):
- return "InformationElement(%s, %s, %s, %s, %s)" % (repr(self.name),
- repr(self.pen), repr(self.num), repr(self.type),
- repr(self.length))
+ return (
+ f"InformationElement({self.name!r}, {self.pen!r}, {self.num!r}, "
+ f"{self.type!r}, {self.length!r})"
+ )
def __str__(self):
- return "%s(%u/%u)%s[%u]" % (self.name, self.pen, self.num, str(self.type), self.length)
+ return f"{self.name}({self.pen}/{self.num}){self.type}[{self.length}]"
def __hash__(self):
- return ((self.num << 16) + self.length) ^ self.pen
+ return hash((self.pen, self.num))
def for_length(self, length):
"""
@@ -160,11 +164,17 @@ def for_length(self, length):
:returns: this IE if length matches, or a new IE for the length
:raises: ValueError
"""
-
if not length or length == self.length:
return self
- else:
- return self.__class__(self.name, self.pen, self.num, self.type, length)
+ return self.__class__(
+ self.name,
+ self.pen,
+ self.num,
+ self.type,
+ length,
+ valstr=self.valstr,
+ valparse=self.valparse,
+ )
def unparse(self, v):
"""
@@ -172,15 +182,13 @@ def unparse(self, v):
for this Information Element. Uses the default string conversion
for the IE's type if not overridden at IE creation time.
- :param v: value to unparse using this IEs's string conversion
+ :param v: value to unparse using this IE's string conversion
:returns: string representation of v
:raises: ValueError if v is not a valid value for this IE
"""
-
if self.valstr:
return self.valstr(v)
- else:
- return self.type.valstr(v)
+ return self.type.valstr(v)
def parse(self, s):
"""
@@ -188,27 +196,28 @@ def parse(self, s):
for this Information Element. Uses the default string conversion
for the IE's type if not overridden at IE creation time.
- :param s: string to parse using this IEs's string conversion
+ :param s: string to parse using this IE's string conversion
:returns: value for given string
- :raises: ValueError is not a valid string representation for this IE
+ :raises: ValueError if s is not a valid string representation for this IE
"""
if self.valparse:
return self.valparse(s)
- else:
- return self.type.valparse(s)
+ return self.type.valparse(s)
@total_ordering
-class InformationElementList(object):
+class InformationElementList:
"""
A hashable ordered list of Information Elements.
Used internally by templates, and to specify the
order of tuples to the tuple append and iterator interfaces. Get an
- instance by calling :func:`spec_list`
+ instance by calling :func:`spec_list`.
"""
- def __init__(self, iterable = None):
+
+ def __init__(self, iterable=None):
self.inner = []
+ self.hashcache = None
if iterable:
for x in iterable:
@@ -218,21 +227,24 @@ def __iter__(self):
return iter(self.inner)
def __eq__(self, other):
+ if not isinstance(other, InformationElementList):
+ return NotImplemented
return self.inner == other.inner
def __lt__(self, other):
+ if not isinstance(other, InformationElementList):
+ return NotImplemented
return self.inner < other.inner
def __repr__(self):
- return "InformationElementList(" + ",".join((repr(x) for x in self.inner)) + ")"
+ return "InformationElementList(" + ",".join(repr(x) for x in self.inner) + ")"
def __str__(self):
- return "\n".join((str(x) for x in self.inner))
+ return "\n".join(str(x) for x in self.inner)
def __hash__(self):
- if not self.hashcache:
- self.hashcache = reduce(operator.xor, (hash(x) for x in self.inner))
-
+ if self.hashcache is None:
+ self.hashcache = hash(tuple(self.inner))
return self.hashcache
def __len__(self):
@@ -248,83 +260,72 @@ def append(self, ie):
self.inner.append(ie)
self.hashcache = None
-def parse_spec(spec):
- """Parse an IESpec into name, pen, number, typename, and length fields"""
- (name, pen, num, typename, length) = _iespec_re.match(spec).group(1,4,5,7,9)
-
- if pen:
- pen = int(pen)
- else:
- pen = 0
- if num:
- num = int(num)
- else:
- num = 0
-
- if length:
- length = int(length)
- else:
- length = 0
+def parse_spec(spec):
+ """Parse an IESpec into name, pen, number, typename, and length fields."""
+ match = _iespec_re.match(spec)
+ name, pen, num, typename, length = match.group(1, 4, 5, 7, 9)
+ pen = int(pen) if pen else 0
+ num = int(num) if num else 0
+ length = int(length) if length else 0
if not typename:
typename = False
return (name, pen, num, typename, length)
+
def for_spec(spec):
"""
Get an IE from the cache of known IEs, or create a
new IE if not found, given an IESpec.
- :param spec: IEspec, as in draft-ietf-ipfix-ie-doctors, of the
+ :param spec: IESpec, as in RFC 7013, of the
form name(pen/num)[size]; some fields may be
omitted unless creating a new IE in the cache.
:returns: an IE for the name
:raises: ValueError
-
-
"""
- (name, pen, num, typename, length) = parse_spec(spec)
+ name, pen, num, typename, length = parse_spec(spec)
if not name and not pen and not num and not typename and not length:
- raise ValueError("unrecognized IE spec "+spec)
+ raise ValueError("unrecognized IE spec " + spec)
if name and not pen and not num and name in _ieForName:
- # lookup in name registry
return _ieForName[name].for_length(length)
if num and (pen, num) in _ieForNum:
- # lookup in number registry
return _ieForNum[(pen, num)].for_length(length)
# try to create new registered IE
if not typename:
- raise ValueError("IE "+str(spec)+
- " unknown; use a full IEspec to create a new IE.")
+ raise ValueError(f"IE {spec} unknown; use a full IEspec to create a new IE.")
ietype = types.for_name(typename)
-
return _register_ie(InformationElement(name, pen, num, ietype, length))
+
def for_template_entry(pen, num, length):
"""
- Get an IE from the cache of known IEs, or create a
- new IE if not found, given a private enterprise number,
+ Get an IE from the cache of known IEs, or create an unregistered
+ octetArray IE if not found, given a private enterprise number,
element number, and length. Used internally by Templates.
+ Unknown IEs are intentionally NOT registered into the global cache
+ to prevent unbounded memory growth from untrusted network templates.
+
:param pen: private enterprise number, or 0 for an IANA IE
:param num: IE number (Element ID)
:param length: length of the IE in bytes
:returns: an IE for the given pen, num, and length. If the IE has not
- been previously added to the cache of known IEs, the IE will be
- named _ipfix_pen_num, and have octetArray as a type.
-
+ been previously added to the cache of known IEs, the IE will be
+ named _ipfix_pen_num, and have octetArray as a type.
"""
- if ((pen, num) in _ieForNum):
+ if (pen, num) in _ieForNum:
return _ieForNum[(pen, num)].for_length(length)
- return _register_ie(InformationElement(None, pen, num, types.for_name("octetArray"), length))
+ return InformationElement(None, pen, num, types.for_name("octetArray"), length)
+
def spec_list(specs):
"""
@@ -336,63 +337,57 @@ def spec_list(specs):
:returns: a new Information Element List, suitable for use with the tuple
export and iterator functions in :mod:`message`
:raises: ValueError
-
"""
return InformationElementList(for_spec(spec) for spec in specs)
+
def clear_infomodel():
"""Reset the cache of known Information Elements."""
_ieForName.clear()
_ieForNum.clear()
+
def dump_infomodel():
- return sorted([_ieForNum[x] for x in _ieForNum])
+ return sorted(_ieForNum.values())
+
+
+def _load_spec_stream(stream):
+ for line in stream:
+ line = line.strip()
+ if line and not line.startswith("#"):
+ for_spec(line)
+
def use_specfile(filename):
"""
- Load a file listing IESpecs into the cache of known IEs
+ Load a file listing IESpecs into the cache of known IEs.
- :param filename: name of file containing IESpecs to open
+ :param filename: path-like object or filename containing IESpecs to open
:raises: ValueError
-
"""
- with open(filename) as f:
- for line in f:
- for_spec(line)
+ with open(filename, encoding="utf-8") as f:
+ _load_spec_stream(f)
+
+
+def _use_package_specfile(name):
+ resource = importlib.resources.files("ipfix").joinpath(name)
+ with resource.open("r", encoding="utf-8") as f:
+ _load_spec_stream(f)
+
def use_iana_default():
"""
Load the module internal list of IANA registered IEs into the
cache of known IEs. Normally, client code should call this before
using any other part of this module.
-
"""
- use_specfile(os.path.join(os.path.dirname(__file__), "iana.iespec"))
+ _use_package_specfile("iana.iespec")
+
def use_5103_default():
"""
Load the module internal list of RFC 5103 reverse IEs for IANA
registered IEs into the cache of known IEs. Normally, biflow-aware
client code should call this just after use_iana_default().
-
"""
- use_specfile(os.path.join(os.path.dirname(__file__), "rfc5103.iespec"))
-
-def test_ie_internals():
- # Tests for full statement coverage of the ipfix.ie module
- # (not already covered in doctest or elsewhere)
- la = InformationElementList([InformationElement(None, 35566, 9999, length=1)])
- lb = InformationElementList([InformationElement(None, 35566, 9999, length=4)])
- lc = InformationElementList([InformationElement(None, 35566, 9998)])
-
- assert la[0].name == "_ipfix_35566_9999"
- assert la == lb
- assert la > lc
-
- try:
- for_spec("not a spec")
- assert False
- except ValueError as e:
- pass
-
- assert for_template_entry(35566,9999,4) == InformationElement(None, 35566, 9999, length=4)
+ _use_package_specfile("rfc5103.iespec")
diff --git a/ipfix/ieutils.py b/ipfix/ieutils.py
index e5da51f..e4c775e 100644
--- a/ipfix/ieutils.py
+++ b/ipfix/ieutils.py
@@ -1,5 +1,5 @@
#
-# python-ipfix (c) 2013 Brian Trammell.
+# python-ipfix (c) 2013-2026 Brian Trammell.
#
# Many thanks to the mPlane consortium (http://www.ict-mplane.eu) for
# its material support of this effort.
@@ -18,56 +18,113 @@
# this program. If not, see .
#
-from __future__ import with_statement
+"""
+Utilities for generating IESpec files from the IANA IPFIX Information Elements
+registry (CSV or XML) and deriving RFC 5103 reverse Information Elements.
+"""
+
+import csv
+import io
+import urllib.request as urlreq
import xml.etree.ElementTree as etree
-from warnings import warn
-from . import types, ie, compat
-from .compat import urlreq
-from io import open
+from . import ie, types
+
+IANA_CSV_URI = "https://www.iana.org/assignments/ipfix/ipfix-information-elements.csv"
+IANA_XML_URI = "https://www.iana.org/assignments/ipfix/ipfix.xml"
+
+# RFC 5103 §6.1: Information Elements that are not reversible (flow-key directional
+# identifiers, scope identifiers, etc.)
+_NON_REVERSIBLE_SUBSTRINGS = ("Source", "Destination", "source", "destination")
+_NON_REVERSIBLE_NAMES = frozenset({"messageScope"})
+
+
+def is_reversible_ie(name):
+ """Return True if an IANA IE name is eligible for an RFC 5103 reverse counterpart."""
+ if name in _NON_REVERSIBLE_NAMES:
+ return False
+ return not any(tok in name for tok in _NON_REVERSIBLE_SUBSTRINGS)
+
-def iana_xml_to_iespec(uri = "http://www.iana.org/assignments/ipfix/ipfix.xml"):
+def parse_iana_csv(csv_file):
+ """Parse an open text file/stream of the IANA IPFIX IE CSV into IESpec strings."""
iespecs = []
+ reader = csv.DictReader(csv_file)
+ for row in reader:
+ name = (row.get("Name") or "").strip()
+ typename = (row.get("Abstract Data Type") or "").strip()
+ num = (row.get("ElementID") or "").strip()
+ if not (name and typename and num.isdigit()):
+ continue
+ try:
+ ietype = types.for_name(typename)
+ except types.IpfixTypeError:
+ # Skip types not yet implemented (e.g. RFC 6313 structured data)
+ continue
+ iespecs.append(f"{name}({int(num)})<{ietype.name}>[{ietype.length}]")
+ return iespecs
+
- nsmap = { "iana" : "http://www.iana.org/assignments" }
+def iana_csv_to_iespec(uri=IANA_CSV_URI):
+ """Fetch the IANA IPFIX IE CSV over HTTPS and return a list of IESpec strings."""
+ with urlreq.urlopen(uri) as res:
+ text = io.TextIOWrapper(res, encoding="utf-8")
+ return parse_iana_csv(text)
- res = urlreq.urlopen(uri)
- root = etree.parse(res).getroot()
- for recelem in root.iterfind("iana:registry[@id='ipfix-information-elements']/iana:record", nsmap):
- (name, typename, num) = (None, None, None)
- for fieldelem in recelem.iter():
- if fieldelem.tag[-4:] == "name":
- name = fieldelem.text
- elif fieldelem.tag[-8:] == "dataType":
- typename = fieldelem.text
- elif fieldelem.tag[-9:] == "elementId":
- num = fieldelem.text
+def parse_iana_xml(xml_file):
+ """Parse an open binary/text file of the IANA IPFIX XML into IESpec strings."""
+ iespecs = []
+ ns = "http://www.iana.org/assignments"
+ nsmap = {"iana": ns}
+ tag_name = f"{{{ns}}}name"
+ tag_datatype = f"{{{ns}}}dataType"
+ tag_element_id = f"{{{ns}}}elementId"
+ root = etree.parse(xml_file).getroot()
+ for recelem in root.iterfind(
+ "iana:registry[@id='ipfix-information-elements']/iana:record", nsmap
+ ):
+ name = typename = num = None
+ for fieldelem in recelem:
+ if fieldelem.tag == tag_name:
+ name = (fieldelem.text or "").strip()
+ elif fieldelem.tag == tag_datatype:
+ typename = (fieldelem.text or "").strip()
+ elif fieldelem.tag == tag_element_id:
+ num = (fieldelem.text or "").strip()
- if name and typename and num:
+ if name and typename and num and num.isdigit():
try:
ietype = types.for_name(typename)
- iespecs.append("%s(%u)<%s>[%u]" % (name, int(num), ietype.name, ietype.length))
- except:
- pass
+ except types.IpfixTypeError:
+ continue
+ iespecs.append(f"{name}({int(num)})<{ietype.name}>[{ietype.length}]")
return iespecs
+def iana_xml_to_iespec(uri=IANA_XML_URI):
+ """Fetch the IANA IPFIX XML over HTTPS and return a list of IESpec strings."""
+ with urlreq.urlopen(uri) as res:
+ return parse_iana_xml(res)
+
+
def reverse_iespec(iespec):
- (name, pen, num, typename, length) = ie.parse_spec(iespec)
- revname = "reverse" + name[0].capitalize() + name[1:]
+ """Generate the RFC 5103 reverse counterpart IESpec for a given IESpec."""
+ name, pen, num, typename, length = ie.parse_spec(iespec)
+ revname = "reverse" + name[0].upper() + name[1:]
if pen:
num |= 0x4000
else:
pen = 29305
- return "%s(%u/%u)<%s>[%u]" % (revname, pen, num, typename, length)
+ return f"{revname}({pen}/{num})<{typename}>[{length}]"
def write_specfile(filename, iespecs):
- with open(filename, "w") as f:
+ """Write a sequence of IESpec strings to a file, one per line."""
+ with open(filename, "w", encoding="utf-8") as f:
for spec in iespecs:
f.write(spec)
f.write("\n")
diff --git a/ipfix/message.py b/ipfix/message.py
index 0af2fad..56d75fe 100644
--- a/ipfix/message.py
+++ b/ipfix/message.py
@@ -1,6 +1,5 @@
-# coding: utf8
#
-# python-ipfix (c) 2013 Brian Trammell.
+# python-ipfix (c) 2013-2026 Brian Trammell.
#
# Many thanks to the mPlane consortium (http://www.ict-mplane.eu) for
# its material support of this effort.
@@ -28,7 +27,6 @@
To create a message buffer:
->>> from __future__ import unicode_literals
>>> import ipfix.message
>>> msg = ipfix.message.MessageBuffer()
>>> msg
@@ -96,7 +94,7 @@
Variable-length information elements will be encoded using the native length
of the passed value:
->>> ipfix.ie.for_spec("myNewInformationElement(35566/1)") #doctest: +IGNORE_UNICODE
+>>> ipfix.ie.for_spec("myNewInformationElement(35566/1)")
InformationElement('myNewInformationElement', 35566, 1, ipfix.types.for_name('string'), 65535)
>>> tmpl = ipfix.template.from_ielist(257,
... ipfix.ie.spec_list(("flowStartMilliseconds",
@@ -152,7 +150,7 @@
... for key, value in unicode_recs:
... print("{}: {}".format(key, value))
...
->>> print_msg(msg) #doctest: +IGNORE_UNICODE
+>>> print_msg(msg)
[('destinationIPv4Address', IPv4Address('10.5.6.7')), ('flowStartMilliseconds', datetime.datetime(2013, 6, 21, 14, 0)), ('packetDeltaCount', 27), ('sourceIPv4Address', IPv4Address('10.1.2.3'))]
[('destinationIPv4Address', IPv4Address('10.12.13.14')), ('flowStartMilliseconds', datetime.datetime(2013, 6, 21, 14, 0, 2)), ('packetDeltaCount', 33), ('sourceIPv4Address', IPv4Address('10.8.9.11'))]
[('flowStartMilliseconds', datetime.datetime(2013, 6, 21, 14, 0, 4))]
@@ -172,7 +170,7 @@
(datetime.datetime(2013, 6, 21, 14, 0), 27)
(datetime.datetime(2013, 6, 21, 14, 0, 2), 33)
-Notice that the variable-length record written to the message are not returned
+Notice that the variable-length record written to the message is not returned
by this iterator, since that record doesn't include a packetDeltaCount IE.
The record is, however, still there:
@@ -184,41 +182,64 @@
"""
-from __future__ import unicode_literals
-from . import template, types, compat
-from .template import IpfixEncodeError, IpfixDecodeError
-from .compat import timezone, ifilter, reduce
-
import io
-import operator
import struct
-from datetime import datetime
+from datetime import UTC, datetime
from warnings import warn
+from . import template, types
+from .template import EndOfMessage, IpfixDecodeError, IpfixEncodeError
+
_sethdr_st = struct.Struct("!HH")
_msghdr_st = struct.Struct("!HHLLL")
-class EndOfMessage(Exception):
- """
- Exception raised when a write operation on a Message
- fails because there is not enough space in the message.
-
- """
- def __init__(self, *args):
- super(self.__class__, self).__init__(args)
def accept_all_templates(tmpl):
return True
-class MessageBuffer(object):
+
+def _is_zero_padding(buf, start, end):
+ return all(b == 0 for b in buf[start:end])
+
+
+def _iter_template_set_records(buf, offset, setend, setid, *, v9=False):
+ setview = buf[:setend]
+ label = "v9 template set" if v9 else "template set"
+ while offset < setend:
+ rem = setend - offset
+ # RFC 7011 §3.3.1: alignment padding at end of Template Set
+ if rem < template._tmplhdr_st.size:
+ if _is_zero_padding(buf, offset, setend):
+ break
+ raise IpfixDecodeError(f"Non-zero trailing bytes ({rem}) in {label}")
+ if (
+ buf[offset] == 0
+ and buf[offset + 1] == 0
+ and _is_zero_padding(buf, offset, setend)
+ ):
+ break
+
+ tmpl, offset = template.decode_template_from(
+ setview, offset, setid, setend=setend
+ )
+ yield tmpl
+
+
+def _recache_all_accepted_tids(templates, accepted_tids, tmplaccept_fn):
+ accepted_tids.clear()
+ for key, tmpl in templates.items():
+ if tmplaccept_fn(tmpl):
+ accepted_tids.add(key)
+
+
+class MessageBuffer:
"""
Implements a buffer for reading or writing IPFIX messages.
-
"""
+
def __init__(self, buf_sz=65536):
"""Create a new MessageBuffer instance."""
-
- self.mbuf = compat.get_buffer(bytearray(buf_sz))
+ self.mbuf = memoryview(bytearray(buf_sz))
self.length = 0
self.sequence = None
self.export_epoch = None
@@ -237,8 +258,9 @@ def __init__(self, buf_sz=65536):
self.curtmpl = None
self.last_tuple_iterator_ielist = None
+ self._accepted_cache_key = None
- self.mtu = 65535
+ self.mtu = min(65535, buf_sz)
self.template_record_hook = None
self.unknown_data_set_hook = None
@@ -247,27 +269,25 @@ def __init__(self, buf_sz=65536):
def __repr__(self):
if self.cursetid:
- addinf = " (writing set "+str(self.cursetid)+")"
+ addinf = f" (writing set {self.cursetid})"
elif self.setlist:
- addinf = " (deframed "+str(len(self.setlist))+" sets)"
+ addinf = f" (deframed {len(self.setlist)} sets)"
elif self.length:
addinf = " (writing)"
else:
addinf = ""
- return ""
+ return f""
def get_export_time(self):
"""
Return the export time of this message. When reading, returns the
export time as read from the message header. When writing, this is
the argument of the last call to :meth:`set_export_time`, or, if
- :attr:auto_export_time is True, the time of the last message
+ :attr:`auto_export_time` is True, the time of the last message
export.
:returns: export time of the last message read/written.
-
"""
return types._decode_sec(self.export_epoch)
@@ -277,17 +297,16 @@ def set_export_time(self, dt=None):
:meth:`write_message` or :meth:`to_bytes`. Disables automatic export
time updates. By default, sets the export time to the current time.
- :param dt: export time to set, as a datetime
-
+ :param dt: export time to set, as a datetime (aware or naive UTC)
"""
- if not dt:
- dt = datetime.utcnow()
+ if dt is None:
+ dt = datetime.now(UTC)
self.export_epoch = types._encode_sec(dt)
self.auto_export_time = False
def _increment_sequence(self):
- self.sequences.setdefault((self.odid, self.streamid), 0)
- self.sequences[(self.odid, self.streamid)] += 1
+ key = (self.odid, self.streamid)
+ self.sequences[key] = (self.sequences.get(key, 0) + 1) & 0xFFFFFFFF
def _scan_setlist(self):
# We've read a message. Discard all export state.
@@ -299,54 +318,55 @@ def _scan_setlist(self):
self.setlist = []
offset = _msghdr_st.size
- while (offset < self.length):
- (setid, setlen) = _sethdr_st.unpack_from(self.mbuf, offset)
+ while offset < self.length:
+ if offset + _sethdr_st.size > self.length:
+ raise IpfixDecodeError("Truncated set header at end of message")
+ setid, setlen = _sethdr_st.unpack_from(self.mbuf, offset)
+ if setlen < _sethdr_st.size:
+ raise IpfixDecodeError(f"Illegal set length {setlen} (must be >= 4)")
if offset + setlen > self.length:
raise IpfixDecodeError("Set too long for message")
self.setlist.append((offset, setid, setlen))
offset += setlen
def read_message(self, stream):
- """Read a IPFIX message from a stream.
+ """Read an IPFIX message from a stream.
This populates message header fields and the internal setlist.
Call for each new message before iterating over records when reading
from a stream.
:param stream: stream to read from
- :raises: IpfixDecodeError
-
+ :raises: IpfixDecodeError, EOFError
"""
-
# deframe and parse message header
msghdr = stream.read(_msghdr_st.size)
- if (len(msghdr) == 0):
+ if len(msghdr) == 0:
raise EOFError()
- elif (len(msghdr) < _msghdr_st.size):
- raise IpfixDecodeError("Short read in message header ("+
- str(len(msghdr)) +")")
+ if len(msghdr) < _msghdr_st.size:
+ raise IpfixDecodeError(f"Short read in message header ({len(msghdr)})")
- self.mbuf[0:_msghdr_st.size] = msghdr
- (version, self.length, self.export_epoch, self.sequence, self.odid) = \
- _msghdr_st.unpack_from(self.mbuf, 0)
+ self.mbuf[0 : _msghdr_st.size] = msghdr
+ (version, self.length, self.export_epoch, self.sequence, self.odid) = (
+ _msghdr_st.unpack_from(self.mbuf, 0)
+ )
# verify version and length
if version != 10:
- raise IpfixDecodeError("Illegal or unsupported version " +
- str(version))
+ raise IpfixDecodeError(f"Illegal or unsupported version {version}")
- if self.length < 20:
- raise IpfixDecodeError("Illegal message length" +
- str(self.length))
+ if self.length < 20 or self.length > len(self.mbuf):
+ raise IpfixDecodeError(f"Illegal message length {self.length}")
# read the rest of the message into the buffer
- msgbody = stream.read(self.length-_msghdr_st.size)
- if len(msgbody) < self.length - _msghdr_st.size:
- raise IpfixDecodeError("Short read in message body (got "+
- str(len(msgbody))+", expected "+
- str(self.length - _msghdr_st.size)+")")
- self.mbuf[_msghdr_st.size:self.length] = msgbody
-
+ bodylen = self.length - _msghdr_st.size
+ msgbody = stream.read(bodylen)
+ if len(msgbody) < bodylen:
+ raise IpfixDecodeError(
+ f"Short read in message body (got {len(msgbody)}, expected {bodylen})"
+ )
+ self.mbuf[_msghdr_st.size : self.length] = msgbody
+
# call the message header hook
if self.message_header_hook:
self.message_header_hook(self)
@@ -354,24 +374,92 @@ def read_message(self, stream):
# populate setlist
self._scan_setlist()
- def from_bytes(self, str_):
+ def from_bytes(self, data):
"""
- Read an IPFIX message from a byte array.
+ Read an IPFIX message from a bytes-like object.
This populates message header fields and the internal setlist.
Call for each new message before iterating over records when reading
from a byte array.
- :param bytes: a byte array containing a complete IPFIX message.
+ :param data: a bytes-like object containing a complete IPFIX message.
:raises: IpfixDecodeError
-
"""
- return self.read_message(io.BytesIO(str_))
-
- def record_iterator(self,
- decode_fn=template.Template.decode_namedict_from,
- tmplaccept_fn=accept_all_templates,
- recinf=None):
+ return self.read_message(io.BytesIO(data))
+
+ def _handle_template_withdrawal(self, setid, tid):
+ if tid == setid:
+ # All-Templates Withdrawal (RFC 7011 §8.1)
+ to_delete = [
+ k
+ for k, t in self.templates.items()
+ if k[0] == self.odid and t.native_setid() == setid
+ ]
+ for k in to_delete:
+ del self.templates[k]
+ self.accepted_tids.discard(k)
+ else:
+ key = (self.odid, tid)
+ self.templates.pop(key, None)
+ self.accepted_tids.discard(key)
+
+ def _iter_records(self, decode_fn, tmplaccept_fn, recinf):
+ for offset, setid, setlen in self.setlist:
+ setend = offset + setlen
+ setview = self.mbuf[:setend]
+ offset += _sethdr_st.size # skip set header in decode
+ if setid in (template.TEMPLATE_SET_ID, template.OPTIONS_SET_ID):
+ for tmpl in _iter_template_set_records(
+ self.mbuf, offset, setend, setid, v9=False
+ ):
+ if tmpl.count() == 0:
+ self._handle_template_withdrawal(setid, tmpl.tid)
+ else:
+ key = (self.odid, tmpl.tid)
+ self.templates[key] = tmpl
+ if tmplaccept_fn(tmpl):
+ self.accepted_tids.add(key)
+ else:
+ self.accepted_tids.discard(key)
+
+ if self.template_record_hook:
+ self.template_record_hook(self, tmpl)
+
+ elif setid < 256:
+ warn("skipping illegal set id " + str(setid), stacklevel=2)
+ else:
+ key = (self.odid, setid)
+ try:
+ tmpl = self.templates[key]
+ except KeyError:
+ if self.unknown_data_set_hook:
+ self.unknown_data_set_hook(
+ self, self.mbuf[offset - _sethdr_st.size : setend]
+ )
+ continue
+
+ if key in self.accepted_tids:
+ if tmpl.minlength <= 0:
+ raise IpfixDecodeError(
+ f"Template {tmpl.tid} has zero minimum record length"
+ )
+ while offset + tmpl.minlength <= setend:
+ rec, offset = decode_fn(
+ tmpl, setview, offset, recinf=recinf
+ )
+ yield rec
+ self._increment_sequence()
+ elif self.ignored_data_set_hook:
+ self.ignored_data_set_hook(
+ self, tmpl, self.mbuf[offset - _sethdr_st.size : setend]
+ )
+
+ def record_iterator(
+ self,
+ decode_fn=template.Template.decode_namedict_from,
+ tmplaccept_fn=accept_all_templates,
+ recinf=None,
+ ):
"""
Low-level interface to record iteration.
@@ -379,7 +467,7 @@ def record_iterator(self,
:meth:`read_message()` or :meth:`from_bytes()`. Automatically handles
templates in set order. By default, iterates over each record in the
stream as a dictionary mapping IE name to value
- (i.e., the same as :meth:`namedict_iterator`)
+ (i.e., the same as :meth:`namedict_iterator`).
:param decode_fn: Function used to decode a record;
must be an (unbound) "decode" instance method of the
@@ -391,46 +479,17 @@ def record_iterator(self,
will be skipped.
:param recinf: Record information opaquely passed to decode function
:returns: an iterator over records decoded by decode_fn.
-
"""
- for (offset, setid, setlen) in self.setlist:
- setend = offset + setlen
- offset += _sethdr_st.size # skip set header in decode
- if setid == template.TEMPLATE_SET_ID or\
- setid == template.OPTIONS_SET_ID:
- while offset < setend:
- (tmpl, offset) = template.decode_template_from(
- self.mbuf, offset, setid)
- # FIXME handle withdrawal
- self.templates[(self.odid, tmpl.tid)] = tmpl
- if tmplaccept_fn(tmpl):
- self.accepted_tids.add((self.odid, tmpl.tid))
- else:
- self.accepted_tids.discard((self.odid, tmpl.tid))
+ if tmplaccept_fn is accept_all_templates:
+ if self._accepted_cache_key != "all":
+ self._recache_accepted_tids(accept_all_templates)
+ self._accepted_cache_key = "all"
+ self.last_tuple_iterator_ielist = None
+ else:
+ self._recache_accepted_tids(tmplaccept_fn)
+ self._accepted_cache_key = None
- if self.template_record_hook:
- self.template_record_hook(self, tmpl)
-
- elif setid < 256:
- warn("skipping illegal set id "+str(setid))
- else:
- try:
- tmpl = self.templates[(self.odid, setid)]
- if (self.odid, setid) in self.accepted_tids:
- while offset + tmpl.minlength <= setend:
- (rec, offset) = decode_fn(tmpl, self.mbuf, offset,
- recinf = recinf)
- yield rec
- self._increment_sequence()
- elif self.ignored_data_set_hook:
- # not in accepted tids - ignored data set
- self.ignored_data_set_hook(self, tmpl,
- self.mbuf[offset-_sethdr_st.size:setend])
- except KeyError as e:
- if self.unknown_data_set_hook:
- # KeyError on template lookup - unknown data set
- self.unknown_data_set_hook(self,
- self.mbuf[offset-_sethdr_st.size:setend])
+ return self._iter_records(decode_fn, tmplaccept_fn, recinf)
def namedict_iterator(self):
"""
@@ -438,18 +497,17 @@ def namedict_iterator(self):
to values.
:returns: a name dictionary iterator
-
"""
-
- return self.record_iterator(
- decode_fn = template.Template.decode_namedict_from)
+ if self._accepted_cache_key != "all":
+ self._recache_accepted_tids(accept_all_templates)
+ self._accepted_cache_key = "all"
+ self.last_tuple_iterator_ielist = None
+ return self._iter_records(
+ template.Template.decode_namedict_from, accept_all_templates, None
+ )
def _recache_accepted_tids(self, tmplaccept_fn):
- for tid in self.active_template_ids():
- if tmplaccept_fn(self.templates[(self.odid, tid)]):
- self.accepted_tids.add((self.odid, tid))
- else:
- self.accepted_tids.discard((self.odid, tid))
+ _recache_all_accepted_tids(self.templates, self.accepted_tids, tmplaccept_fn)
def tuple_iterator(self, ielist):
"""
@@ -459,46 +517,47 @@ def tuple_iterator(self, ielist):
:param ielist: an instance of :class:`ipfix.ie.InformationElementList`
listing IEs to return as a tuple
:returns: a tuple iterator for tuples as in ielist order
-
"""
+ def tmplaccept_fn(tmpl):
+ return all(elem in tmpl.ies for elem in ielist)
- tmplaccept_fn = lambda tmpl: \
- reduce(operator.__and__,
- (ie in tmpl.ies for ie in ielist))
-
- if ((not self.last_tuple_iterator_ielist) or
- (ielist is not self.last_tuple_iterator_ielist)):
- self._recache_accepted_tids(tmplaccept_fn)
+ cache_key = tuple(ielist)
+ if self._accepted_cache_key != cache_key:
+ self._recache_accepted_tids(tmplaccept_fn)
+ self._accepted_cache_key = cache_key
self.last_tuple_iterator_ielist = ielist
- return self.record_iterator(
- decode_fn = template.Template.decode_tuple_from,
- tmplaccept_fn = tmplaccept_fn,
- recinf = ielist)
+ return self._iter_records(
+ template.Template.decode_tuple_from, tmplaccept_fn, ielist
+ )
def to_bytes(self):
"""
- Convert this MessageBuffer to a byte array, suitable for writing
+ Convert this MessageBuffer to a bytes object, suitable for writing
to a binary file, socket, or datagram. Finalizes the message by
- rewriting the message header with current length, and export time.
-
- :returns: message as a byte array
+ rewriting the message header with current length and export time.
+ :returns: message as bytes
"""
-
# Close final set
self._export_close_set()
# Update export time if necessary
if self.auto_export_time:
- dt = datetime.utcnow().replace(tzinfo=timezone.utc)
- self.export_epoch = int(compat.datetime_to_timestamp(dt))
+ self.export_epoch = int(datetime.now(UTC).timestamp())
# Update message header in buffer
- _msghdr_st.pack_into(self.mbuf, 0, 10, self.length,
- self.export_epoch, self.sequence, self.odid)
-
- return self.mbuf[0:self.length].tobytes()
+ _msghdr_st.pack_into(
+ self.mbuf,
+ 0,
+ 10,
+ self.length,
+ self.export_epoch,
+ self.sequence,
+ self.odid,
+ )
+
+ return self.mbuf[0 : self.length].tobytes()
def write_message(self, stream):
"""
@@ -517,6 +576,7 @@ def add_template(self, tmpl, export=True):
:raises: EndOfMessage
"""
self.templates[(self.odid, tmpl.tid)] = tmpl
+ self._accepted_cache_key = None
if export:
self.export_template(tmpl.tid)
@@ -530,14 +590,17 @@ def delete_template(self, tid, export=True):
:param tid: ID of the template to delete
:param export: if True, export a Template Withdrawal for this
- Template after deleting it
- :raises: EndOfMessage
-
+ Template before deleting it
+ :raises: EndOfMessage, KeyError
"""
- setid = self.templates[self.odid, tid].native_setid()
- del(self.templates[self.odid, tid])
+ key = (self.odid, tid)
+ setid = self.templates[key].native_setid()
if export:
- self.export_template_withdrawal(setid, tid)
+ self._export_template_withdrawal(setid, tid)
+ elif self.cursetid == tid:
+ self._export_close_set()
+ del self.templates[key]
+ self.accepted_tids.discard(key)
def active_template_ids(self):
"""
@@ -546,10 +609,10 @@ def active_template_ids(self):
multiple Messages.
:returns: a template ID iterator
-
"""
- for tk in ifilter(lambda k: k[0] == self.odid, self.templates):
- yield tk[1]
+ for odid, tid in self.templates:
+ if odid == self.odid:
+ yield tid
def template_for_id(self, tid):
"""
@@ -558,7 +621,6 @@ def template_for_id(self, tid):
:param tid: template ID to get
:returns: the template
:raises: KeyError
-
"""
return self.templates[(self.odid, tid)]
@@ -573,29 +635,28 @@ def begin_export(self, odid=None):
templates will need to be added after switching to a new
observation domain ID.
:raises: IpfixEncodeError
-
"""
# We're exporting. Clear setlist from any previously read message.
self.setlist = []
- # Set sequence number
- self.sequences.setdefault((self.odid, self.streamid), 0) # FIXME why do we need this?
- self.sequence = self.sequences[(self.odid, self.streamid)]
-
- # set new domain if necessary
- if odid:
+ # Set new domain before looking up sequence number
+ if odid is not None:
self.odid = odid
+ # Set sequence number for current domain/stream
+ self.sequence = self.sequences.setdefault((self.odid, self.streamid), 0)
+
# reset message and zero header
self.length = _msghdr_st.size
self.cursetoff = self.length
- self.mbuf[0:_msghdr_st.size] = bytearray([0] * _msghdr_st.size)
+ self.mbuf[0 : _msghdr_st.size] = bytes(_msghdr_st.size)
if self.mtu <= self.length:
- raise IpfixEncodeError("MTU too small: "+str(self.mtu))
+ raise IpfixEncodeError("MTU too small: " + str(self.mtu))
# no current set
self.cursetid = None
+ self.curtmpl = None
def export_new_set(self, setid):
"""
@@ -605,19 +666,19 @@ def export_new_set(self, setid):
:param setid: Set ID of the new Set; corresponds to the Template ID of
the Template that will be used to encode records into the
- Set. The require Template must have already been added
+ Set. The required Template must have already been added
to the MessageBuffer, see :meth:`add_template`.
:raises: IpfixEncodeError, EndOfMessage
-
"""
# close current set if any
self._export_close_set()
if setid >= 256:
# make sure we have a template for the set
- if not ((self.odid, setid) in self.templates):
- raise IpfixEncodeError("can't start set without template id " +
- str(setid))
+ if (self.odid, setid) not in self.templates:
+ raise IpfixEncodeError(
+ "can't start set without template id " + str(setid)
+ )
# make sure we have room to export at least one record
tmpl = self.templates[(self.odid, setid)]
@@ -625,6 +686,8 @@ def export_new_set(self, setid):
raise EndOfMessage()
else:
# special Set ID. no template
+ if self.length + _sethdr_st.size > self.mtu:
+ raise EndOfMessage()
tmpl = None
# set up new set
@@ -637,14 +700,13 @@ def export_new_set(self, setid):
def export_ensure_set(self, setid):
"""
Ensure that the current set for export has the given Set ID.
- Starts a new set if not using :meth:`export_new_set`
+ Starts a new set if not using :meth:`export_new_set`.
:param setid: Set ID of the new Set; corresponds to the Template ID of
the Template that will be used to encode records into the
- Set. The require Template must have already been added
+ Set. The required Template must have already been added
to the MessageBuffer, see :meth:`add_template`.
:raises: IpfixEncodeError, EndOfMessage
-
"""
if self.cursetid != setid:
self.export_new_set(setid)
@@ -652,20 +714,32 @@ def export_ensure_set(self, setid):
def export_needs_flush(self):
"""
True if content has been written to this MessageBuffer since the
- last call to :meth:`begin_export`
-
+ last call to :meth:`begin_export`.
"""
- # FIXME we don't prewrite a set, do we?
- if self.length <= _msghdr_st.size + _sethdr_st.size:
- return False
- else:
- return True
+ return self.length > _msghdr_st.size + _sethdr_st.size
def _export_close_set(self):
- if self.cursetid:
- _sethdr_st.pack_into(self.mbuf, self.cursetoff,
- self.cursetid, self.length - self.cursetoff)
+ if self.cursetid is not None:
+ if self.length == self.cursetoff + _sethdr_st.size:
+ self.length = self.cursetoff
+ else:
+ _sethdr_st.pack_into(
+ self.mbuf,
+ self.cursetoff,
+ self.cursetid,
+ self.length - self.cursetoff,
+ )
self.cursetid = None
+ self.curtmpl = None
+
+ def _effective_length_for_set(self, setid):
+ if (
+ self.cursetid is not None
+ and self.cursetid != setid
+ and self.length == self.cursetoff + _sethdr_st.size
+ ):
+ return self.cursetoff
+ return self.length
def export_template(self, tid):
"""
@@ -674,31 +748,41 @@ def export_template(self, tid):
:param tid: ID of template to export; must have been added to this
message previously with :meth:`add_template`.
:raises: EndOfMessage, KeyError
-
"""
-
tmpl = self.templates[(self.odid, tid)]
+ setid = tmpl.native_setid()
+ hdrlen = (
+ template._otmplhdr_st.size
+ if setid == template.OPTIONS_SET_ID
+ else template._tmplhdr_st.size
+ )
+ sethdr_needed = 0 if self.cursetid == setid else _sethdr_st.size
+ base_len = self._effective_length_for_set(setid)
+
+ if base_len + sethdr_needed + hdrlen + tmpl.enclength > self.mtu:
+ raise EndOfMessage()
- self.export_ensure_set(tmpl.native_setid())
-
- if self.length + tmpl.enclength > self.mtu:
- raise EndOfMessage
-
- self.length = tmpl.encode_template_to(self.mbuf, self.length,
- tmpl.native_setid())
+ self.export_ensure_set(setid)
+ self.length = tmpl.encode_template_to(self.mbuf, self.length, setid)
def _export_template_withdrawal(self, setid, tid):
- self.export_ensure_set(setid)
+ sethdr_needed = 0 if self.cursetid == setid else _sethdr_st.size
+ base_len = self._effective_length_for_set(setid)
- if self.length + template.withdrawal_length(setid) > self.mtu:
- raise EndOfMessage
+ if base_len + sethdr_needed + template.withdrawal_length(setid) > self.mtu:
+ raise EndOfMessage()
- self.length = template.encode_withdrawal_to(self.mbuf, self.length,
- setid, tid)
+ self.export_ensure_set(setid)
+ self.length = template.encode_withdrawal_to(
+ self.mbuf, self.length, setid, tid
+ )
- def export_record(self, rec,
- encode_fn=template.Template.encode_namedict_to,
- recinf = None):
+ def export_record(
+ self,
+ rec,
+ encode_fn=template.Template.encode_namedict_to,
+ recinf=None,
+ ):
"""
Low-level interface to record export.
@@ -711,17 +795,20 @@ def export_record(self, rec,
:param encode_fn: Function used to encode a record;
must be an (unbound) "encode" instance method of the
:class:`ipfix.template.Template` class.
- :param recinf: Record information opaquely passed to decode function
- :raises: EndOfMessage
-
+ :param recinf: Record information opaquely passed to encode function
+ :raises: EndOfMessage, IpfixEncodeError
"""
+ if self.curtmpl is None:
+ raise IpfixEncodeError("no active data set for record export")
savelength = self.length
try:
- self.length = encode_fn(self.curtmpl, self.mbuf, self.length, rec, recinf)
- except struct.error: # out of bounds on the underlying mbuf
+ self.length = encode_fn(
+ self.curtmpl, self.mbuf, self.length, rec, recinf
+ )
+ except Exception:
self.length = savelength
- raise EndOfMessage()
+ raise
# check for mtu overrun
if self.length > self.mtu:
@@ -739,7 +826,6 @@ def export_namedict(self, rec):
:param rec: the record to export, as a dictionary
:raises: EndOfMessage
-
"""
self.export_record(rec, template.Template.encode_namedict_to)
@@ -750,6 +836,5 @@ def export_tuple(self, rec):
:param rec: the record to export, as a tuple in template order.
:raises: EndOfMessage
-
"""
self.export_record(rec, template.Template.encode_tuple_to)
diff --git a/ipfix/reader.py b/ipfix/reader.py
index 7dcaae4..c855344 100644
--- a/ipfix/reader.py
+++ b/ipfix/reader.py
@@ -1,5 +1,5 @@
#
-# python-ipfix (c) 2013 Brian Trammell.
+# python-ipfix (c) 2013-2026 Brian Trammell.
#
# Many thanks to the mPlane consortium (http://www.ict-mplane.eu) for
# its material support of this effort.
@@ -20,12 +20,12 @@
"""
Interface to read IPFIX Messages from a stream.
-
"""
from . import message
-class MessageStreamReader(object):
+
+class MessageStreamReader:
"""
Reads records from a stream of IPFIX messages.
@@ -34,10 +34,10 @@ class MessageStreamReader(object):
until the end of the stream. Use :func:`from_stream` to get an instance.
Suitable for reading from IPFIX files (see :rfc:`5655`) as well as from
- UDP or TCP sockets with :class:`socketserver.StreamRequestHandler`.
+ TCP sockets with :class:`socketserver.StreamRequestHandler`.
When opening a stream from a file, use mode='rb'.
-
"""
+
def __init__(self, stream):
self.stream = stream
self.msg = message.MessageBuffer()
@@ -49,14 +49,12 @@ def namedict_iterator(self):
to values.
:returns: a name dictionary iterator
-
"""
try:
- while(True):
+ while True:
self.msg.read_message(self.stream)
- for name in self.msg.namedict_iterator():
- yield name
- self.msgcount += 1
+ self.msgcount += 1
+ yield from self.msg.namedict_iterator()
except EOFError:
return
@@ -67,23 +65,22 @@ def tuple_iterator(self, ielist):
:param ielist: an instance of :class:`ipfix.ie.InformationElementList`
listing IEs to return as a tuple
- :returns: a tuple iterator for tuples in ielist order
+ :returns: a tuple iterator for tuples as in ielist order
"""
try:
- while(True):
+ while True:
self.msg.read_message(self.stream)
- for tuple_ in self.msg.tuple_iterator(ielist):
- yield tuple_
- self.msgcount += 1
+ self.msgcount += 1
+ yield from self.msg.tuple_iterator(ielist)
except EOFError:
return
+
def from_stream(stream):
"""
- Get a MessageStreamReader for a given stream
+ Get a MessageStreamReader for a given stream.
:param stream: stream to read
:return: a :class:`MessageStreamReader` wrapped around the stream.
-
"""
return MessageStreamReader(stream)
diff --git a/ipfix/rfc5103.iespec b/ipfix/rfc5103.iespec
index e272559..06318e4 100644
--- a/ipfix/rfc5103.iespec
+++ b/ipfix/rfc5103.iespec
@@ -5,9 +5,6 @@ reverseProtocolIdentifier(29305/4)[1]
reverseIpClassOfService(29305/5)[1]
reverseTcpControlBits(29305/6)[2]
reverseIngressInterface(29305/10)[4]
-reverseDestinationTransportPort(29305/11)[2]
-reverseDestinationIPv4Address(29305/12)[4]
-reverseDestinationIPv4PrefixLength(29305/13)[1]
reverseEgressInterface(29305/14)[4]
reverseIpNextHopIPv4Address(29305/15)[4]
reverseBgpNextHopIPv4Address(29305/18)[4]
@@ -220,7 +217,7 @@ reverseCollectorCertificate(29305/274)[65535]
reverseExporterCertificate(29305/275)[65535]
reverseDataRecordsReliability(29305/276)[1]
reverseObservationPointType(29305/277)[1]
-reverseConnectionCountNew(29305/278)[4]
+reverseNewConnectionDeltaCount(29305/278)[4]
reverseConnectionSumDurationSeconds(29305/279)[8]
reverseConnectionTransactionId(29305/280)[8]
reverseNatPoolId(29305/283)[4]
@@ -359,5 +356,86 @@ reverseLayer2OctetDeltaSumOfSquares(29305/428)[8]
reverseLayer2OctetTotalSumOfSquares(29305/429)[8]
reverseLayer2FrameDeltaCount(29305/430)[8]
reverseLayer2FrameTotalCount(29305/431)[8]
-reversePseudoWireDestinationIPv4Address(29305/432)[4]
-reverseIgnoredLayer2FrameTotalCount(29305/433)[8]
\ No newline at end of file
+reverseIgnoredLayer2FrameTotalCount(29305/433)[8]
+reverseMibObjectValueInteger(29305/434)[4]
+reverseMibObjectValueOctetString(29305/435)[65535]
+reverseMibObjectValueOID(29305/436)[65535]
+reverseMibObjectValueBits(29305/437)[65535]
+reverseMibObjectValueIPAddress(29305/438)[4]
+reverseMibObjectValueCounter(29305/439)[8]
+reverseMibObjectValueGauge(29305/440)[4]
+reverseMibObjectValueTimeTicks(29305/441)[4]
+reverseMibObjectValueUnsigned(29305/442)[4]
+reverseMibObjectIdentifier(29305/445)[65535]
+reverseMibSubIdentifier(29305/446)[4]
+reverseMibIndexIndicator(29305/447)[8]
+reverseMibCaptureTimeSemantics(29305/448)[1]
+reverseMibContextEngineID(29305/449)[65535]
+reverseMibContextName(29305/450)[65535]
+reverseMibObjectName(29305/451)[65535]
+reverseMibObjectDescription(29305/452)[65535]
+reverseMibObjectSyntax(29305/453)[65535]
+reverseMibModuleName(29305/454)[65535]
+reverseMobileIMSI(29305/455)[65535]
+reverseMobileMSISDN(29305/456)[65535]
+reverseHttpStatusCode(29305/457)[2]
+reverseHttpRequestMethod(29305/459)[65535]
+reverseHttpRequestHost(29305/460)[65535]
+reverseHttpRequestTarget(29305/461)[65535]
+reverseHttpMessageVersion(29305/462)[65535]
+reverseNatInstanceID(29305/463)[4]
+reverseInternalAddressRealm(29305/464)[65535]
+reverseExternalAddressRealm(29305/465)[65535]
+reverseNatQuotaExceededEvent(29305/466)[4]
+reverseNatThresholdEvent(29305/467)[4]
+reverseHttpUserAgent(29305/468)[65535]
+reverseHttpContentType(29305/469)[65535]
+reverseHttpReasonPhrase(29305/470)[65535]
+reverseMaxSessionEntries(29305/471)[4]
+reverseMaxBIBEntries(29305/472)[4]
+reverseMaxEntriesPerUser(29305/473)[4]
+reverseMaxSubscribers(29305/474)[4]
+reverseMaxFragmentsPendingReassembly(29305/475)[4]
+reverseAddressPoolHighThreshold(29305/476)[4]
+reverseAddressPoolLowThreshold(29305/477)[4]
+reverseAddressPortMappingHighThreshold(29305/478)[4]
+reverseAddressPortMappingLowThreshold(29305/479)[4]
+reverseAddressPortMappingPerUserHighThreshold(29305/480)[4]
+reverseGlobalAddressMappingHighThreshold(29305/481)[4]
+reverseVpnIdentifier(29305/482)[65535]
+reverseBgpCommunity(29305/483)[4]
+reverseBgpExtendedCommunity(29305/486)[65535]
+reverseBgpLargeCommunity(29305/489)[65535]
+reverseSrhFlagsIPv6(29305/492)[1]
+reverseSrhTagIPv6(29305/493)[2]
+reverseSrhSegmentIPv6(29305/494)[16]
+reverseSrhActiveSegmentIPv6(29305/495)[16]
+reverseSrhSegmentIPv6ListSection(29305/497)[65535]
+reverseSrhSegmentsIPv6Left(29305/498)[1]
+reverseSrhIPv6Section(29305/499)[65535]
+reverseSrhIPv6ActiveSegmentType(29305/500)[1]
+reverseSrhSegmentIPv6LocatorLength(29305/501)[1]
+reverseSrhSegmentIPv6EndpointBehavior(29305/502)[2]
+reverseTransportChecksum(29305/503)[2]
+reverseIcmpHeaderPacketSection(29305/504)[65535]
+reverseGtpuFlags(29305/505)[1]
+reverseGtpuMsgType(29305/506)[1]
+reverseGtpuTEid(29305/507)[4]
+reverseGtpuSequenceNum(29305/508)[2]
+reverseGtpuQFI(29305/509)[1]
+reverseGtpuPduType(29305/510)[1]
+reverseIpv6ExtensionHeaderType(29305/513)[1]
+reverseIpv6ExtensionHeaderCount(29305/514)[1]
+reverseIpv6ExtensionHeadersFull(29305/515)[32]
+reverseIpv6ExtensionHeadersLimit(29305/517)[1]
+reverseIpv6ExtensionHeadersChainLength(29305/518)[4]
+reverseTcpOptionsFull(29305/520)[32]
+reverseTcpSharedOptionExID16(29305/521)[2]
+reverseTcpSharedOptionExID32(29305/522)[4]
+reverseUdpSafeOptions(29305/525)[32]
+reverseUdpUnsafeOptions(29305/526)[8]
+reverseUdpExID(29305/527)[2]
+reversePathDelayMeanDeltaMicroseconds(29305/530)[4]
+reversePathDelayMinDeltaMicroseconds(29305/531)[4]
+reversePathDelayMaxDeltaMicroseconds(29305/532)[4]
+reversePathDelaySumDeltaMicroseconds(29305/533)[8]
diff --git a/ipfix/template.py b/ipfix/template.py
index 1203e55..9155345 100644
--- a/ipfix/template.py
+++ b/ipfix/template.py
@@ -1,5 +1,5 @@
#
-# python-ipfix (c) 2013 Brian Trammell.
+# python-ipfix (c) 2013-2026 Brian Trammell.
#
# Many thanks to the mPlane consortium (http://www.ict-mplane.eu) for
# its material support of this effort.
@@ -28,27 +28,55 @@
See :mod:`ipfix.message` for examples.
"""
-from . import ie, types, compat
-from .compat import izip, xrange, lru_cache
import struct
+from . import ie, types
+
# Builtin exceptions
class IpfixEncodeError(Exception):
"""Raised on internal encoding errors, or if message MTU is too small"""
- def __init__(self, *args):
- super(self.__class__, self).__init__(args)
+
class IpfixDecodeError(Exception):
"""Raised when decoding a malformed IPFIX message"""
- def __init__(self, *args):
- super(self.__class__, self).__init__(args)
+
+
+class EndOfMessage(Exception):
+ """
+ Exception raised when a write operation on a Message
+ fails because there is not enough space in the message.
+ """
+
# constants for v9
V9_TEMPLATE_SET_ID = 0
V9_OPTIONS_SET_ID = 1
+_V9_SCOPE_NAMES = {
+ 1: "v9ScopeSystem",
+ 2: "v9ScopeInterface",
+ 3: "v9ScopeLineCard",
+ 4: "v9ScopeCache",
+ 5: "v9ScopeTemplate",
+}
+
+
+class _V9ScopeIE(ie.InformationElement):
+ """NetFlow v9 Options Template scope field (distinct namespace from IANA IEs)."""
+
+ def __eq__(self, other):
+ if isinstance(other, _V9ScopeIE):
+ return self.num == other.num
+ if isinstance(other, ie.InformationElement):
+ return False
+ return NotImplemented
+
+ def __hash__(self):
+ return hash(("v9scope", self.num))
+
+
# constants
TEMPLATE_SET_ID = 2
OPTIONS_SET_ID = 3
@@ -59,16 +87,19 @@ def __init__(self, *args):
_iespec_st = struct.Struct("!HH")
_iepen_st = struct.Struct("!L")
-class TemplatePackingPlan(object):
+
+class TemplatePackingPlan:
"""
Plan to pack/unpack a specific set of indices for a template.
Used internally by Templates for efficient encoding and decoding.
"""
+
def __init__(self, tmpl, indices):
self.tmpl = tmpl
self.indices = indices
- self.ranks = sorted(xrange(len(indices)), key=indices.__getitem__)
+ self.index_set = frozenset(indices)
+ self.ranks = sorted(range(len(indices)), key=indices.__getitem__)
self.valenc = []
self.valdec = []
@@ -76,7 +107,7 @@ def __init__(self, tmpl, indices):
for i, t in enumerate(e.type for e in tmpl.ies):
if i >= tmpl.fixlen_count():
break
- if i in indices:
+ if i in self.index_set:
packstring += t.stel
self.valenc.append(t.valenc)
self.valdec.append(t.valdec)
@@ -86,20 +117,26 @@ def __init__(self, tmpl, indices):
self.st = struct.Struct(packstring)
def __repr__(self):
- return ""
+ return (
+ f""
+ )
-class Template(object):
+
+class Template:
"""
An IPFIX Template.
A template is an ordered list of IPFIX Information Elements with an ID.
"""
- def __init__(self, tid = 0, iterable = None):
- if tid < 256 or tid > 65535:
- raise ValueError("bad template ID "+str(tid))
+
+ def __init__(self, tid=0, iterable=None, *, _allow_withdrawal_tid=False):
+ if _allow_withdrawal_tid:
+ if not (tid in (TEMPLATE_SET_ID, OPTIONS_SET_ID) or 256 <= tid <= 65535):
+ raise ValueError("bad template ID " + str(tid))
+ elif tid < 256 or tid > 65535:
+ raise ValueError("bad template ID " + str(tid))
self.tid = tid
self.minlength = 0
@@ -107,6 +144,7 @@ def __init__(self, tid = 0, iterable = None):
self.scopecount = 0
self.varlenslice = None
self.packplan = None
+ self._packplan_cache = {}
self.ies = []
if iterable:
@@ -116,38 +154,45 @@ def __init__(self, tid = 0, iterable = None):
self.append(elem)
def __repr__(self):
- return ""
+ return (
+ f""
+ )
def identical_to(self, other):
"""
Determine if two templates are identical to each other.
Two templates are considered identical if they contain the same
- IEs in the same order, and the same scope count. Template ID
- is not considered as part of the test for template identity.
+ IEs (with the same lengths) in the same order, and the same scope count.
+ Template ID is not considered as part of the test for template identity.
"""
-
- # FIXME this needs to check IE lengths as well
- return (self.ies == other.ies) and (self.scopecount == other.scopecount)
-
- def append(self, ie):
- """Append an IE to this Template"""
- self.ies.append(ie)
-
- if ie.length == types.VARLEN:
+ return (
+ self.scopecount == other.scopecount
+ and len(self.ies) == len(other.ies)
+ and all(
+ (isinstance(a, _V9ScopeIE), a.pen, a.num, a.length)
+ == (isinstance(b, _V9ScopeIE), b.pen, b.num, b.length)
+ for a, b in zip(self.ies, other.ies, strict=True)
+ )
+ )
+
+ def append(self, elem):
+ """Append an IE to this Template."""
+ self.ies.append(elem)
+
+ if elem.length == types.VARLEN:
self.minlength += 1
if self.varlenslice is None:
self.varlenslice = len(self.ies) - 1
else:
- self.minlength += ie.length
+ self.minlength += elem.length
self.enclength += _iespec_st.size
- if (ie.pen):
+ if elem.pen:
self.enclength += _iepen_st.size
def count(self):
- """Count IEs in this template"""
+ """Count IEs in this template."""
return len(self.ies)
def fixlen_count(self):
@@ -155,120 +200,166 @@ def fixlen_count(self):
Count of fixed-length IEs in this template before the first
variable-length IE; this is the size of the portion of the template
which can be encoded/decoded efficiently.
-
"""
if self.varlenslice is not None:
return self.varlenslice
- else:
- return self.count()
+ return self.count()
def finalize(self):
"""Compile a default packing plan. Called after append()ing all IEs."""
- self.packplan = TemplatePackingPlan(self, xrange(self.count()))
+ self.packplan = TemplatePackingPlan(self, range(self.count()))
- @lru_cache(maxsize = 32)
def packplan_for_ielist(self, ielist):
"""
Given a list of IEs, devise and cache a packing plan.
Used by the tuple interfaces.
-
"""
- return TemplatePackingPlan(self, [self.ies.index(ie) for ie in ielist])
-
- def decode_from(self, buf, offset, packplan = None):
- """Decodes a record into a tuple containing values in template order"""
+ plan = self._packplan_cache.get(ielist)
+ if plan is None:
+ if len(self._packplan_cache) >= 32:
+ self._packplan_cache.clear()
+ plan = TemplatePackingPlan(self, [self.ies.index(elem) for elem in ielist])
+ self._packplan_cache[ielist] = plan
+ return plan
+
+ def decode_from(self, buf, offset, packplan=None, setend=None):
+ """Decodes a record into a list containing values in template order."""
+ limit = len(buf) if setend is None else min(setend, len(buf))
# use default packplan unless someone hacked us not to
if not packplan:
packplan = self.packplan
+ if offset + packplan.st.size > limit:
+ raise IpfixDecodeError("Data record extends past end of set")
+
# decode fixed values
- vals = [f(v) for f, v in izip(packplan.valdec, packplan.st.unpack_from(buf, offset))]
+ try:
+ vals = [
+ f(v)
+ for f, v in zip(
+ packplan.valdec, packplan.st.unpack_from(buf, offset), strict=True
+ )
+ ]
+ except (struct.error, ValueError, UnicodeDecodeError) as exc:
+ raise IpfixDecodeError(f"Failed to decode fixed record field: {exc}") from exc
offset += packplan.st.size
# short circuit on no varlen
- if not self.varlenslice:
+ if self.varlenslice is None:
return (vals, offset)
# direct iteration over remaining IEs
- for i, ie in izip(xrange(self.varlenslice, self.count()),
- self.ies[self.varlenslice:]):
- length = ie.length
+ for i, elem in zip(
+ range(self.varlenslice, self.count()),
+ self.ies[self.varlenslice :],
+ strict=True,
+ ):
+ length = elem.length
if length == types.VARLEN:
- (length, offset) = types.decode_varlen(buf, offset)
- if i in packplan.indices:
- vals.append(ie.type.decode_single_value_from(
- buf, offset, length))
+ try:
+ length, offset = types.decode_varlen(buf, offset, end=limit)
+ except struct.error as exc:
+ raise IpfixDecodeError(f"Truncated varlen prefix: {exc}") from exc
+ if offset + length > limit:
+ raise IpfixDecodeError(
+ f"Field {elem.name} (length {length}) extends past end of set"
+ )
+ if i in packplan.index_set:
+ try:
+ vals.append(elem.type.decode_single_value_from(buf, offset, length))
+ except (struct.error, ValueError, UnicodeDecodeError) as exc:
+ raise IpfixDecodeError(
+ f"Failed to decode field {elem.name}: {exc}"
+ ) from exc
offset += length
return (vals, offset)
- def decode_namedict_from(self, buf, offset, recinf = None):
+ def decode_namedict_from(self, buf, offset, recinf=None):
"""Decodes a record from a buffer into a dict keyed by IE name."""
- (vals, offset) = self.decode_from(buf, offset)
- return (dict(( k, v) for k,v in izip((ie.name for ie in self.ies), vals)), offset)
+ vals, offset = self.decode_from(buf, offset)
+ return ({elem.name: v for elem, v in zip(self.ies, vals, strict=True)}, offset)
- def decode_tuple_from(self, buf, offset, recinf = None):
+ def decode_tuple_from(self, buf, offset, recinf=None):
"""
Decodes a record from a buffer into a tuple,
ordered as the IEs in the InformationElementList given as recinf.
-
"""
if recinf:
packplan = self.packplan_for_ielist(recinf)
else:
packplan = self.packplan
- (vals, offset) = self.decode_from(buf, offset, packplan = packplan)
-
- outvals = tuple(v for i,v in sorted(izip(packplan.ranks, vals)))
+ vals, offset = self.decode_from(buf, offset, packplan=packplan)
# re-sort values in same order as packplan indices
- return (outvals, offset)
+ outvals = tuple(v for _, v in sorted(zip(packplan.ranks, vals, strict=True)))
- def encode_to(self, buf, offset, vals, packplan = None):
- """Encodes a record from a tuple containing values in template order"""
+ return (outvals, offset)
- # use default packplan unless someone hacked us not to
+ def encode_to(self, buf, offset, vals, packplan=None, limit=None):
+ """Encodes a record from a sequence containing values in template order."""
if not packplan:
packplan = self.packplan
+ if packplan is self.packplan and len(vals) != self.count():
+ raise ValueError(
+ f"Expected {self.count()} values for template {self.tid}, got {len(vals)}"
+ )
+
+ bufend = len(buf) if limit is None else min(limit, len(buf))
+ if offset + packplan.st.size > bufend:
+ raise EndOfMessage()
+
# encode fixed values
- fixvals = [f(v) for f,v in izip(packplan.valenc, vals)]
+ fixvals = [
+ f(v)
+ for f, v in zip(
+ packplan.valenc,
+ vals[: self.fixlen_count()],
+ strict=(packplan is self.packplan),
+ )
+ ]
packplan.st.pack_into(buf, offset, *fixvals)
offset += packplan.st.size
# shortcircuit no varlen
- if not self.varlenslice:
+ if self.varlenslice is None:
return offset
# direct iteration over remaining IEs
- for i, ie, val in izip(xrange(self.varlenslice, self.count()),
- self.ies[self.varlenslice:],
- vals[self.varlenslice:]):
- if i in packplan.indices:
- #print(" encoding "+str(ie))
- if ie.length == types.VARLEN:
- # FIXME this arrangement requires double-encode of varlen
- # values, one to get the length, one to do the encode.
- # Fixing this requires a rearrangement of type encoding
- # though. For now we'll just say that if you're exporting
- # varlen you get to put up with some inefficiency. :)
- offset = types.encode_varlen(buf, offset,
- len(ie.type.valenc(val)))
- offset = ie.type.encode_single_value_to(val, buf, offset)
+ for i, elem, val in zip(
+ range(self.varlenslice, self.count()),
+ self.ies[self.varlenslice :],
+ vals[self.varlenslice :],
+ strict=True,
+ ):
+ if i in packplan.index_set:
+ if elem.length == types.VARLEN:
+ enc = elem.type.valenc(val)
+ enclen = len(enc)
+ varlen_hdr = 3 if enclen >= 255 else 1
+ if enclen > types.VARLEN or offset + varlen_hdr + enclen > bufend:
+ raise EndOfMessage()
+ offset = types.encode_varlen(buf, offset, enclen)
+ buf[offset : offset + enclen] = enc
+ offset += enclen
+ else:
+ if offset + elem.length > bufend:
+ raise EndOfMessage()
+ offset = elem.type.encode_single_value_to(val, buf, offset)
return offset
- def encode_namedict_to(self, buf, offset, rec, recinf = None):
- """Encodes a record from a dict containing values keyed by IE name"""
- return self.encode_to(buf, offset, [rec[ie.name] for ie in self.ies])
+ def encode_namedict_to(self, buf, offset, rec, recinf=None):
+ """Encodes a record from a dict containing values keyed by IE name."""
+ return self.encode_to(buf, offset, [rec[elem.name] for elem in self.ies])
- def encode_tuple_to(self, buf, offset, rec, recinf = None):
+ def encode_tuple_to(self, buf, offset, rec, recinf=None):
"""
Encodes a record from a tuple containing values ordered as the IEs
in the template.
-
"""
return self.encode_to(buf, offset, rec)
@@ -277,7 +368,6 @@ def encode_template_to(self, buf, offset, setid):
Encodes the template to a buffer.
Encodes as a Template if setid is TEMPLATE_SET_ID,
as an Options Template if setid is OPTIONS_SET_ID.
-
"""
if setid == TEMPLATE_SET_ID:
_tmplhdr_st.pack_into(buf, offset, self.tid, self.count())
@@ -286,7 +376,7 @@ def encode_template_to(self, buf, offset, setid):
_otmplhdr_st.pack_into(buf, offset, self.tid, self.count(), self.scopecount)
offset += _otmplhdr_st.size
else:
- raise IpfixEncodeError("bad template set id "+str(setid))
+ raise IpfixEncodeError("bad template set id " + str(setid))
for e in self.ies:
if e.pen:
@@ -303,16 +393,16 @@ def encode_template_to(self, buf, offset, setid):
def native_setid(self):
if self.scopecount:
return OPTIONS_SET_ID
- else:
- return TEMPLATE_SET_ID
+ return TEMPLATE_SET_ID
+
def withdrawal_length(setid):
if setid == TEMPLATE_SET_ID:
return _tmplhdr_st.size
- elif setid == OPTIONS_SET_ID:
+ if setid == OPTIONS_SET_ID:
return _otmplhdr_st.size
- else:
- return IpfixEncodeError("bad template set id "+str(setid))
+ raise IpfixEncodeError("bad template set id " + str(setid))
+
def encode_withdrawal_to(buf, offset, setid, tid):
if setid == TEMPLATE_SET_ID:
@@ -322,61 +412,126 @@ def encode_withdrawal_to(buf, offset, setid, tid):
_otmplhdr_st.pack_into(buf, offset, tid, 0, 0)
offset += _otmplhdr_st.size
else:
- raise IpfixEncodeError("bad template set id "+str(setid))
+ raise IpfixEncodeError("bad template set id " + str(setid))
return offset
-def decode_template_from(buf, offset, setid):
+
+def decode_template_from(buf, offset, setid, setend=None):
"""
Decodes a template from a buffer.
- Decodes as a Template if setid is TEMPLATE_SET_ID,
- as an Options Template if setid is OPTIONS_SET_ID.
-
+ Decodes as a Template if setid is TEMPLATE_SET_ID (or V9_TEMPLATE_SET_ID),
+ as an Options Template if setid is OPTIONS_SET_ID (or V9_OPTIONS_SET_ID).
"""
- if (setid == TEMPLATE_SET_ID) or (setid == V9_TEMPLATE_SET_ID):
- (tid, count) = _tmplhdr_st.unpack_from(buf, offset);
+ limit = len(buf) if setend is None else min(setend, len(buf))
+
+ if setid in (TEMPLATE_SET_ID, V9_TEMPLATE_SET_ID):
+ if offset + _tmplhdr_st.size > limit:
+ raise IpfixDecodeError("Truncated template header")
+ tid, count = _tmplhdr_st.unpack_from(buf, offset)
scopecount = 0
offset += _tmplhdr_st.size
- elif (setid == OPTIONS_SET_ID) or (setid == V9_OPTIONS_SET_ID):
- (tid, count, scopecount) = _otmplhdr_st.unpack_from(buf, offset);
+ elif setid == OPTIONS_SET_ID:
+ if offset + _otmplhdr_st.size > limit:
+ raise IpfixDecodeError("Truncated options template header")
+ tid, count, scopecount = _otmplhdr_st.unpack_from(buf, offset)
+ offset += _otmplhdr_st.size
+ elif setid == V9_OPTIONS_SET_ID:
+ if offset + _otmplhdr_st.size > limit:
+ raise IpfixDecodeError("Truncated v9 options template header")
+ tid, scope_len, opt_len = _otmplhdr_st.unpack_from(buf, offset)
offset += _otmplhdr_st.size
+ if scope_len % _iespec_st.size or opt_len % _iespec_st.size:
+ raise IpfixDecodeError(
+ f"Illegal v9 options template byte lengths ({scope_len}, {opt_len})"
+ )
+ scopecount = scope_len // _iespec_st.size
+ count = scopecount + (opt_len // _iespec_st.size)
+ if scopecount == 0 or count == 0:
+ raise IpfixDecodeError(
+ f"Illegal v9 options template scope/option lengths ({scope_len}, {opt_len})"
+ )
else:
- raise IpfixDecodeError("bad template set id "+str(setid))
-
- tmpl = Template(tid)
+ raise IpfixDecodeError("bad template set id " + str(setid))
+
+ is_withdrawal = count == 0 and setid in (TEMPLATE_SET_ID, OPTIONS_SET_ID)
+ if is_withdrawal:
+ if setid == OPTIONS_SET_ID and scopecount != 0:
+ raise IpfixDecodeError(
+ f"Options template withdrawal must have scope count 0, got {scopecount}"
+ )
+ if not (tid == setid or 256 <= tid <= 65535):
+ raise IpfixDecodeError(f"bad withdrawal template ID {tid} for set {setid}")
+ tmpl = Template(tid, _allow_withdrawal_tid=True)
+ tmpl.finalize()
+ return (tmpl, offset)
+
+ if setid == V9_TEMPLATE_SET_ID and count == 0:
+ raise IpfixDecodeError("Illegal zero field count in NetFlow v9 template")
+
+ if setid == OPTIONS_SET_ID and (scopecount == 0 or scopecount > count):
+ raise IpfixDecodeError(
+ f"Illegal options template scope count {scopecount} for field count {count}"
+ )
+
+ try:
+ tmpl = Template(tid)
+ except ValueError as exc:
+ raise IpfixDecodeError(str(exc)) from exc
tmpl.scopecount = scopecount
- while count:
- (num, length) = _iespec_st.unpack_from(buf, offset)
+ for field_idx in range(count):
+ if offset + _iespec_st.size > limit:
+ raise IpfixDecodeError("Truncated IE specifier in template")
+ num, length = _iespec_st.unpack_from(buf, offset)
offset += _iespec_st.size
+ if length == 0:
+ raise IpfixDecodeError(f"Illegal zero field length for IE {num & 0x7FFF}")
if num & 0x8000:
- num &= 0x7fff
+ if setid in (V9_TEMPLATE_SET_ID, V9_OPTIONS_SET_ID):
+ raise IpfixDecodeError("Enterprise bit set in NetFlow v9 template")
+ num &= 0x7FFF
+ if offset + _iepen_st.size > limit:
+ raise IpfixDecodeError("Truncated enterprise number in template")
pen = _iepen_st.unpack_from(buf, offset)[0]
- offset += _iespec_st.size
+ offset += _iepen_st.size
else:
pen = 0
- tmpl.append(ie.for_template_entry(pen, num, length))
- count -= 1
+ try:
+ if setid == V9_OPTIONS_SET_ID and field_idx < scopecount:
+ scope_name = _V9_SCOPE_NAMES.get(num, f"_v9_scope_{num}")
+ elem = _V9ScopeIE(
+ scope_name, 0, num, types.for_name("octetArray"), length
+ )
+ else:
+ elem = ie.for_template_entry(pen, num, length)
+ tmpl.append(elem)
+ except types.IpfixTypeError as exc:
+ raise IpfixDecodeError(str(exc)) from exc
tmpl.finalize()
return (tmpl, offset)
-def from_ielist(tid, ielist):
+def from_ielist(tid, ielist, scopecount=0):
tmpl = Template(tid, ielist)
-
+ if scopecount < 0 or scopecount > tmpl.count():
+ raise ValueError(
+ f"Illegal scope count {scopecount} for template with {tmpl.count()} IEs"
+ )
+ tmpl.scopecount = scopecount
tmpl.finalize()
-
return tmpl
-def for_specs(tid, *specs):
+
+def for_specs(tid, *specs, scopecount=0):
"""
- Create a template from a template ID and a list of IESpecs
+ Create a template from a template ID and a list of IESpecs.
:param tid: Template ID, must be between 256 and 65535.
:param *specs: List of IESpecs
+ :param scopecount: Optional scope field count for Options Templates
:return: A new Template, ready to use for writing to a Message
-
"""
- return from_ielist(tid, ie.spec_list(specs))
+ return from_ielist(tid, ie.spec_list(specs), scopecount=scopecount)
diff --git a/ipfix/testutils.py b/ipfix/testutils.py
index 4e84ef5..f5c47c2 100644
--- a/ipfix/testutils.py
+++ b/ipfix/testutils.py
@@ -1,6 +1,5 @@
-# coding: utf8
#
-# python-ipfix (c) 2013-2014 Brian Trammell.
+# python-ipfix (c) 2013-2026 Brian Trammell.
#
# Many thanks to the mPlane consortium (http://www.ict-mplane.eu) for
# its material support of this effort.
@@ -19,35 +18,116 @@
# this program. If not, see .
#
-from __future__ import unicode_literals, division
-from . import ie, template, message, compat
-from .template import IpfixEncodeError, IpfixDecodeError
-from .compat import xrange
+"""Helper utilities for generating synthetic IPFIX test messages."""
+
+import base64
from datetime import datetime, timedelta
from ipaddress import ip_address
-import base64
-import io
-_stored_test_message = base64.b64decode(b'AAoPe0mfAfkAAAAAAAAgcAACACABAQAFAAgABACYAAj//v//AACK7gABAAQAAgAIAQEPS38AAAAAAAEfkPtEAARhbGZhAAAAAAAAAAAAAAAAfwAAAQAAAR+Q+0QBBWJyYXZvAAAAAQAAAAAAAAABfwAAAgAAAR+Q+0QCB2NoYXJsaWUAAAACAAAAAAAAAAJ/AAADAAABH5D7RAMFZGVsdGEAAAADAAAAAAAAAAN/AAAEAAABH5D7RAQEZWNobwAAAAQAAAAAAAAABH8AAAUAAAEfkPtEBQdmb3h0cm90AAAABQAAAAAAAAAFfwAABgAAAR+Q+0QGB2dyw7xlemkAAAAGAAAAAAAAAAZ/AAAHAAABH5D7RAcEYWxmYQAAAAcAAAAAAAAAB38AAAgAAAEfkPtECAVicmF2bwAAAAgAAAAAAAAACH8AAAkAAAEfkPtECQdjaGFybGllAAAACQAAAAAAAAAJfwAACgAAAR+Q+0QKBWRlbHRhAAAACgAAAAAAAAAKfwAACwAAAR+Q+0QLBGVjaG8AAAALAAAAAAAAAAt/AAAMAAABH5D7RAwHZm94dHJvdAAAAAwAAAAAAAAADH8AAA0AAAEfkPtEDQdncsO8ZXppAAAADQAAAAAAAAANfwAADgAAAR+Q+0QOBGFsZmEAAAAOAAAAAAAAAA5/AAAPAAABH5D7RA8FYnJhdm8AAAAPAAAAAAAAAA9/AAAQAAABH5D7RBAHY2hhcmxpZQAAABAAAAAAAAAAEH8AABEAAAEfkPtEEQVkZWx0YQAAABEAAAAAAAAAEX8AABIAAAEfkPtEEgRlY2hvAAAAEgAAAAAAAAASfwAAEwAAAR+Q+0QTB2ZveHRyb3QAAAATAAAAAAAAABN/AAAUAAABH5D7RBQHZ3LDvGV6aQAAABQAAAAAAAAAFH8AABUAAAEfkPtEFQRhbGZhAAAAFQAAAAAAAAAVfwAAFgAAAR+Q+0QWBWJyYXZvAAAAFgAAAAAAAAAWfwAAFwAAAR+Q+0QXB2NoYXJsaWUAAAAXAAAAAAAAABd/AAAYAAABH5D7RBgFZGVsdGEAAAAYAAAAAAAAABh/AAAZAAABH5D7RBkEZWNobwAAABkAAAAAAAAAGX8AABoAAAEfkPtEGgdmb3h0cm90AAAAGgAAAAAAAAAafwAAGwAAAR+Q+0QbB2dyw7xlemkAAAAbAAAAAAAAAAB/AAAcAAABH5D7RBwEYWxmYQAAABwAAAAAAAAAAX8AAB0AAAEfkPtEHQVicmF2bwAAAB0AAAAAAAAAAn8AAB4AAAEfkPtEHgdjaGFybGllAAAAHgAAAAAAAAADfwAAHwAAAR+Q+0QfBWRlbHRhAAAAHwAAAAAAAAAEfwAAIAAAAR+Q+0QgBGVjaG8AAAAgAAAAAAAAAAV/AAAhAAABH5D7RCEHZm94dHJvdAAAAAAAAAAAAAAABn8AACIAAAEfkPtEIgdncsO8ZXppAAAAAQAAAAAAAAAHfwAAIwAAAR+Q+0QjBGFsZmEAAAACAAAAAAAAAAh/AAAkAAABH5D7RCQFYnJhdm8AAAADAAAAAAAAAAl/AAAlAAABH5D7RCUHY2hhcmxpZQAAAAQAAAAAAAAACn8AACYAAAEfkPtEJgVkZWx0YQAAAAUAAAAAAAAAC38AACcAAAEfkPtEJwRlY2hvAAAABgAAAAAAAAAMfwAAKAAAAR+Q+0QoB2ZveHRyb3QAAAAHAAAAAAAAAA1/AAApAAABH5D7RCkHZ3LDvGV6aQAAAAgAAAAAAAAADn8AACoAAAEfkPtEKgRhbGZhAAAACQAAAAAAAAAPfwAAKwAAAR+Q+0QrBWJyYXZvAAAACgAAAAAAAAAQfwAALAAAAR+Q+0QsB2NoYXJsaWUAAAALAAAAAAAAABF/AAAtAAABH5D7RC0FZGVsdGEAAAAMAAAAAAAAABJ/AAAuAAABH5D7RC4EZWNobwAAAA0AAAAAAAAAE38AAC8AAAEfkPtELwdmb3h0cm90AAAADgAAAAAAAAAUfwAAMAAAAR+Q+0QwB2dyw7xlemkAAAAPAAAAAAAAABV/AAAxAAABH5D7RDEEYWxmYQAAABAAAAAAAAAAFn8AADIAAAEfkPtEMgVicmF2bwAAABEAAAAAAAAAF38AADMAAAEfkPtEMwdjaGFybGllAAAAEgAAAAAAAAAYfwAANAAAAR+Q+0Q0BWRlbHRhAAAAEwAAAAAAAAAZfwAANQAAAR+Q+0Q1BGVjaG8AAAAUAAAAAAAAABp/AAA2AAABH5D7RDYHZm94dHJvdAAAABUAAAAAAAAAAH8AADcAAAEfkPtENwdncsO8ZXppAAAAFgAAAAAAAAABfwAAOAAAAR+Q+0Q4BGFsZmEAAAAXAAAAAAAAAAJ/AAA5AAABH5D7RDkFYnJhdm8AAAAYAAAAAAAAAAN/AAA6AAABH5D7RDoHY2hhcmxpZQAAABkAAAAAAAAABH8AADsAAAEfkPtEOwVkZWx0YQAAABoAAAAAAAAABX8AADwAAAEfkPtEPARlY2hvAAAAGwAAAAAAAAAGfwAAPQAAAR+Q+0Q9B2ZveHRyb3QAAAAcAAAAAAAAAAd/AAA+AAABH5D7RD4HZ3LDvGV6aQAAAB0AAAAAAAAACH8AAD8AAAEfkPtEPwRhbGZhAAAAHgAAAAAAAAAJfwAAQAAAAR+Q+0RABWJyYXZvAAAAHwAAAAAAAAAKfwAAQQAAAR+Q+0RBB2NoYXJsaWUAAAAgAAAAAAAAAAt/AABCAAABH5D7REIFZGVsdGEAAAAAAAAAAAAAAAx/AABDAAABH5D7REMEZWNobwAAAAEAAAAAAAAADX8AAEQAAAEfkPtERAdmb3h0cm90AAAAAgAAAAAAAAAOfwAARQAAAR+Q+0RFB2dyw7xlemkAAAADAAAAAAAAAA9/AABGAAABH5D7REYEYWxmYQAAAAQAAAAAAAAAEH8AAEcAAAEfkPtERwVicmF2bwAAAAUAAAAAAAAAEX8AAEgAAAEfkPtESAdjaGFybGllAAAABgAAAAAAAAASfwAASQAAAR+Q+0RJBWRlbHRhAAAABwAAAAAAAAATfwAASgAAAR+Q+0RKBGVjaG8AAAAIAAAAAAAAABR/AABLAAABH5D7REsHZm94dHJvdAAAAAkAAAAAAAAAFX8AAEwAAAEfkPtETAdncsO8ZXppAAAACgAAAAAAAAAWfwAATQAAAR+Q+0RNBGFsZmEAAAALAAAAAAAAABd/AABOAAABH5D7RE4FYnJhdm8AAAAMAAAAAAAAABh/AABPAAABH5D7RE8HY2hhcmxpZQAAAA0AAAAAAAAAGX8AAFAAAAEfkPtEUAVkZWx0YQAAAA4AAAAAAAAAGn8AAFEAAAEfkPtEUQRlY2hvAAAADwAAAAAAAAAAfwAAUgAAAR+Q+0RSB2ZveHRyb3QAAAAQAAAAAAAAAAF/AABTAAABH5D7RFMHZ3LDvGV6aQAAABEAAAAAAAAAAn8AAFQAAAEfkPtEVARhbGZhAAAAEgAAAAAAAAADfwAAVQAAAR+Q+0RVBWJyYXZvAAAAEwAAAAAAAAAEfwAAVgAAAR+Q+0RWB2NoYXJsaWUAAAAUAAAAAAAAAAV/AABXAAABH5D7RFcFZGVsdGEAAAAVAAAAAAAAAAZ/AABYAAABH5D7RFgEZWNobwAAABYAAAAAAAAAB38AAFkAAAEfkPtEWQdmb3h0cm90AAAAFwAAAAAAAAAIfwAAWgAAAR+Q+0RaB2dyw7xlemkAAAAYAAAAAAAAAAl/AABbAAABH5D7RFsEYWxmYQAAABkAAAAAAAAACn8AAFwAAAEfkPtEXAVicmF2bwAAABoAAAAAAAAAC38AAF0AAAEfkPtEXQdjaGFybGllAAAAGwAAAAAAAAAMfwAAXgAAAR+Q+0ReBWRlbHRhAAAAHAAAAAAAAAANfwAAXwAAAR+Q+0RfBGVjaG8AAAAdAAAAAAAAAA5/AABgAAABH5D7RGAHZm94dHJvdAAAAB4AAAAAAAAAD38AAGEAAAEfkPtEYQdncsO8ZXppAAAAHwAAAAAAAAAQfwAAYgAAAR+Q+0RiBGFsZmEAAAAgAAAAAAAAABF/AABjAAABH5D7RGMFYnJhdm8AAAAAAAAAAAAAABJ/AABkAAABH5D7RGQHY2hhcmxpZQAAAAEAAAAAAAAAE38AAGUAAAEfkPtEZQVkZWx0YQAAAAIAAAAAAAAAFH8AAGYAAAEfkPtEZgRlY2hvAAAAAwAAAAAAAAAVfwAAZwAAAR+Q+0RnB2ZveHRyb3QAAAAEAAAAAAAAABZ/AABoAAABH5D7RGgHZ3LDvGV6aQAAAAUAAAAAAAAAF38AAGkAAAEfkPtEaQRhbGZhAAAABgAAAAAAAAAYfwAAagAAAR+Q+0RqBWJyYXZvAAAABwAAAAAAAAAZfwAAawAAAR+Q+0RrB2NoYXJsaWUAAAAIAAAAAAAAABp/AABsAAABH5D7RGwFZGVsdGEAAAAJAAAAAAAAAAB/AABtAAABH5D7RG0EZWNobwAAAAoAAAAAAAAAAX8AAG4AAAEfkPtEbgdmb3h0cm90AAAACwAAAAAAAAACfwAAbwAAAR+Q+0RvB2dyw7xlemkAAAAMAAAAAAAAAAN/AABwAAABH5D7RHAEYWxmYQAAAA0AAAAAAAAABH8AAHEAAAEfkPtEcQVicmF2bwAAAA4AAAAAAAAABX8AAHIAAAEfkPtEcgdjaGFybGllAAAADwAAAAAAAAAGfwAAcwAAAR+Q+0RzBWRlbHRhAAAAEAAAAAAAAAAHfwAAdAAAAR+Q+0R0BGVjaG8AAAARAAAAAAAAAAh/AAB1AAABH5D7RHUHZm94dHJvdAAAABIAAAAAAAAACX8AAHYAAAEfkPtEdgdncsO8ZXppAAAAEwAAAAAAAAAKfwAAdwAAAR+Q+0R3BGFsZmEAAAAUAAAAAAAAAAt/AAB4AAABH5D7RHgFYnJhdm8AAAAVAAAAAAAAAAx/AAB5AAABH5D7RHkHY2hhcmxpZQAAABYAAAAAAAAADX8AAHoAAAEfkPtEegVkZWx0YQAAABcAAAAAAAAADn8AAHsAAAEfkPtEewRlY2hvAAAAGAAAAAAAAAAPfwAAfAAAAR+Q+0R8B2ZveHRyb3QAAAAZAAAAAAAAABB/AAB9AAABH5D7RH0HZ3LDvGV6aQAAABoAAAAAAAAAEX8AAH4AAAEfkPtEfgRhbGZhAAAAGwAAAAAAAAASfwAAfwAAAR+Q+0R/BWJyYXZvAAAAHAAAAAAAAAAT')
+from . import ie, message, template
+
+_stored_test_message = base64.b64decode(
+ b"AAoPe0mfAfkAAAAAAAAgcAACACABAQAFAAgABACYAAj//v//AACK7gABAAQAAgAIAQEPS38AAAAAAA"
+ b"EfkPtEAARhbGZhAAAAAAAAAAAAAAAAfwAAAQAAAR+Q+0QBBWJyYXZvAAAAAQAAAAAAAAABfwAAAgAA"
+ b"AR+Q+0QCB2NoYXJsaWUAAAACAAAAAAAAAAJ/AAADAAABH5D7RAMFZGVsdGEAAAADAAAAAAAAAAN/AA"
+ b"AEAAABH5D7RAQEZWNobwAAAAQAAAAAAAAABH8AAAUAAAEfkPtEBQdmb3h0cm90AAAABQAAAAAAAAAF"
+ b"fwAABgAAAR+Q+0QGB2dyw7xlemkAAAAGAAAAAAAAAAZ/AAAHAAABH5D7RAcEYWxmYQAAAAcAAAAAAA"
+ b"AAB38AAAgAAAEfkPtECAVicmF2bwAAAAgAAAAAAAAACH8AAAkAAAEfkPtECQdjaGFybGllAAAACQAA"
+ b"AAAAAAAJfwAACgAAAR+Q+0QKBWRlbHRhAAAACgAAAAAAAAAKfwAACwAAAR+Q+0QLBGVjaG8AAAALAA"
+ b"AAAAAAAAt/AAAMAAABH5D7RAwHZm94dHJvdAAAAAwAAAAAAAAADH8AAA0AAAEfkPtEDQdncsO8ZXpp"
+ b"AAAADQAAAAAAAAANfwAADgAAAR+Q+0QOBGFsZmEAAAAOAAAAAAAAAA5/AAAPAAABH5D7RA8FYnJhdm"
+ b"8AAAAPAAAAAAAAAA9/AAAQAAABH5D7RBAHY2hhcmxpZQAAABAAAAAAAAAAEH8AABEAAAEfkPtEEQVk"
+ b"ZWx0YQAAABEAAAAAAAAAEX8AABIAAAEfkPtEEgRlY2hvAAAAEgAAAAAAAAASfwAAEwAAAR+Q+0QTB2"
+ b"ZveHRyb3QAAAATAAAAAAAAABN/AAAUAAABH5D7RBQHZ3LDvGV6aQAAABQAAAAAAAAAFH8AABUAAAEf"
+ b"kPtEFQRhbGZhAAAAFQAAAAAAAAAVfwAAFgAAAR+Q+0QWBWJyYXZvAAAAFgAAAAAAAAAWfwAAFwAAAR"
+ b"+Q+0QXB2NoYXJsaWUAAAAXAAAAAAAAABd/AAAYAAABH5D7RBgFZGVsdGEAAAAYAAAAAAAAABh/AAAZ"
+ b"AAABH5D7RBkEZWNobwAAABkAAAAAAAAAGX8AABoAAAEfkPtEGgdmb3h0cm90AAAAGgAAAAAAAAAafw"
+ b"AAGwAAAR+Q+0QbB2dyw7xlemkAAAAbAAAAAAAAAAB/AAAcAAABH5D7RBwEYWxmYQAAABwAAAAAAAAA"
+ b"AX8AAB0AAAEfkPtEHQVicmF2bwAAAB0AAAAAAAAAAn8AAB4AAAEfkPtEHgdjaGFybGllAAAAHgAAAA"
+ b"AAAAADfwAAHwAAAR+Q+0QfBWRlbHRhAAAAHwAAAAAAAAAEfwAAIAAAAR+Q+0QgBGVjaG8AAAAgAAAA"
+ b"AAAAAAV/AAAhAAABH5D7RCEHZm94dHJvdAAAAAAAAAAAAAAABn8AACIAAAEfkPtEIgdncsO8ZXppAA"
+ b"AAAQAAAAAAAAAHfwAAIwAAAR+Q+0QjBGFsZmEAAAACAAAAAAAAAAh/AAAkAAABH5D7RCQFYnJhdm8A"
+ b"AAADAAAAAAAAAAl/AAAlAAABH5D7RCUHY2hhcmxpZQAAAAQAAAAAAAAACn8AACYAAAEfkPtEJgVkZW"
+ b"x0YQAAAAUAAAAAAAAAC38AACcAAAEfkPtEJwRlY2hvAAAABgAAAAAAAAAMfwAAKAAAAR+Q+0QoB2Zv"
+ b"eHRyb3QAAAAHAAAAAAAAAA1/AAApAAABH5D7RCkHZ3LDvGV6aQAAAAgAAAAAAAAADn8AACoAAAEfkP"
+ b"tEKgRhbGZhAAAACQAAAAAAAAAPfwAAKwAAAR+Q+0QrBWJyYXZvAAAACgAAAAAAAAAQfwAALAAAAR+Q"
+ b"+0QsB2NoYXJsaWUAAAALAAAAAAAAABF/AAAtAAABH5D7RC0FZGVsdGEAAAAMAAAAAAAAABJ/AAAuAA"
+ b"ABH5D7RC4EZWNobwAAAA0AAAAAAAAAE38AAC8AAAEfkPtELwdmb3h0cm90AAAADgAAAAAAAAAUfwAA"
+ b"MAAAAR+Q+0QwB2dyw7xlemkAAAAPAAAAAAAAABV/AAAxAAABH5D7RDEEYWxmYQAAABAAAAAAAAAAFn"
+ b"8AADIAAAEfkPtEMgVicmF2bwAAABEAAAAAAAAAF38AADMAAAEfkPtEMwdjaGFybGllAAAAEgAAAAAA"
+ b"AAAYfwAANAAAAR+Q+0Q0BWRlbHRhAAAAEwAAAAAAAAAZfwAANQAAAR+Q+0Q1BGVjaG8AAAAUAAAAAA"
+ b"AAABp/AAA2AAABH5D7RDYHZm94dHJvdAAAABUAAAAAAAAAAH8AADcAAAEfkPtENwdncsO8ZXppAAAA"
+ b"FgAAAAAAAAABfwAAOAAAAR+Q+0Q4BGFsZmEAAAAXAAAAAAAAAAJ/AAA5AAABH5D7RDkFYnJhdm8AAA"
+ b"AYAAAAAAAAAAN/AAA6AAABH5D7RDoHY2hhcmxpZQAAABkAAAAAAAAABH8AADsAAAEfkPtEOwVkZWx0"
+ b"YQAAABoAAAAAAAAABX8AADwAAAEfkPtEPARlY2hvAAAAGwAAAAAAAAAGfwAAPQAAAR+Q+0Q9B2ZveH"
+ b"Ryb3QAAAAcAAAAAAAAAAd/AAA+AAABH5D7RD4HZ3LDvGV6aQAAAB0AAAAAAAAACH8AAD8AAAEfkPtE"
+ b"PwRhbGZhAAAAHgAAAAAAAAAJfwAAQAAAAR+Q+0RABWJyYXZvAAAAHwAAAAAAAAAKfwAAQQAAAR+Q+0"
+ b"RBB2NoYXJsaWUAAAAgAAAAAAAAAAt/AABCAAABH5D7REIFZGVsdGEAAAAAAAAAAAAAAAx/AABDAAAB"
+ b"H5D7REMEZWNobwAAAAEAAAAAAAAADX8AAEQAAAEfkPtERAdmb3h0cm90AAAAAgAAAAAAAAAOfwAARQ"
+ b"AAAR+Q+0RFB2dyw7xlemkAAAADAAAAAAAAAA9/AABGAAABH5D7REYEYWxmYQAAAAQAAAAAAAAAEH8A"
+ b"AEcAAAEfkPtERwVicmF2bwAAAAUAAAAAAAAAEX8AAEgAAAEfkPtESAdjaGFybGllAAAABgAAAAAAAA"
+ b"ASfwAASQAAAR+Q+0RJBWRlbHRhAAAABwAAAAAAAAATfwAASgAAAR+Q+0RKBGVjaG8AAAAIAAAAAAAA"
+ b"ABR/AABLAAABH5D7REsHZm94dHJvdAAAAAkAAAAAAAAAFX8AAEwAAAEfkPtETAdncsO8ZXppAAAACg"
+ b"AAAAAAAAAWfwAATQAAAR+Q+0RNBGFsZmEAAAALAAAAAAAAABd/AABOAAABH5D7RE4FYnJhdm8AAAAM"
+ b"AAAAAAAAABh/AABPAAABH5D7RE8HY2hhcmxpZQAAAA0AAAAAAAAAGX8AAFAAAAEfkPtEUAVkZWx0YQ"
+ b"AAAA4AAAAAAAAAGn8AAFEAAAEfkPtEUQRlY2hvAAAADwAAAAAAAAAAfwAAUgAAAR+Q+0RSB2ZveHRy"
+ b"b3QAAAAQAAAAAAAAAAF/AABTAAABH5D7RFMHZ3LDvGV6aQAAABEAAAAAAAAAAn8AAFQAAAEfkPtEVA"
+ b"RhbGZhAAAAEgAAAAAAAAADfwAAVQAAAR+Q+0RVBWJyYXZvAAAAEwAAAAAAAAAEfwAAVgAAAR+Q+0RW"
+ b"B2NoYXJsaWUAAAAUAAAAAAAAAAV/AABXAAABH5D7RFcFZGVsdGEAAAAVAAAAAAAAAAZ/AABYAAABH5"
+ b"D7RFgEZWNobwAAABYAAAAAAAAAB38AAFkAAAEfkPtEWQdmb3h0cm90AAAAFwAAAAAAAAAIfwAAWgAA"
+ b"AR+Q+0RaB2dyw7xlemkAAAAYAAAAAAAAAAl/AABbAAABH5D7RFsEYWxmYQAAABkAAAAAAAAACn8AAF"
+ b"wAAAEfkPtEXAVicmF2bwAAABoAAAAAAAAAC38AAF0AAAEfkPtEXQdjaGFybGllAAAAGwAAAAAAAAAM"
+ b"fwAAXgAAAR+Q+0ReBWRlbHRhAAAAHAAAAAAAAAANfwAAXwAAAR+Q+0RfBGVjaG8AAAAdAAAAAAAAAA"
+ b"5/AABgAAABH5D7RGAHZm94dHJvdAAAAB4AAAAAAAAAD38AAGEAAAEfkPtEYQdncsO8ZXppAAAAHwAA"
+ b"AAAAAAAQfwAAYgAAAR+Q+0RiBGFsZmEAAAAgAAAAAAAAABF/AABjAAABH5D7RGMFYnJhdm8AAAAAAA"
+ b"AAAAAAABJ/AABkAAABH5D7RGQHY2hhcmxpZQAAAAEAAAAAAAAAE38AAGUAAAEfkPtEZQVkZWx0YQAA"
+ b"AAIAAAAAAAAAFH8AAGYAAAEfkPtEZgRlY2hvAAAAAwAAAAAAAAAVfwAAZwAAAR+Q+0RnB2ZveHRyb3"
+ b"QAAAAEAAAAAAAAABZ/AABoAAABH5D7RGgHZ3LDvGV6aQAAAAUAAAAAAAAAF38AAGkAAAEfkPtEaQRh"
+ b"bGZhAAAABgAAAAAAAAAYfwAAagAAAR+Q+0RqBWJyYXZvAAAABwAAAAAAAAAZfwAAawAAAR+Q+0RrB2"
+ b"NoYXJsaWUAAAAIAAAAAAAAABp/AABsAAABH5D7RGwFZGVsdGEAAAAJAAAAAAAAAAB/AABtAAABH5D7"
+ b"RG0EZWNobwAAAAoAAAAAAAAAAX8AAG4AAAEfkPtEbgdmb3h0cm90AAAACwAAAAAAAAACfwAAbwAAAR"
+ b"+Q+0RvB2dyw7xlemkAAAAMAAAAAAAAAAN/AABwAAABH5D7RHAEYWxmYQAAAA0AAAAAAAAABH8AAHEA"
+ b"AAEf"
+ b"kPtEcQVicmF2bwAAAA4AAAAAAAAABX8AAHIAAAEfkPtEcgdjaGFybGllAAAADwAAAAAAAAAGfw"
+ b"AAcwAAAR+Q+0RzBWRlbHRhAAAAEAAAAAAAAAAHfwAAdAAAAR+Q+0R0BGVjaG8AAAARAAAAAAAAAAh/"
+ b"AAB1AAABH5D7RHUHZm94dHJvdAAAABIAAAAAAAAACX8AAHYAAAEfkPtEdgdncsO8ZXppAAAAEwAAAA"
+ b"AAAAAKfwAAdwAAAR+Q+0R3BGFsZmEAAAAUAAAAAAAAAAt/AAB4AAABH5D7RHgFYnJhdm8AAAAVAAAA"
+ b"AAAAAAx/AAB5AAABH5D7RHkHY2hhcmxpZQAAABYAAAAAAAAADX8AAHoAAAEfkPtEegVkZWx0YQAAAB"
+ b"cAAAAAAAAADn8AAHsAAAEfkPtEewRlY2hvAAAAGAAAAAAAAAAPfwAAfAAAAR+Q+0R8B2ZveHRyb3QA"
+ b"AAAZAAAAAAAAABB/AAB9AAABH5D7RH0HZ3LDvGV6aQAAABoAAAAAAAAAEX8AAH4AAAEfkPtEfgRhbG"
+ b"ZhAAAAGwAAAAAAAAASfwAAfwAAAR+Q+0R/BWJyYXZvAAAAHAAAAAAAAAAT"
+)
_test_strings = ["alfa", "bravo", "charlie", "delta", "echo", "foxtrot", "grüezi"]
+
def mktest_record(sequence):
- return { 'sourceIPv4Address': ip_address(0x7f000000 + sequence),
- 'flowStartMilliseconds': datetime(2009, 2, 20, tzinfo=None) + timedelta(0, sequence / 1000),
- 'testString': _test_strings[sequence % len(_test_strings)],
- 'octetDeltaCount': sequence % 33,
- 'packetDeltaCount': sequence % 27 }
+ return {
+ "sourceIPv4Address": ip_address(0x7F000000 + sequence),
+ "flowStartMilliseconds": datetime(2009, 2, 20, tzinfo=None)
+ + timedelta(0, sequence / 1000),
+ "testString": _test_strings[sequence % len(_test_strings)],
+ "octetDeltaCount": sequence % 33,
+ "packetDeltaCount": sequence % 27,
+ }
+
def mktest_template(tid=257):
ie.use_iana_default()
ie.for_spec("testString(35566/32766)")
- return template.from_ielist(tid,
- ie.spec_list(["sourceIPv4Address",
- "flowStartMilliseconds",
- "testString",
- "octetDeltaCount[4]",
- "packetDeltaCount"]))
+ return template.from_ielist(
+ tid,
+ ie.spec_list(
+ [
+ "sourceIPv4Address",
+ "flowStartMilliseconds",
+ "testString",
+ "octetDeltaCount[4]",
+ "packetDeltaCount",
+ ]
+ ),
+ )
+
def mktest_message(rec_count=128, odid=8304, tid=257):
"""
@@ -56,111 +136,27 @@ def mktest_message(rec_count=128, odid=8304, tid=257):
address, and string Information Elements, using both normal
and reduced-length encoding.
"""
-
msg = message.MessageBuffer()
msg.begin_export(odid)
msg.add_template(mktest_template(tid))
msg.export_ensure_set(tid)
msg.set_export_time(datetime(2009, 2, 20, 19, 18, 17, tzinfo=None))
- for seq in xrange(rec_count):
+ for seq in range(rec_count):
msg.export_namedict(mktest_record(seq))
return msg
+
def fuzzy_datetime_compare(a, b):
- # FIXME This is a hack. We should find a way to make datetimes export exactly
- return abs((a-b).total_seconds()) < 0.01
+ return abs((a - b).total_seconds()) < 0.01
-def msg_to_python(msg, varname="_stored_test_message"):
- return varname+' = base64.b64decode('+repr(base64.b64encode(msg.to_bytes()))+')'
-def mktest_message_python(rec_count=128, odid=8304, tid=257, varname="_stored_test_message"):
- return msg_to_python(mktest_message(rec_count, odid, tid), varname=varname)
+def msg_to_python(msg, varname="_stored_test_message"):
+ return varname + " = base64.b64decode(" + repr(base64.b64encode(msg.to_bytes())) + ")"
-def test_stored_message():
- assert(_stored_test_message == mktest_message().to_bytes())
- msg = message.MessageBuffer()
- msg.from_bytes(_stored_test_message)
- for i, rec in enumerate(msg.namedict_iterator()):
- trec = mktest_record(i)
- assert(rec['packetDeltaCount'] == trec['packetDeltaCount'])
- assert(rec['octetDeltaCount'] == trec['octetDeltaCount'])
- assert(rec['sourceIPv4Address'] == trec['sourceIPv4Address'])
- assert(rec['testString'] == trec['testString'])
- assert(fuzzy_datetime_compare(rec['flowStartMilliseconds'], trec['flowStartMilliseconds']))
-
-def test_message_write_internals():
- # make sure EOM works
- try:
- mktest_message(rec_count=65536)
- assert(False)
- except message.EndOfMessage as m:
- pass
-
-def test_message_read_internals():
- msg = mktest_message()
-
- # test get_export_time
- assert(fuzzy_datetime_compare(msg.get_export_time(), datetime(2009, 2, 20, 19, 18, 17, tzinfo=None)))
-
-
-def test_message_read_errors():
- short_read_test_message_hdr = bytearray(_stored_test_message)
- short_read_test_message_hdr = short_read_test_message_hdr[0:12]
- msg = message.MessageBuffer()
- try:
- msg.from_bytes(short_read_test_message_hdr)
- assert(False)
- except IpfixDecodeError as e:
- pass
-
- short_read_test_message_body = bytearray(_stored_test_message)
- short_read_test_message_body = short_read_test_message_body[0:33]
- msg = message.MessageBuffer()
- try:
- msg.from_bytes(short_read_test_message_body)
- assert(False)
- except IpfixDecodeError as e:
- pass
-
- bad_msg_version_test_message = bytearray(_stored_test_message)
- bad_msg_version_test_message[0] = 1
- bad_msg_version_test_message[1] = 2
- msg = message.MessageBuffer()
- try:
- msg.from_bytes(bad_msg_version_test_message)
- assert(False)
- except IpfixDecodeError as e:
- pass
-
- bad_msg_length_test_message = bytearray(_stored_test_message)
- bad_msg_length_test_message[2] = 0
- bad_msg_length_test_message[3] = 17
- msg = message.MessageBuffer()
- try:
- msg.from_bytes(bad_msg_length_test_message)
- assert(False)
- except IpfixDecodeError as e:
- pass
-
- bad_set_length_test_message_short = bytearray(_stored_test_message)
- bad_set_length_test_message_short[18] = 0
- bad_set_length_test_message_short[19] = 1
- msg = message.MessageBuffer()
- try:
- msg.from_bytes(bad_set_length_test_message_short)
- assert(False)
- except IpfixDecodeError as e:
- pass
-
- bad_set_length_test_message_long = bytearray(_stored_test_message)
- bad_set_length_test_message_long[18] = 255
- bad_set_length_test_message_long[19] = 255
- msg = message.MessageBuffer()
- try:
- msg.from_bytes(bad_set_length_test_message_long)
- assert(False)
- except IpfixDecodeError as e:
- pass
+def mktest_message_python(
+ rec_count=128, odid=8304, tid=257, varname="_stored_test_message"
+):
+ return msg_to_python(mktest_message(rec_count, odid, tid), varname=varname)
diff --git a/ipfix/types.py b/ipfix/types.py
index db56f32..1553dda 100644
--- a/ipfix/types.py
+++ b/ipfix/types.py
@@ -1,6 +1,5 @@
-# coding: utf8
#
-# python-ipfix (c) 2013-2014 Brian Trammell.
+# python-ipfix (c) 2013-2026 Brian Trammell.
#
# Many thanks to the mPlane consortium (http://www.ict-mplane.eu) for
# its material support of this effort.
@@ -32,6 +31,7 @@
unsigned16 int
unsigned32 int
unsigned64 int
+unsigned256 int
signed8 int
signed16 int
signed32 int
@@ -55,10 +55,8 @@
internally by the :class:`ipfix.message.MessageBuffer` class, so we'll create
one to illustrate encoding and decoding:
->>> from __future__ import unicode_literals
->>> import ipfix.compat
>>> import ipfix.types
->>> buf = ipfix.compat.get_buffer(16)
+>>> buf = memoryview(bytearray(32))
Each of the encoding methods returns the offset into the buffer of the first
byte after the encoded value; since we're always encoding to the beginning
@@ -83,15 +81,13 @@
>>> float32.decode_single_value_from(buf, 0, length)
42.035789489746094
-...strings by the str type, encoded as UTF-8 (note that the Python 2
-interpreter prints unicode characters as hex escapes, but using 'print'
-avoids this, and produces the same result in Python 2/3):
+...strings by the str type, encoded as UTF-8:
>>> string = ipfix.types.for_name("string")
>>> length = string.encode_single_value_to("Grüezi", buf, 0)
>>> buf[0:length].tolist()
[71, 114, 195, 188, 101, 122, 105]
->>> print (string.decode_single_value_from(buf, 0, length))
+>>> print(string.decode_single_value_from(buf, 0, length))
Grüezi
...addresses as the IPv4Address and IPv6Address types in the ipaddress module:
@@ -111,7 +107,7 @@
IPv6Address('2001:db8::c0:ffee')
...and the timestamps of various precision as a python datetime,
-encoded as per RFC5101bis:
+encoded as per RFC 7011:
>>> from datetime import datetime
>>> dtfmt = "%Y-%m-%d %H:%M:%S.%f"
@@ -149,55 +145,122 @@
microsecond-level timing.
"""
-from __future__ import unicode_literals
-from __future__ import division
-from datetime import datetime, timedelta
-from functools import total_ordering
-from ipaddress import ip_address
+
import binascii
-import struct
import math
+import operator
+import struct
+from datetime import UTC, datetime
+from functools import total_ordering
+from ipaddress import ip_address
VARLEN = 65535
ISO8601_FMT = "%Y-%m-%d %H:%M:%S"
-# Seconds between NTP epoch and Unix epoch
+# Seconds between NTP epoch (1900-01-01) and Unix epoch (1970-01-01)
NTP_EPOCH_TO_UNIX_EPOCH = 0x83AA7E80
+
class IpfixTypeError(ValueError):
"""Raised when attempting to do an unsupported operation on a type"""
- def __init__(self, *args):
- super(self.__class__, self).__init__(args)
-
-# Table for downconverting struct elements for reduced length encoding
-_stel_rle = { ('H', 1) : 'B',
- ('L', 2) : 'H',
- ('L', 1) : 'B',
- ('Q', 4) : 'L',
- ('Q', 2) : 'H',
- ('Q', 1) : 'B',
- ('h', 1) : 'b',
- ('l', 2) : 'h',
- ('l', 1) : 'b',
- ('q', 4) : 'l',
- ('q', 2) : 'h',
- ('q', 1) : 'b',
- ('d', 4) : 'f'}
+
+
+_OCTET_ARRAY_NUM = 0
+_FLOAT64_NUM = 10
+_STRING_NUM = 13
+_IPV4_NUM = 18
+
+_SIGNED_INT_NUMS = frozenset({5, 6, 7, 8})
+_INT_DEFAULT_LEN = {
+ 1: 1,
+ 2: 2,
+ 3: 4,
+ 4: 8,
+ 5: 1,
+ 6: 2,
+ 7: 4,
+ 8: 8,
+ 23: 32,
+}
+_INT_STRUCT_CODE = {
+ (False, 1): "B",
+ (False, 2): "H",
+ (False, 4): "L",
+ (False, 8): "Q",
+ (True, 1): "b",
+ (True, 2): "h",
+ (True, 4): "l",
+ (True, 8): "q",
+}
# Builtin structs for varlen information
_varlen1_st = struct.Struct("!B")
_varlen2_st = struct.Struct("!H")
-# builtin default encode/decode function
+
def _identity(x):
return x
+def _make_int_encoder(length, signed=False):
+ def _encode_int_bytes(val):
+ return operator.index(val).to_bytes(length, "big", signed=signed)
+
+ return _encode_int_bytes
+
+
+def _make_int_decoder(signed=False):
+ def _decode_int_bytes(octets):
+ return int.from_bytes(octets, "big", signed=signed)
+
+ return _decode_int_bytes
+
+
+def _make_fixed_utf8_encoder(length):
+ def _encode_utf8_fixed(s):
+ encoded = s.encode("utf-8")
+ if len(encoded) > length:
+ raise ValueError(
+ f"UTF-8 encoded string ({len(encoded)} bytes) exceeds fixed length {length}"
+ )
+ return encoded
+
+ return _encode_utf8_fixed
+
+
+def _decode_utf8_fixed(octets):
+ return octets.rstrip(b"\x00").decode("utf-8")
+
+
+def _fixed_sequence_type(roottype, length):
+ if roottype.num == _STRING_NUM:
+ return StructType(
+ roottype.name,
+ roottype.num,
+ f"{length}s",
+ valenc=_make_fixed_utf8_encoder(length),
+ valdec=_decode_utf8_fixed,
+ valstr=roottype.valstr,
+ valparse=roottype.valparse,
+ roottype=roottype,
+ )
+ return StructType(
+ roottype.name,
+ roottype.num,
+ f"{length}s",
+ valenc=roottype.valenc,
+ valdec=roottype.valdec,
+ valstr=roottype.valstr,
+ valparse=roottype.valparse,
+ roottype=roottype,
+ )
+
+
@total_ordering
-class IpfixType(object):
- # Builtin type implementation
- """Abstract interface for all IPFIX types. Used internally. """
+class IpfixType:
+ """Abstract interface for all IPFIX types. Used internally."""
+
def __init__(self, name, num, valenc, valdec, valstr, valparse, roottype=None):
self.name = name
self.num = num
@@ -205,200 +268,337 @@ def __init__(self, name, num, valenc, valdec, valstr, valparse, roottype=None):
self.valdec = valdec
self.valstr = valstr
self.valparse = valparse
- if roottype:
- self.roottype = roottype
- else:
- self.roottype = self
+ self.roottype = roottype if roottype is not None else self
self.length = 0
def __eq__(self, other):
+ if not isinstance(other, IpfixType):
+ return NotImplemented
return (self.num, self.length) == (other.num, other.length)
def __lt__(self, other):
+ if not isinstance(other, IpfixType):
+ return NotImplemented
return (self.num, self.length) < (other.num, other.length)
def __str__(self):
- return "<%s>" % self.name
+ return f"<{self.name}>"
def __repr__(self):
- return "ipfix.types.for_name(%s)" % repr(self.name)
+ return f"ipfix.types.for_name({self.name!r})"
class StructType(IpfixType):
"""Type encoded by struct packing. Used internally."""
- def __init__(self, name, num, stel, valenc=_identity, valdec=_identity, valstr=str, valparse=int, roottype=None):
- super(self.__class__, self).__init__(name, num, valenc, valdec, valstr, valparse, roottype)
+
+ def __init__(
+ self,
+ name,
+ num,
+ stel,
+ valenc=_identity,
+ valdec=_identity,
+ valstr=str,
+ valparse=int,
+ roottype=None,
+ ):
+ super().__init__(name, num, valenc, valdec, valstr, valparse, roottype=roottype)
self.stel = stel
- self.st = struct.Struct("!"+stel)
+ self.st = struct.Struct("!" + stel)
self.length = self.st.size
- self.skipel = str(self.length)+"x"
+ self.skipel = f"{self.length}x"
def for_length(self, length):
if not length or length == self.length:
return self
- elif self.roottype is _roottypes[0]:
- # FIXME this is kind of a hack to allow any-length encoding of octet arrays
- return StructType(self.name, self.num, str(length)+"s",
- self.valenc, self.valdec, self.roottype)
- else:
- try:
- return StructType(self.name, self.num,
- _stel_rle[(self.stel, length)],
- self.valenc, self.valdec, self.roottype)
- except KeyError:
- raise IpfixTypeError("No RLE for <%s>[%u]" %
- (self.name, length))
+ if length < 0 or length > VARLEN:
+ raise IpfixTypeError(f"Illegal length {length} for <{self.name}>")
+
+ # OctetArray / string fixed-length or varlen re-sizing
+ if self.num in (_OCTET_ARRAY_NUM, _STRING_NUM):
+ if length == VARLEN:
+ return self.roottype
+ return _fixed_sequence_type(self.roottype, length)
+
+ if length == VARLEN:
+ raise IpfixTypeError(f"Illegal length {length} for <{self.name}>")
+
+ # Reduced-size encoding for integer types (RFC 7011 §6.2, RFC 9740)
+ default_len = _INT_DEFAULT_LEN.get(self.num)
+ if default_len is not None and 1 <= length <= default_len:
+ if length == default_len:
+ return self.roottype
+ signed = self.num in _SIGNED_INT_NUMS
+ stel = _INT_STRUCT_CODE.get((signed, length))
+ if stel is not None:
+ return StructType(
+ self.name,
+ self.num,
+ stel,
+ valstr=self.roottype.valstr,
+ valparse=self.roottype.valparse,
+ roottype=self.roottype,
+ )
+ return StructType(
+ self.name,
+ self.num,
+ f"{length}s",
+ valenc=_make_int_encoder(length, signed=signed),
+ valdec=_make_int_decoder(signed=signed),
+ valstr=self.roottype.valstr,
+ valparse=self.roottype.valparse,
+ roottype=self.roottype,
+ )
+
+ # Reduced-size encoding for float64 -> float32 (RFC 7011 §6.2)
+ if self.num == _FLOAT64_NUM:
+ if length == 8:
+ return self.roottype
+ if length == 4:
+ return StructType(
+ self.name,
+ self.num,
+ "f",
+ valstr=self.roottype.valstr,
+ valparse=self.roottype.valparse,
+ roottype=self.roottype,
+ )
+
+ raise IpfixTypeError(f"No RLE for <{self.name}>[{length}]")
def encode_single_value_to(self, val, buf, offset):
self.st.pack_into(buf, offset, self.valenc(val))
return offset + self.length
def decode_single_value_from(self, buf, offset, length):
- assert(self.length == length)
+ if self.length != length:
+ raise IpfixTypeError(
+ f"Length mismatch for <{self.name}>: expected {self.length}, got {length}"
+ )
return self.valdec(self.st.unpack_from(buf, offset)[0])
+
class OctetArrayType(IpfixType):
"""Type encoded by byte array packing. Used internally."""
- def __init__(self, name, num, valenc=_identity, valdec=_identity, valstr=binascii.hexlify, valparse=binascii.unhexlify, roottype=None):
- super(self.__class__, self).__init__(name, num, valenc, valdec, valstr, valparse, roottype)
+
+ def __init__(
+ self,
+ name,
+ num,
+ valenc=_identity,
+ valdec=_identity,
+ valstr=binascii.hexlify,
+ valparse=binascii.unhexlify,
+ roottype=None,
+ ):
+ super().__init__(name, num, valenc, valdec, valstr, valparse, roottype=roottype)
self.length = VARLEN
def for_length(self, length):
if not length or length == self.length:
return self
- else:
- return StructType(self.name, self.num, str(length)+"s",
- self.valenc, self.valdec, self.roottype)
+ if length < 0 or length > VARLEN:
+ raise IpfixTypeError(f"Illegal length {length} for <{self.name}>")
+ return _fixed_sequence_type(self.roottype, length)
def encode_single_value_to(self, val, buf, offset):
enc = self.valenc(val)
- buf[offset:offset+len(enc)] = enc
+ buf[offset : offset + len(enc)] = enc
return offset + len(enc)
def decode_single_value_from(self, buf, offset, length):
- return self.valdec(buf[offset:offset+length].tobytes())
+ return self.valdec(bytes(buf[offset : offset + length]))
-# Utility calls for buildin encoders/decoders
+
+# Utility calls for builtin encoders/decoders
def dt2epoch(dt):
- return (dt - datetime(1970,1,1,0,0,tzinfo=None)).total_seconds()
+ """Convert a datetime (aware or naive-as-UTC) to POSIX seconds since 1970-01-01T00:00:00Z."""
+ if dt.tzinfo is None:
+ dt = dt.replace(tzinfo=UTC)
+ return dt.timestamp()
+
# Builtin encoders/decoders
+def _encode_smibool(val):
+ return 1 if val else 2
-def _encode_smibool(bool):
- if bool:
- return 1
- else:
- return 2
def _decode_smibool(byte):
if byte == 1:
return True
- else:
+ if byte == 2:
return False
+ raise ValueError(f"invalid IPFIX boolean value {byte} (expected 1 or 2)")
+
+
+def _str_bool(val):
+ return "true" if val else "false"
-def _str_bool(bool):
- if bool:
- return "true"
- else:
- return "false"
def _parse_bool(string):
- if string == 'true':
- return True
- else:
- return False
+ return string == "true"
+
def _encode_utf8(string):
- return string.encode('utf8')
+ return string.encode("utf-8")
+
def _decode_utf8(octets):
- return octets.decode('utf8')
+ return octets.decode("utf-8")
+
+
+def _to_naive_utc(dt):
+ if dt.tzinfo is not None:
+ return dt.astimezone(UTC).replace(tzinfo=None)
+ return dt
+
+
+def _parse_iso_dt(string):
+ return _to_naive_utc(datetime.fromisoformat(string))
+
def _encode_sec(dt):
return int(dt2epoch(dt))
+
def _decode_sec(epoch):
- return datetime.utcfromtimestamp(epoch)
+ return datetime.fromtimestamp(epoch, tz=UTC).replace(tzinfo=None)
+
def _str_sec(dt):
- return dt.strftime(ISO8601_FMT)
+ return _to_naive_utc(dt).strftime(ISO8601_FMT)
-def _parse_sec(string):
- return datetime.strptime(string, ISO8601_FMT)
def _encode_msec(dt):
return int(dt2epoch(dt) * 1000)
+
def _decode_msec(epoch):
- return datetime.utcfromtimestamp(epoch/1000)
+ return datetime.fromtimestamp(epoch / 1000, tz=UTC).replace(tzinfo=None)
+
def _str_msec(dt):
- return "%s.%03u" % (dt.strftime(ISO8601_FMT), int(dt.microsecond / 1000))
+ dt = _to_naive_utc(dt)
+ return f"{dt.strftime(ISO8601_FMT)}.{dt.microsecond // 1000:03d}"
-def _parse_msec(string):
- (ss, mss) = string.split(".")
- return datetime.strptime(ss, ISO8601_FMT).replace(microsecond = int(mss) * 1000)
def _encode_ntp(dt):
- (tsf, tsi) = math.modf(dt2epoch(dt))
+ tsf, tsi = math.modf(dt2epoch(dt))
return int(((int(tsi) + NTP_EPOCH_TO_UNIX_EPOCH) << 32) + (tsf * 2**32))
+
def _decode_ntp(ntp):
tsf = ntp & (2**32 - 1)
tsi = (ntp >> 32) - NTP_EPOCH_TO_UNIX_EPOCH
- return datetime.utcfromtimestamp(tsi + tsf / 2**32)
+ return datetime.fromtimestamp(tsi + tsf / 2**32, tz=UTC).replace(tzinfo=None)
+
def _str_usec(dt):
- return "%s.%06u" % (dt.strftime(ISO8601_FMT), dt.microsecond)
+ dt = _to_naive_utc(dt)
+ return f"{dt.strftime(ISO8601_FMT)}.{dt.microsecond:06d}"
+
+
+_parse_sec = _parse_msec = _parse_usec = _parse_iso_dt
-def _parse_usec(string):
- (ss, uss) = string.split(".")
- return datetime.strptime(ss, ISO8601_FMT).replace(microsecond = int(uss))
def _encode_ip(ipaddr):
return ipaddr.packed
-# builtin type registry
+
+# Builtin type registry (RFC 7012 + RFC 9740)
_roottypes = [
OctetArrayType("octetArray", 0),
- StructType("unsigned8", 1, "B"),
+ StructType("unsigned8", 1, "B"),
StructType("unsigned16", 2, "H"),
StructType("unsigned32", 3, "L"),
StructType("unsigned64", 4, "Q"),
- StructType("signed8", 5, "b"),
- StructType("signed16", 6, "h"),
- StructType("signed32", 7, "l"),
- StructType("signed64", 8, "q"),
- StructType("float32", 9, "f", valparse=float),
- StructType("float64", 10, "d", valparse=float),
- StructType("boolean", 11, "B",
- valenc=_encode_smibool, valdec=_decode_smibool,
- valstr=_str_bool, valparse=_parse_bool),
+ StructType("signed8", 5, "b"),
+ StructType("signed16", 6, "h"),
+ StructType("signed32", 7, "l"),
+ StructType("signed64", 8, "q"),
+ StructType("float32", 9, "f", valparse=float),
+ StructType("float64", 10, "d", valparse=float),
+ StructType(
+ "boolean",
+ 11,
+ "B",
+ valenc=_encode_smibool,
+ valdec=_decode_smibool,
+ valstr=_str_bool,
+ valparse=_parse_bool,
+ ),
StructType("macAddress", 12, "6s"),
- OctetArrayType("string", 13,
- valenc=_encode_utf8, valdec=_decode_utf8,
- valstr=_identity, valparse=_identity),
- StructType("dateTimeSeconds", 14, "L",
- valenc=_encode_sec, valdec=_decode_sec,
- valstr=_str_sec, valparse=_parse_sec),
- StructType("dateTimeMilliseconds", 15, "Q",
- valenc=_encode_msec, valdec=_decode_msec,
- valstr=_str_msec, valparse=_parse_msec),
- StructType("dateTimeMicroseconds", 16, "Q",
- valenc=_encode_ntp, valdec=_decode_ntp,
- valstr=_str_usec, valparse=_parse_usec),
- StructType("dateTimeNanoseconds", 17, "Q",
- valenc=_encode_ntp, valdec=_decode_ntp,
- valstr=_str_usec, valparse=_parse_usec),
- StructType("ipv4Address", 18, "4s",
- valenc=_encode_ip, valdec=ip_address,
- valparse=ip_address),
- StructType("ipv6Address", 19, "16s",
- valenc=_encode_ip, valdec=ip_address,
- valparse=ip_address)
+ OctetArrayType(
+ "string",
+ 13,
+ valenc=_encode_utf8,
+ valdec=_decode_utf8,
+ valstr=_identity,
+ valparse=_identity,
+ ),
+ StructType(
+ "dateTimeSeconds",
+ 14,
+ "L",
+ valenc=_encode_sec,
+ valdec=_decode_sec,
+ valstr=_str_sec,
+ valparse=_parse_sec,
+ ),
+ StructType(
+ "dateTimeMilliseconds",
+ 15,
+ "Q",
+ valenc=_encode_msec,
+ valdec=_decode_msec,
+ valstr=_str_msec,
+ valparse=_parse_msec,
+ ),
+ StructType(
+ "dateTimeMicroseconds",
+ 16,
+ "Q",
+ valenc=_encode_ntp,
+ valdec=_decode_ntp,
+ valstr=_str_usec,
+ valparse=_parse_usec,
+ ),
+ StructType(
+ "dateTimeNanoseconds",
+ 17,
+ "Q",
+ valenc=_encode_ntp,
+ valdec=_decode_ntp,
+ valstr=_str_usec,
+ valparse=_parse_usec,
+ ),
+ StructType(
+ "ipv4Address",
+ 18,
+ "4s",
+ valenc=_encode_ip,
+ valdec=ip_address,
+ valparse=ip_address,
+ ),
+ StructType(
+ "ipv6Address",
+ 19,
+ "16s",
+ valenc=_encode_ip,
+ valdec=ip_address,
+ valparse=ip_address,
+ ),
+ StructType(
+ "unsigned256",
+ 23,
+ "32s",
+ valenc=_make_int_encoder(32, signed=False),
+ valdec=_make_int_decoder(signed=False),
+ ),
]
-_TypeForName = dict((ietype.name, ietype) for ietype in _roottypes)
+_TypeForName = {ietype.name: ietype for ietype in _roottypes}
+
def use_integer_ipv4():
"""
@@ -407,9 +607,22 @@ def use_integer_ipv4():
Designed for use with numpy arrays, to not require a Python object for
storing IP addresses.
"""
- _roottypes[18] = StructType("ipv4address", 18, "L")
- global _TypeForName
- _TypeForName = dict((ietype.name, ietype) for ietype in _roottypes)
+ _roottypes[_IPV4_NUM] = StructType("ipv4Address", _IPV4_NUM, "L")
+ _TypeForName["ipv4Address"] = _roottypes[_IPV4_NUM]
+
+
+def use_ipaddress_ipv4():
+ """Restore ipaddress.IPv4Address representation for ipv4Address."""
+ _roottypes[_IPV4_NUM] = StructType(
+ "ipv4Address",
+ _IPV4_NUM,
+ "4s",
+ valenc=_encode_ip,
+ valdec=ip_address,
+ valparse=ip_address,
+ )
+ _TypeForName["ipv4Address"] = _roottypes[_IPV4_NUM]
+
def for_name(name):
"""
@@ -422,20 +635,27 @@ def for_name(name):
"""
try:
return _TypeForName[name]
- except KeyError:
- raise IpfixTypeError("no such type "+name)
+ except KeyError as exc:
+ raise IpfixTypeError("no such type " + name) from exc
-def decode_varlen(buf, offset):
- """Decode a IPFIX varlen encoded length; used internally by template"""
+
+def decode_varlen(buf, offset, end=None):
+ """Decode an IPFIX varlen encoded length; used internally by template."""
+ limit = len(buf) if end is None else end
+ if offset + _varlen1_st.size > limit:
+ raise struct.error("varlen prefix extends past end of buffer")
length = _varlen1_st.unpack_from(buf, offset)[0]
offset += _varlen1_st.size
if length == 255:
+ if offset + _varlen2_st.size > limit:
+ raise struct.error("extended varlen prefix extends past end of buffer")
length = _varlen2_st.unpack_from(buf, offset)[0]
offset += _varlen2_st.size
return (length, offset)
+
def encode_varlen(buf, offset, length):
- """Encode a IPFIX varlen encoded length; used internally by template"""
+ """Encode an IPFIX varlen encoded length; used internally by template."""
if length >= 255:
_varlen1_st.pack_into(buf, offset, 255)
offset += _varlen1_st.size
@@ -445,12 +665,3 @@ def encode_varlen(buf, offset, length):
_varlen1_st.pack_into(buf, offset, length)
offset += _varlen1_st.size
return offset
-
-def test_types_internals():
- try:
- for_name("bogus")
- assert False
- except IpfixTypeError:
- pass
-
-
diff --git a/ipfix/v9pdu.py b/ipfix/v9pdu.py
index c54b01b..03e829a 100644
--- a/ipfix/v9pdu.py
+++ b/ipfix/v9pdu.py
@@ -1,5 +1,5 @@
#
-# python-ipfix (c) 2013 Brian Trammell.
+# python-ipfix (c) 2013-2026 Brian Trammell.
#
# Many thanks to the mPlane consortium (http://www.ict-mplane.eu) for
# its material support of this effort.
@@ -19,33 +19,34 @@
#
"""
-Provides the PduBuffer class for decoding NetFlow V9 Protocol Data
-Units (PDUs) from a stream.
-
+Provides the PduBuffer classes for read-only decoding of NetFlow v9 Protocol
+Data Units (PDUs) from a stream or single packet.
"""
-from __future__ import division
-from . import template, types, ie, compat
-from .template import IpfixEncodeError, IpfixDecodeError
-from .message import accept_all_templates
-from .compat import ifilter
-
-import operator
import struct
from warnings import warn
+from . import ie, template, types
+from .message import (
+ _iter_template_set_records,
+ _recache_all_accepted_tids,
+ accept_all_templates,
+)
+from .template import IpfixDecodeError
+
NETFLOW9_VERSION = 9
_sethdr_st = struct.Struct("!HH")
_pduhdr_st = struct.Struct("!HHLLLL")
-class PduBuffer(object):
+
+class PduBuffer:
"""
- Implements a buffer for reading NetFlow V9 PDUs from a stream or packet.
+ Implements a buffer for reading NetFlow v9 PDUs from a stream or packet.
- Abstract class; use the :meth:`from_stream` to get an instance for
- reading from a stream instead.
+ Abstract base class; use :func:`from_stream` or :class:`SinglePduBuffer`.
"""
+
def __init__(self, mbuf):
"""Create a new PduBuffer instance."""
self.mbuf = mbuf
@@ -57,7 +58,7 @@ def __init__(self, mbuf):
self.sequence = None
self.export_epoch = None
self.sysuptime_ms = None
- self.base_epoch = None
+ self.basetime_epoch = None
self.odid = 0
self.sesid = 0
@@ -66,6 +67,7 @@ def __init__(self, mbuf):
self.sequences = {}
self.last_tuple_iterator_ielist = None
+ self._accepted_cache_key = None
self.template_record_hook = None
self.unknown_data_set_hook = None
@@ -73,136 +75,136 @@ def __init__(self, mbuf):
self.message_header_hook = None
def __repr__(self):
- return ""
+ return f""
- def _increment_sequence(self, inc = 1):
- self.sequences.setdefault(self.odid, 0)
- self.sequences[self.odid] += inc
+ def _increment_sequence(self, inc=1):
+ self.sequences[self.odid] = (self.sequences.get(self.odid, 0) + inc) & 0xFFFFFFFF
def _parse_pdu_header(self):
- (version, self.reccount, self.sysuptime_ms,
- self.export_epoch, self.sequence, self.odid) = \
- _pduhdr_st.unpack_from(self.mbuf, 0)
+ (
+ version,
+ self.reccount,
+ self.sysuptime_ms,
+ self.export_epoch,
+ self.sequence,
+ self.odid,
+ ) = _pduhdr_st.unpack_from(self.mbuf, 0)
if version != NETFLOW9_VERSION:
- raise IpfixDecodeError("Illegal or unsupported version " +
- str(version))
+ raise IpfixDecodeError(f"Illegal or unsupported version {version}")
- self._increment_sequence(self.reccount)
- self.basetime_epoch = self.export_epoch - (self.sysuptime_ms / 1000)
+ self.basetime_epoch = self.export_epoch - (self.sysuptime_ms / 1000.0)
if self.message_header_hook:
self.message_header_hook(self)
def set_iterator(self):
- """
- Low-level interface to set iteration.
-
- """
+ """Low-level interface to set iteration."""
while True:
try:
yield self.next_set()
except EOFError:
break
- def record_iterator(self,
- decode_fn=template.Template.decode_namedict_from,
- tmplaccept_fn=accept_all_templates,
- recinf=None):
- """
- Low-level interface to record iteration.
-
- Iterate over records in a PDU; the buffer must either be attached to
- a stream via :meth:`attach_stream` or have been preloaded with
- :meth:`from_bytes`. Automatically handles
- templates in set order. By default, iterates over each record in the
- stream as a dictionary mapping IE name to value
- (i.e., the same as :meth:`namedict_iterator`)
-
- :param decode_fn: Function used to decode a record;
- must be an (unbound) "decode" instance method of the
- :class:`ipfix.template.Template` class.
- :param tmplaccept_fn: Function returning True if the given template
- is of interest to the caller, False if not.
- Default accepts all templates. Sets described by
- templates for which this function returns False
- will be skipped.
- :param recinf: Record information opaquely passed to decode function
- :returns: an iterator over records decoded by decode_fn.
-
- """
- for (mbuf, offset, setid, setlen) in self.set_iterator():
-
+ def _iter_records(self, decode_fn, tmplaccept_fn, recinf):
+ for mbuf, offset, setid, setlen in self.set_iterator():
setend = offset + setlen
- offset += _sethdr_st.size # skip set header in decode
- if setid == template.V9_TEMPLATE_SET_ID or \
- setid == template.V9_OPTIONS_SET_ID:
- while offset < setend:
- (tmpl, offset) = template.decode_template_from(
- mbuf, offset, setid)
- # FIXME handle withdrawal
- self.templates[(self.sesid, self.odid, tmpl.tid)] = tmpl
+ setview = mbuf[:setend]
+ offset += _sethdr_st.size # skip set header in decode
+
+ if setid in (template.V9_TEMPLATE_SET_ID, template.V9_OPTIONS_SET_ID):
+ for tmpl in _iter_template_set_records(
+ mbuf, offset, setend, setid, v9=True
+ ):
+ tkey = (self.sesid, self.odid, tmpl.tid)
+ self.templates[tkey] = tmpl
if tmplaccept_fn(tmpl):
- self.accepted_tids.add((self.odid, tmpl.tid))
+ self.accepted_tids.add(tkey)
else:
- self.accepted_tids.discard((self.odid, tmpl.tid))
+ self.accepted_tids.discard(tkey)
if self.template_record_hook:
self.template_record_hook(self, tmpl)
elif setid < 256:
- warn("skipping illegal set id "+str(setid))
+ warn("skipping illegal set id " + str(setid), stacklevel=2)
else:
+ tkey = (self.sesid, self.odid, setid)
try:
- tmpl = self.templates[(self.sesid, self.odid, setid)]
- if (self.odid, setid) in self.accepted_tids:
- while offset + tmpl.minlength <= setend:
- (rec, offset) = decode_fn(tmpl, self.mbuf, offset,
- recinf = recinf)
- yield rec
- self._increment_sequence()
- elif self.ignored_data_set_hook:
- # not in accepted tids - ignored data set
- self.ignored_data_set_hook(self, tmpl,
- self.mbuf[offset-_sethdr_st.size:setend])
- except KeyError as e:
+ tmpl = self.templates[tkey]
+ except KeyError:
if self.unknown_data_set_hook:
- # KeyError on template lookup - unknown data set
- self.unknown_data_set_hook(self,
- self.mbuf[offset-_sethdr_st.size:setend])
+ self.unknown_data_set_hook(
+ self, mbuf[offset - _sethdr_st.size : setend]
+ )
+ continue
+
+ if tkey in self.accepted_tids:
+ if tmpl.minlength <= 0:
+ raise IpfixDecodeError(
+ f"Template {tmpl.tid} has zero minimum record length"
+ )
+ while offset + tmpl.minlength <= setend:
+ rec, offset = decode_fn(
+ tmpl, setview, offset, recinf=recinf
+ )
+ yield rec
+ self._increment_sequence()
+ elif self.ignored_data_set_hook:
+ self.ignored_data_set_hook(
+ self, tmpl, mbuf[offset - _sethdr_st.size : setend]
+ )
+
+ def record_iterator(
+ self,
+ decode_fn=template.Template.decode_namedict_from,
+ tmplaccept_fn=accept_all_templates,
+ recinf=None,
+ ):
+ """
+ Low-level interface to record iteration.
- def namedict_iterator(self):
+ Iterate over records in a PDU stream or buffer. Automatically handles
+ templates in set order. By default, iterates over each record as a
+ dictionary mapping IE name to value (same as :meth:`namedict_iterator`).
"""
- Iterate over all records in the Message, as dicts mapping IE names
- to values.
+ if tmplaccept_fn is accept_all_templates:
+ if self._accepted_cache_key != "all":
+ self._recache_accepted_tids(accept_all_templates)
+ self._accepted_cache_key = "all"
+ self.last_tuple_iterator_ielist = None
+ else:
+ self._recache_accepted_tids(tmplaccept_fn)
+ self._accepted_cache_key = None
- :returns: a name dictionary iterator
+ return self._iter_records(decode_fn, tmplaccept_fn, recinf)
+ def namedict_iterator(self):
"""
+ Iterate over all records in the PDU, as dicts mapping IE names to values.
- return self.record_iterator(
- decode_fn = template.Template.decode_namedict_from)
+ :returns: a name dictionary iterator
+ """
+ if self._accepted_cache_key != "all":
+ self._recache_accepted_tids(accept_all_templates)
+ self._accepted_cache_key = "all"
+ self.last_tuple_iterator_ielist = None
+ return self._iter_records(
+ template.Template.decode_namedict_from, accept_all_templates, None
+ )
def active_template_ids(self):
"""
- Get an iterator over all active template IDs in the current domain.
- Provided to allow callers to export some or all active Templates across
- multiple Messages.
+ Get an iterator over all active template IDs in the current session and domain.
:returns: a template ID iterator
-
"""
- # FIXME make sure this is correct
- for tk in filter(lambda k: k[0:1] == (self.sesid, self.odid), self.templates):
- yield tk[1]
-
+ for sesid, odid, tid in self.templates:
+ if sesid == self.sesid and odid == self.odid:
+ yield tid
+
def _recache_accepted_tids(self, tmplaccept_fn):
- for tid in self.active_template_ids():
- if tmplaccept_fn(self.templates[(self.odid, tid)]):
- self.accepted_tids.add((self.odid, tid))
- else:
- self.accepted_tids.discard((self.odid, tid))
+ _recache_all_accepted_tids(self.templates, self.accepted_tids, tmplaccept_fn)
def tuple_iterator(self, ielist):
"""
@@ -211,112 +213,131 @@ def tuple_iterator(self, ielist):
:param ielist: an instance of :class:`ipfix.ie.InformationElementList`
listing IEs to return as a tuple
- :returns: a tuple iterator for tuples as in ielist order
-
+ :returns: a tuple iterator for tuples in ielist order
"""
+ def tmplaccept_fn(tmpl):
+ return all(elem in tmpl.ies for elem in ielist)
- tmplaccept_fn = lambda tmpl: \
- reduce(operator.__and__,
- (ie in tmpl.ies for ie in ielist))
-
- if ((not self.last_tuple_iterator_ielist) or
- (ielist is not self.last_tuple_iterator_ielist)):
- self._recache_accepted_tids(tmplaccept_fn)
+ cache_key = tuple(ielist)
+ if self._accepted_cache_key != cache_key:
+ self._recache_accepted_tids(tmplaccept_fn)
+ self._accepted_cache_key = cache_key
self.last_tuple_iterator_ielist = ielist
- return self.record_iterator(
- decode_fn = template.Template.decode_tuple_from,
- tmplaccept_fn = tmplaccept_fn,
- recinf = ielist)
+ return self._iter_records(
+ template.Template.decode_tuple_from, tmplaccept_fn, ielist
+ )
def save_state(self):
- return {'t': self.templates.copy(), 's': self.sequences.copy()}
+ return {"t": self.templates.copy(), "s": self.sequences.copy()}
def restore_state(self, state):
- for k in state['t'].keys():
- self.templates[k] = state['t'][k]
- for k in state['s'].keys():
- self.sequences[k] = state['s'][k]
+ for k, v in state["t"].items():
+ self.templates[k] = v
+ for k, v in state["s"].items():
+ self.sequences[k] = v
+ self._accepted_cache_key = None
+ self.last_tuple_iterator_ielist = None
+
class StreamPduBuffer(PduBuffer):
- """Create a new StreamPduBuffer instance."""
+ """Reads NetFlow v9 PDUs from a binary stream."""
+
def __init__(self, stream, buf_sz=65536):
- super().__init__(mbuf=compat.get_buffer(buf_sz))
-
+ super().__init__(mbuf=memoryview(bytearray(buf_sz)))
self.stream = stream
+ self._seen_pdu_header = False
def next_set(self):
"""
- Reads the next set from the stream. Automatically reads PDU headers, as
+ Reads the next set from the stream. Automatically reads PDU headers as
well, since PDU headers are treated as a special case of set header in
- streamed PDU reading.
-
- Raises EOF to signal end of stream.
-
- Yes, NetFlow V9 really is that broken as a storage format,
- and this is the only way to stream it without counting records
- (which we can't do in the tuple-reading case).
-
+ streamed PDU reading. Raises EOFError to signal end of stream.
"""
sethdr = self.stream.read(_sethdr_st.size)
- if (len(sethdr) == 0):
+ if len(sethdr) == 0:
raise EOFError()
- elif (len(sethdr) < _sethdr_st.size):
- raise IpfixDecodeError("Short read in V9 set header ("+
- str(len(sethdr)) +")")
+ if len(sethdr) < _sethdr_st.size:
+ raise IpfixDecodeError(f"Short read in V9 set header ({len(sethdr)})")
- self.mbuf[0:_sethdr_st.size] = sethdr
- (setid, setlen) = _sethdr_st.unpack_from(self.mbuf)
+ self.mbuf[0 : _sethdr_st.size] = sethdr
+ setid, setlen = _sethdr_st.unpack_from(self.mbuf)
while setid == NETFLOW9_VERSION:
- # Actually, this is the first part of a message header.
- # Grab the rest from the stream, then parse it.
- resthdr = self.stream.read(_pduhdr_st.size - _sethdr_st.size)
- if (len(resthdr) < _pduhdr_st.size - _sethdr_st.size):
- raise IpfixDecodeError("Short read in V9 pdu header ("+
- str(len(resthdr)) +")")
-
- self.mbuf[_sethdr_st.size:_pduhdr_st.size] = resthdr
+ restlen = _pduhdr_st.size - _sethdr_st.size
+ resthdr = self.stream.read(restlen)
+ if len(resthdr) < restlen:
+ raise IpfixDecodeError(f"Short read in V9 pdu header ({len(resthdr)})")
+
+ self.mbuf[_sethdr_st.size : _pduhdr_st.size] = resthdr
self._parse_pdu_header()
- # Now try again to get a set header
- self.mbuf[0:_sethdr_st.size]= self.stream.read(_sethdr_st.size)
- (setid, setlen) = _sethdr_st.unpack_from(self.mbuf)
+ self._seen_pdu_header = True
+
+ sethdr = self.stream.read(_sethdr_st.size)
+ if len(sethdr) == 0:
+ raise EOFError()
+ if len(sethdr) < _sethdr_st.size:
+ raise IpfixDecodeError(f"Short read in V9 set header ({len(sethdr)})")
+ self.mbuf[0 : _sethdr_st.size] = sethdr
+ setid, setlen = _sethdr_st.unpack_from(self.mbuf)
+
+ if not self._seen_pdu_header:
+ raise IpfixDecodeError(f"Illegal or unsupported version {setid}")
- # read the set body into the buffer
- setbody = self.stream.read(setlen - _sethdr_st.size)
- if (len(setbody) < setlen - _sethdr_st.size):
- raise IpfixDecodeError("Short read in V9 set body ("+
- str(len(setbody)) +")")
+ if setlen < _sethdr_st.size or setlen > len(self.mbuf):
+ raise IpfixDecodeError(f"Illegal V9 set length {setlen}")
- self.mbuf[_sethdr_st.size:setlen] = setbody
+ bodylen = setlen - _sethdr_st.size
+ setbody = self.stream.read(bodylen)
+ if len(setbody) < bodylen:
+ raise IpfixDecodeError(f"Short read in V9 set body ({len(setbody)})")
+
+ self.mbuf[_sethdr_st.size : setlen] = setbody
+ self.length = setlen
- # return pointers for set_iterator
return (self.mbuf, 0, setid, setlen)
+
class SinglePduBuffer(PduBuffer):
- """Create a new SinglePduBuffer instance."""
+ """Reads a single NetFlow v9 PDU from a bytes-like object."""
+
def __init__(self, bytes_in):
- super().__init__(mbuf=memoryview(bytes_in))
+ mv = memoryview(bytes_in)
+ if len(mv) < _pduhdr_st.size:
+ raise IpfixDecodeError(f"Short V9 PDU ({len(mv)} bytes)")
+ super().__init__(mbuf=mv)
+ self.length = len(mv)
self._parse_pdu_header()
self._next_set_ptr = _pduhdr_st.size
def next_set(self):
+ if self._next_set_ptr >= self.length:
+ raise EOFError()
+ if self._next_set_ptr + _sethdr_st.size > self.length:
+ raise IpfixDecodeError("Truncated V9 set header")
+
setloc = self._next_set_ptr
- (setid, setlen) = _sethdr_st.unpack_from(self.mbuf, self._next_set_ptr)
+ setid, setlen = _sethdr_st.unpack_from(self.mbuf, setloc)
+ if setlen < _sethdr_st.size:
+ raise IpfixDecodeError(f"Illegal V9 set length {setlen}")
+ if setloc + setlen > self.length:
+ raise IpfixDecodeError("V9 set extends past end of PDU")
+
self._next_set_ptr += setlen
return (self.mbuf, setloc, setid, setlen)
+
def from_stream(stream, buf_sz=65536):
"""
- Get a StreamPduBuffer for a given stream
+ Get a StreamPduBuffer for a given stream.
:param stream: stream to read
- :return: a :class:`PduBuffer` wrapped around the stream.
-
+ :return: a :class:`StreamPduBuffer` wrapped around the stream.
"""
return StreamPduBuffer(stream, buf_sz=buf_sz)
-class TimeAdapter(object):
+
+class TimeAdapter:
"""
Wraps around a PduBuffer and adds flowStartMilliseconds and
flowEndMilliseconds Information Elements to each record, turning
@@ -326,45 +347,37 @@ class TimeAdapter(object):
To use, create a PduBuffer, create a TimeAdapter with the PduBuffer
as the constructor argument, then iterate tuples or namedicts from
the TimeAdapter.
-
"""
def __init__(self, pdubuf):
self.pdubuf = pdubuf
- def namedict_iterator(self):
- for rec in self.pdubuf.namedict_iterator(ienames):
- try:
- rec["flowStartMilliseconds"] = \
- types._decode_msec(rec["flowStartSysUpTime"] / 1000 +
- self.pdubuf.basetime_epoch)
- except KeyError:
- pass
-
- try:
- rec["flowEndMilliseconds"] = \
- types._decode_msec(rec["flowEndSysUpTime"] / 1000 +
- self.pdubuf.basetime_epoch)
- except KeyError:
- pass
+ def _sysuptime_to_dt(self, sysuptime_ms):
+ return types._decode_msec(self.pdubuf.basetime_epoch * 1000.0 + sysuptime_ms)
+ def namedict_iterator(self):
+ for rec in self.pdubuf.namedict_iterator():
+ if "flowStartSysUpTime" in rec:
+ rec["flowStartMilliseconds"] = self._sysuptime_to_dt(
+ rec["flowStartSysUpTime"]
+ )
+ if "flowEndSysUpTime" in rec:
+ rec["flowEndMilliseconds"] = self._sysuptime_to_dt(
+ rec["flowEndSysUpTime"]
+ )
yield rec
def tuple_iterator(self, ielist):
- flowStartSysUpTime = ie.for_spec("flowStartSysUpTime")
- flowEndSysUpTime = ie.for_spec("flowEndSysUpTime")
+ flow_start = ie.for_spec("flowStartSysUpTime")
+ flow_end = ie.for_spec("flowEndSysUpTime")
- if (flowStartSysUpTime in ielist) and \
- (flowEndSysUpTime in ielist):
- start_index = ielist.index(flowStartSysUpTime)
- end_index = ielist.index(flowEndSysUpTime)
+ if flow_start in ielist and flow_end in ielist:
+ start_index = ielist.index(flow_start)
+ end_index = ielist.index(flow_end)
for rec in self.pdubuf.tuple_iterator(ielist):
- start_ms = types._decode_msec(rec[start_index] / 1000 +
- self.pdubuf.basetime_epoch)
- end_ms = types._decode_msec(rec[end_index] / 1000 +
- self.pdubuf.basetime_epoch)
+ start_ms = self._sysuptime_to_dt(rec[start_index])
+ end_ms = self._sysuptime_to_dt(rec[end_index])
yield rec + (start_ms, end_ms)
else:
- for rec in self.pdubuf.tuple_iterator(ielist):
- yield rec
+ yield from self.pdubuf.tuple_iterator(ielist)
diff --git a/ipfix/writer.py b/ipfix/writer.py
index b713e60..e50a4b5 100644
--- a/ipfix/writer.py
+++ b/ipfix/writer.py
@@ -1,9 +1,9 @@
#
-# python-ipfix (c) 2013 Brian Trammell.
+# python-ipfix (c) 2013-2026 Brian Trammell.
#
# Many thanks to the mPlane consortium (http://www.ict-mplane.eu) for
# its material support of this effort.
-#
+#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
@@ -18,121 +18,139 @@
# this program. If not, see .
#
+"""
+Interface to write IPFIX Messages to a stream.
+"""
+
from . import message
-class MessageStreamWriter(object):
+
+class MessageStreamWriter:
"""
Writes records to a stream of IPFIX messages.
-
+
Uses an :class:`ipfix.message.MessageBuffer` internally, and continually
- writes records into messages, exporting messages to the stream each time the
+ writes records into messages, exporting messages to the stream each time the
maximum message size (MTU) is reached. Use :func:`to_stream` to get an
instance.
-
- Suitable for writing to IPFIX files (see :rfc:`5655`) as well as to TCP
+
+ Suitable for writing to IPFIX files (see :rfc:`5655`) as well as to TCP
sockets. When writing a stream to a file, use mode='wb'.
-
- ..warning: This class is not yet suitable for UDP export; this is an open
- issue to be fixed in a subsequent release.
-
"""
+
def __init__(self, stream, mtu=65535):
self.stream = stream
- self.msg = message.MessageBuffer()
+ self.msg = message.MessageBuffer()
self.msg.mtu = mtu
self.msgcount = 0
-
+ self.curtid = None
+ self.msg.begin_export(0)
+
def _retry_after_flush(self, fn, *args, **kwargs):
try:
return fn(*args, **kwargs)
except message.EndOfMessage:
self.flush()
return fn(*args, **kwargs)
-
+
def set_domain(self, odid):
"""
- Sets the observation domain for subsequent messages sent with
+ Sets the observation domain for subsequent messages sent with
this Writer.
-
+
:param odid: Observation domain ID to use for export. Note that
- templates are scoped to observation domain, so
- templates will need to be added after switching to a
+ templates are scoped to observation domain, so
+ templates will need to be added after switching to a
new observation domain ID.
-
"""
if self.msg.export_needs_flush():
self.msg.write_message(self.stream)
+ self.msgcount += 1
+ self.curtid = None
self.msg.begin_export(odid)
def add_template(self, tmpl):
"""
- Add a template to this Writer. Adding a template makes it
- available for use for exporting records; see :meth:`set_export_template`.
-
- :param tmpl: the template to add
+ Add a template to this Writer. Adding a template makes it
+ available for use for exporting records; see :meth:`set_export_template`.
+ :param tmpl: the template to add
"""
- self.msg.add_template(tmpl)
-
+ self._retry_after_flush(message.MessageBuffer.add_template, self.msg, tmpl)
+
def set_export_template(self, tid):
"""
Set the template to be used for export by subsequent calls to
:meth:`export_namedict` and :meth:`export_tuple`.
- :param tid: Template ID of the Template that will be used to encode
- records to the Writer. The corresponding Template must
- have already been added to the Writer, see
+ :param tid: Template ID of the Template that will be used to encode
+ records to the Writer. The corresponding Template must
+ have already been added to the Writer, see
:meth:`add_template`.
"""
self.curtid = tid
- self._retry_after_flush(message.MessageBuffer.export_ensure_set,
- self.msg, self.curtid)
-
+ self._retry_after_flush(
+ message.MessageBuffer.export_ensure_set, self.msg, self.curtid
+ )
+
def export_namedict(self, rec):
"""
- Export a record to the message, using the current template
+ Export a record to the message, using the current template.
The record is a dictionary mapping IE names to values. The
dictionary must contain a value for each IE in the template. Keys in the
dictionary not in the template will be ignored.
-
+
:param rec: the record to export, as a dictionary
-
"""
- self._retry_after_flush(message.MessageBuffer.export_ensure_set,
- self.msg, self.curtid)
- self._retry_after_flush(message.MessageBuffer.export_namedict,
- self.msg, rec)
-
+ if self.curtid is None:
+ raise message.IpfixEncodeError(
+ "no export template set; call set_export_template() first"
+ )
+ self._retry_after_flush(
+ message.MessageBuffer.export_ensure_set, self.msg, self.curtid
+ )
+ self._retry_after_flush(
+ message.MessageBuffer.export_namedict, self.msg, rec
+ )
+
def export_tuple(self, rec):
- self._retry_after_flush(message.MessageBuffer.export_ensure_set,
- self.msg, self.curtid)
- self._retry_after_flush(message.MessageBuffer.export_tuple,
- self.msg, rec)
-
+ if self.curtid is None:
+ raise message.IpfixEncodeError(
+ "no export template set; call set_export_template() first"
+ )
+ self._retry_after_flush(
+ message.MessageBuffer.export_ensure_set, self.msg, self.curtid
+ )
+ self._retry_after_flush(
+ message.MessageBuffer.export_tuple, self.msg, rec
+ )
+
def flush(self):
"""
Export an in-progress Message immediately.
-
+
Used internally to manage message boundaries, but
can also be used to force immediate export (e.g. to reduce delay
due to buffer dwell time), as well as to finish write operations on
a Writer before closing the underlying stream.
"""
-
+ if not self.msg.export_needs_flush():
+ return
setid = self.msg.cursetid
self.msg.write_message(self.stream)
self.msgcount += 1
self.msg.begin_export()
- self.msg.export_ensure_set(setid)
+ if setid is not None and setid >= 256:
+ self.msg.export_ensure_set(setid)
+
def to_stream(stream, mtu=65535):
"""
- Get a MessageStreamWriter for a given stream
-
+ Get a MessageStreamWriter for a given stream.
+
:param stream: stream to write
:param mtu: maximum message size in bytes; defaults to 65535,
- the largest possible ipfix message.
+ the largest possible IPFIX message.
:return: a :class:`MessageStreamWriter` wrapped around the stream.
-
"""
return MessageStreamWriter(stream, mtu)
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000..8b869b9
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,68 @@
+[build-system]
+requires = ["hatchling>=1.27"]
+build-backend = "hatchling.build"
+
+[project]
+name = "ipfix"
+version = "0.10.0"
+description = "IPFIX (RFC 7011) implementation for Python"
+readme = "README.md"
+license = "LGPL-3.0-or-later"
+license-files = ["LICENSE.txt"]
+requires-python = ">=3.11"
+authors = [
+ { name = "Brian Trammell", email = "brian@trammell.ch" },
+]
+keywords = ["ipfix", "netflow", "rfc7011", "networking", "telemetry", "flow"]
+classifiers = [
+ "Development Status :: 4 - Beta",
+ "Intended Audience :: Developers",
+ "Operating System :: OS Independent",
+ "Programming Language :: Python :: 3",
+ "Programming Language :: Python :: 3.11",
+ "Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
+ "Programming Language :: Python :: 3.14",
+ "Topic :: System :: Networking",
+]
+
+[project.urls]
+Homepage = "https://github.com/britram/python-ipfix"
+Repository = "https://github.com/britram/python-ipfix"
+Issues = "https://github.com/britram/python-ipfix/issues"
+
+[project.scripts]
+ipfix2csv = "ipfix.cli:main_ipfix2csv"
+ipfixstat = "ipfix.cli:main_ipfixstat"
+
+[project.optional-dependencies]
+docs = ["sphinx>=7.0"]
+
+[dependency-groups]
+dev = [
+ "pytest>=8.0",
+ "pytest-cov>=5.0",
+ "ruff>=0.8",
+]
+
+[tool.hatch.build.targets.wheel]
+packages = ["ipfix"]
+
+[tool.pytest.ini_options]
+addopts = "--doctest-modules --cov=ipfix --cov-report=term-missing"
+testpaths = ["tests", "ipfix"]
+filterwarnings = [
+ "error",
+]
+
+[tool.coverage.run]
+source = ["ipfix"]
+omit = ["ipfix/testutils.py"]
+
+[tool.ruff]
+target-version = "py311"
+line-length = 100
+
+[tool.ruff.lint]
+select = ["E", "F", "W", "I", "UP", "B"]
+ignore = ["E501"]
diff --git a/scripts/collector_test.py b/scripts/collector_test.py
index 32cb301..48136de 100755
--- a/scripts/collector_test.py
+++ b/scripts/collector_test.py
@@ -1,13 +1,13 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
+import argparse
import socketserver
-import ipfix.reader
-import ipfix.ie
-import argparse
+import ipfix.ie
+import ipfix.reader
-ap = argparse.ArgumentParser(description="Dump IPFIX files collected over TCP")
-ap.add_argument('--spec', metavar='specfile', help='iespec file to read')
+ap = argparse.ArgumentParser(description="Dump IPFIX records collected over TCP")
+ap.add_argument("--spec", metavar="specfile", help="iespec file to read")
args = ap.parse_args()
ipfix.ie.use_iana_default()
@@ -17,19 +17,19 @@
class CollectorDictHandler(socketserver.StreamRequestHandler):
-
def handle(self):
reccount = 0
- print ("connection from "+str(self.client_address))
+ print("connection from " + str(self.client_address))
r = ipfix.reader.from_stream(self.rfile)
- for rec in r.records_as_dict():
- print("--- record %u in message %u from %s---" %
- (reccount, r.msgcount, str(self.client_address)))
+ for rec in r.namedict_iterator():
+ print(
+ f"--- record {reccount} in message {r.msgcount} from {self.client_address} ---"
+ )
reccount += 1
- for key in rec:
- print(" %30s => %s" % (key, str(rec[key])))
+ for key, value in rec.items():
+ print(f" {key:>30s} => {value}")
-ss = socketserver.TCPServer(("", 4739), CollectorDictHandler)
-ss.serve_forever()
+with socketserver.TCPServer(("", 4739), CollectorDictHandler) as ss:
+ ss.serve_forever()
diff --git a/scripts/ipfix2csv b/scripts/ipfix2csv
index 602d034..7f062d2 100755
--- a/scripts/ipfix2csv
+++ b/scripts/ipfix2csv
@@ -1,129 +1,7 @@
#!/usr/bin/env python3
-#
-# python-ipfix (c) 2013-2014 Brian Trammell.
-#
-# Many thanks to the mPlane consortium (http://www.ict-mplane.eu) for
-# its material support of this effort.
-#
-# This program is free software: you can redistribute it and/or modify it under
-# the terms of the GNU Lesser General Public License as published by the Free
-# Software Foundation, either version 3 of the License, or (at your option) any
-# later version.
-#
-# This program is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
-# details.
-#
-# You should have received a copy of the GNU General Public License along with
-# this program. If not, see .
-#
+"""Thin wrapper for the ipfix2csv CLI entry point."""
-import ipfix.ie
-import ipfix.reader
-import ipfix.message
-import ipfix.v9pdu
-
-import socketserver
-import argparse
-import csv
-import bz2
-import gzip
-
-from sys import stdin, stdout, stderr
-
-def parse_args():
- parser = argparse.ArgumentParser(description="Convert an IPFIX file or stream to CSV")
- parser.add_argument('ienames', metavar="ie", nargs="+",
- help="column(s) by IE name")
- parser.add_argument('--spec', '-s', metavar="specfile", action="append",
- help="file to load additional IESpecs from")
- parser.add_argument('--file', '-f', metavar="file", nargs="?",
- help="IPFIX file to read (default stdin)")
- parser.add_argument('--gzip', '-z', action="store_const", const=True,
- help="Decompress gzip-compressed IPFIX file")
- parser.add_argument('--bzip2', '-j', action="store_const", const=True,
- help="Decompress bz2-compressed IPFIX file")
- parser.add_argument('--netflow9', '-9', action="store_const", const=True,
- help="Decode as NetFlow version 9 instead of IPFIX (with --file or stdin only)")
- parser.add_argument('--collect', '-c', metavar="transport", nargs="?",
- help="run CP on specified transport")
- parser.add_argument('--bind', '-b', metavar="bind", nargs="?",
- default="", help="address to bind to as CP (default all)")
- parser.add_argument('--port', '-p', metavar="port", nargs="?", type=int,
- default="4739", help="port to bind to as CP (default 4739)")
- return parser.parse_args()
-
-def init_ipfix(specfiles = None):
- ipfix.ie.use_iana_default()
- ipfix.ie.use_5103_default()
-
- if specfiles:
- for sf in specfiles:
- ipfix.ie.use_specfile(sf)
-
-def stream_to_csv(instream, ienames, reader_fn=ipfix.reader.from_stream):
- cols = ipfix.ie.spec_list(ienames)
-
- r = reader_fn(instream)
- w = csv.writer(stdout, dialect='unix')
-
- w.writerow([e.name for e in cols])
-
- for rec in r.tuple_iterator(cols):
- w.writerow([col.unparse(val) for val, col in zip(rec, cols)])
-
-class TcpCsvHandler(socketserver.StreamRequestHandler):
- def handle(self):
- stderr.write("connection from "+str(self.client_address)+"\n")
- stream_to_csv(self.rfile, args.ienames)
-
-#######################################################################
-# MAIN PROGRAM
-#######################################################################
+from ipfix.cli import main_ipfix2csv
if __name__ == "__main__":
-
- # get args
- args = parse_args()
-
- # initialize information model
- init_ipfix(args.spec)
-
- # select reader creator function
- if args.netflow9:
- reader_fn = ipfix.v9pdu.from_stream
- else:
- reader_fn = ipfix.reader.from_stream
-
- # die on invalid arguments
- if args.netflow9 and args.collect:
- raise ValueError("NetFlow9 only supported from files or stdin")
-
- if args.file is None and (args.bzip2 or args.gzip):
- raise ValueError("Decompression only supported from file input")
-
- # now run the gauntlet
- if args.collect == 'tcp':
- stderr.write("starting TCP CP on "+args.bind+":"+
- str(args.port)+"; Ctrl-C to stop\n")
- stderr.flush()
- ss = socketserver.TCPServer((args.bind, args.port), TcpCsvHandler)
- ss.serve_forever()
-
- elif args.collect:
- raise ValueError("Unsupported transport "+args.collect+"; must be 'tcp' in this revision")
-
- elif args.file:
- if args.bzip2:
- with bz2.open (args.file, mode="rb") as f:
- stream_to_csv(f, args.ienames, reader_fn)
- elif args.gzip:
- with gzip.open (args.file, mode="rb") as f:
- stream_to_csv(f, args.ienames, reader_fn)
- else:
- with open (args.file, mode="rb") as f:
- stream_to_csv(f, args.ienames, reader_fn)
- else:
- stdin = stdin.detach()
- stream_to_csv(stdin, args.ienames, reader_fn)
\ No newline at end of file
+ main_ipfix2csv()
diff --git a/scripts/ipfixstat b/scripts/ipfixstat
index db72d10..e55f469 100644
--- a/scripts/ipfixstat
+++ b/scripts/ipfixstat
@@ -1,193 +1,7 @@
#!/usr/bin/env python3
-#
-# python-ipfix (c) 2013-2014 Brian Trammell.
-#
-# Many thanks to the mPlane consortium (http://www.ict-mplane.eu) for
-# its material support of this effort.
-#
-# This program is free software: you can redistribute it and/or modify it under
-# the terms of the GNU Lesser General Public License as published by the Free
-# Software Foundation, either version 3 of the License, or (at your option) any
-# later version.
-#
-# This program is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
-# details.
-#
-# You should have received a copy of the GNU General Public License along with
-# this program. If not, see .
-#
+"""Thin wrapper for the ipfixstat CLI entry point."""
-import ipfix.ie
-import ipfix.reader
-import ipfix.template
-import ipfix.message
-import ipfix.v9pdu
-
-import argparse
-import csv
-import bz2
-import gzip
-
-from functools import reduce
-import operator
-
-from sys import stdin, stdout, stderr
-
-def parse_args():
- parser = argparse.ArgumentParser(description="Dump statistics about templates and data sets in an IPFIX file")
- parser.add_argument('--spec', '-s', metavar="specfile", action="append",
- help="file to load additional IESpecs from")
- parser.add_argument('--file', '-f', metavar="file", nargs="?",
- help="IPFIX file to read (default stdin)")
- parser.add_argument('--gzip', '-z', action="store_const", const=True,
- help="Decompress gzip-compressed IPFIX file")
- parser.add_argument('--bzip2', '-j', action="store_const", const=True,
- help="Decompress bz2-compressed IPFIX file")
- parser.add_argument('--netflow9', '-9', action="store_const", const=True,
- help="Decode as NetFlow version 9 instead of IPFIX")
- return parser.parse_args()
-
-def init_ipfix(specfiles = None):
- ipfix.ie.use_iana_default()
- ipfix.ie.use_5103_default()
-
- if specfiles:
- for sf in specfiles:
- ipfix.ie.use_specfile(sf)
-
-def dump_template(odid, tmpl):
- if tmpl.scopecount:
- print("#\n# Options Template "+str(tmpl.tid)+" in domain "+str(odid)+
- " ("+str(len(tmpl.ies))+" IEs)\n#")
- else:
- print("#\n# Template "+str(tmpl.tid)+" in domain "+str(odid)+
- " ("+str(len(tmpl.ies))+" IEs)\n#")
-
- for i, ie in enumerate(tmpl.ies):
- if i < tmpl.scopecount:
- addl = "{scope}"
- else:
- addl = ""
- print(str(ie)+addl)
-
-class TemplateStatsSession():
-
- def __init__(self, instream, netflow9=False):
- self.templates = {}
- self.template_count = {}
- self.template_replcount = {}
- self.template_setcount = {}
- self.template_bytecount = {}
- self.missing_setcount = {}
- self.missing_bytecount = {}
-
- if netflow9:
- self.r = ipfix.v9pdu.from_stream(instream)
- self.r.template_record_hook = self.handle_template_record
- self.r.ignored_data_set_hook = self.handle_data_set
- self.r.unknown_data_set_hook = self.handle_unknown_set
- else:
- self.r = ipfix.reader.from_stream(instream)
- self.r.msg.template_record_hook = self.handle_template_record
- self.r.msg.ignored_data_set_hook = self.handle_data_set
- self.r.msg.unknown_data_set_hook = self.handle_unknown_set
-
- def handle_template_record(self, msg, tmpl):
- tkey = (msg.odid, tmpl.tid)
-
- # count templates per key, check for replacements
- if tkey in self.templates:
- self.template_count[tkey] += 1
- if not self.templates[tkey].identical_to(tmpl):
- self.template_replcount[tkey] += 1
- self.templates[tkey] = tmpl
- else:
- self.templates[tkey] = tmpl
- self.template_count[tkey] = 1
- self.template_replcount[tkey] = 0
- self.template_setcount[tkey] = 0
- self.template_bytecount[tkey] = 0
-
- def handle_data_set(self, msg, tmpl, setbuf):
- tkey = (msg.odid, tmpl.tid)
-
- self.template_setcount[tkey] += 1
- self.template_bytecount[tkey] += len(setbuf)
-
- def handle_unknown_set(self, msg, setbuf):
- (setid, setlen) = ipfix.message._sethdr_st.unpack_from(setbuf)
- tkey = (msg.odid, setid)
-
- if tkey in self.missing_setcount:
- self.missing_setcount[tkey] += 1
- self.missing_bytecount[tkey] += setlen
- else:
- self.missing_setcount[tkey] = 1
- self.missing_bytecount[tkey] = setlen
-
- def run(self):
- # trick: to run a collector without actually collecting anything,
- # attach an ignored set hook then try to get a tuple containing
- # an IE we'll never see.
- for rec in self.r.tuple_iterator(ipfix.ie.spec_list(["impossible(35566/32767)[1]"])):
- pass
-
- def print_report(self):
- missing_setcount = self.missing_setcount.copy()
-
- print("#\n# %u templates, %u template sets, %u decodable sets, %u replacements, %u missing sets total" %
- (len(self.templates),
- reduce(operator.add, self.template_count.values()),
- reduce(operator.add, self.template_setcount.values()),
- reduce(operator.add, self.template_replcount.values()),
- reduce(operator.add, self.missing_setcount.values(), 0)))
-
- for tkey in sorted(self.templates.keys()):
- dump_template(tkey[0], self.templates[tkey])
- print("# %u instances %u replacements %u sets %u bytes "
- % (self.template_count[tkey], self.template_replcount[tkey],
- self.template_setcount[tkey], self.template_bytecount[tkey]))
- if tkey in missing_setcount:
- print("# %u sets missing template with this ID" % missing_setcount[tkey])
- del(missing_setcount[tkey])
-
- if len(missing_setcount):
- print("#\n# Sets without templates")
- for tkey in missing_setcount:
- print("# %u sets missing template with ID %u in domain %u" %
- (missing_setcount[tkey], tkey[1], tkey[0]))
-
-#######################################################################
-# MAIN PROGRAM
-#######################################################################
+from ipfix.cli import main_ipfixstat
if __name__ == "__main__":
-
- # get args
- args = parse_args()
-
- # initialize information model
- init_ipfix(args.spec)
-
-
- if args.file:
- if args.bzip2:
- with bz2.open (args.file, mode="rb") as f:
- tss = TemplateStatsSession(f, args.netflow9)
- tss.run()
- elif args.gzip:
- with gzip.open (args.file, mode="rb") as f:
- tss = TemplateStatsSession(f, args.netflow9)
- tss.run()
- else:
- with open (args.file, mode="rb") as f:
- tss = TemplateStatsSession(f, args.netflow9)
- tss.run()
- else:
- stdin = stdin.detach()
- tss = TemplateStatsSession(stdin, args.netflow9)
- tss.run()
-
- tss.print_report()
\ No newline at end of file
+ main_ipfixstat()
diff --git a/setup.cfg b/setup.cfg
deleted file mode 100644
index 785a593..0000000
--- a/setup.cfg
+++ /dev/null
@@ -1,5 +0,0 @@
-[nosetests]
-with-doctest=1
-with-doctest-ignore-unicode=1
-with-coverage=1
-cover-package=ipfix
diff --git a/setup.py b/setup.py
deleted file mode 100755
index d856003..0000000
--- a/setup.py
+++ /dev/null
@@ -1,29 +0,0 @@
-#!/usr/bin/env python3
-
-from __future__ import with_statement
-from setuptools import setup
-from io import open
-
-with open('README.txt') as file:
- long_description = file.read()
-
-setup(name='ipfix',
- version='0.9.8',
- description='IPFIX implementation for Python 3.3+',
- long_description = long_description,
- author='Brian Trammell',
- author_email='brian@trammell.ch',
- url='http://github.com/britram/python-ipfix',
- packages=['ipfix'],
- package_data={'ipfix': ['iana.iespec', 'rfc5103.iespec']},
- scripts=['scripts/ipfix2csv', 'scripts/ipfixstat'],
- classifiers=["Development Status :: 3 - Alpha",
- "Intended Audience :: Developers",
- "License :: OSI Approved :: "
- "GNU Lesser General Public License v3 or later (LGPLv3+)",
- "Operating System :: OS Independent",
- "Programming Language :: Python :: 3.3",
- "Topic :: System :: Networking"],
- tests_require=['nose', 'coverage', 'doctest-ignore-unicode'],
- )
-
diff --git a/sphinx/conf.py b/sphinx/conf.py
index 41fb1fb..7f95eab 100755
--- a/sphinx/conf.py
+++ b/sphinx/conf.py
@@ -42,16 +42,16 @@
# General information about the project.
project = 'python-ipfix'
-copyright = '2013-2014, Brian Trammell'
+copyright = '2013-2026, Brian Trammell'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
-version = '0.9'
+version = '0.10'
# The full version, including alpha/beta/rc tags.
-release = '0.9.8'
+release = '0.10.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
@@ -255,7 +255,7 @@
epub_title = 'python-ipfix'
epub_author = 'Brian Trammell'
epub_publisher = 'Brian Trammell'
-epub_copyright = '2013-2014, Brian Trammell'
+epub_copyright = '2013-2026, Brian Trammell'
# The language of the text. It defaults to the language option
# or en if the language is not set.
@@ -308,4 +308,4 @@
# Example configuration for intersphinx: refer to the Python standard library.
-intersphinx_mapping = {'http://docs.python.org/': None}
+intersphinx_mapping = {'python': ('https://docs.python.org/3', None)}
diff --git a/tests/test_ie.py b/tests/test_ie.py
new file mode 100644
index 0000000..b3e518e
--- /dev/null
+++ b/tests/test_ie.py
@@ -0,0 +1,139 @@
+import ipaddress
+
+import pytest
+
+import ipfix.ie as ie
+import ipfix.types as types
+
+
+@pytest.fixture(autouse=True)
+def clean_infomodel():
+ ie.clear_infomodel()
+ yield
+ ie.clear_infomodel()
+
+
+def test_iana_and_5103_2026_registry_loaded():
+ ie.use_iana_default()
+ ie.use_5103_default()
+
+ # Classic IE
+ e1 = ie.for_spec("octetDeltaCount")
+ assert (e1.pen, e1.num, e1.length) == (0, 1, 8)
+
+ # Modern 2026 IEs (RFC 9487, RFC 9740 unsigned256, RFC 9951)
+ tcp_full = ie.for_spec("tcpOptionsFull")
+ assert tcp_full.num == 520
+ assert tcp_full.type.name == "unsigned256"
+ assert tcp_full.length == 32
+
+ udp_safe = ie.for_spec("udpSafeOptions")
+ assert udp_safe.num == 525
+ assert udp_safe.type.name == "unsigned256"
+
+ delay = ie.for_spec("pathDelaySumDeltaMicroseconds")
+ assert delay.num == 533
+ assert delay.type.name == "unsigned64"
+
+ # RFC 5103 reverse counterpart
+ rev = ie.for_spec("reverseOctetDeltaCount")
+ assert (rev.pen, rev.num) == (29305, 1)
+
+ dumped = ie.dump_infomodel()
+ assert len(dumped) > 900
+
+
+def test_ie_equality_and_hash_invariant():
+ ie.use_iana_default()
+ a = ie.for_spec("octetDeltaCount")
+ b = ie.for_spec("octetDeltaCount[4]")
+ assert a.length == 8
+ assert b.length == 4
+ assert a == b
+ assert hash(a) == hash(b)
+ assert len({a, b}) == 1
+
+
+def test_ie_list_hash_and_ordering():
+ la = ie.InformationElementList(
+ [ie.InformationElement(None, 35566, 9999, length=1)]
+ )
+ lb = ie.InformationElementList(
+ [ie.InformationElement(None, 35566, 9999, length=4)]
+ )
+ lc = ie.InformationElementList([ie.InformationElement(None, 35566, 9998)])
+
+ assert la[0].name == "_ipfix_35566_9999"
+ assert la == lb
+ assert la > lc
+ assert len(la) == 1
+ assert "35566/9999" in str(la)
+ assert "InformationElementList" in repr(la)
+
+ # Empty list hashable without AttributeError/TypeError
+ empty = ie.InformationElementList()
+ assert hash(empty) == hash(ie.InformationElementList())
+
+ # Order-sensitive hash
+ ie.use_iana_default()
+ l1 = ie.spec_list(["octetDeltaCount", "packetDeltaCount"])
+ l2 = ie.spec_list(["packetDeltaCount", "octetDeltaCount"])
+ assert l1 != l2
+ assert hash(l1) != hash(l2)
+ assert l1.index(ie.for_spec("packetDeltaCount")) == 1
+
+
+def test_unknown_template_entry_does_not_leak_globally():
+ ie.use_iana_default()
+ before = len(ie._ieForNum)
+
+ elem = ie.for_template_entry(35566, 9999, 4)
+ assert elem.name == "_ipfix_35566_9999"
+ assert elem.length == 4
+ assert elem.type.name == "octetArray"
+
+ # Must NOT have been inserted into global registry
+ assert len(ie._ieForNum) == before
+ assert (35566, 9999) not in ie._ieForNum
+
+
+def test_parse_unparse_and_custom_overrides():
+ ie.use_iana_default()
+ assert ie.for_spec("sourceIPv4Address").parse("192.0.2.19") == ipaddress.IPv4Address(
+ "192.0.2.19"
+ )
+ # RLE and fixed-length string unparse/parse (regression for StructType arg bug)
+ rle_ie = ie.for_spec("octetDeltaCount[4]")
+ assert rle_ie.unparse(42) == "42"
+ assert rle_ie.parse("42") == 42
+
+ fixed_str = ie.for_spec("wlanSSID[14]")
+ assert fixed_str.unparse("ietf") == "ietf"
+ assert fixed_str.parse("ietf") == "ietf"
+
+ custom = ie.InformationElement(
+ "custom",
+ 35566,
+ 1,
+ types.for_name("unsigned8"),
+ valstr=lambda v: f"v={v}",
+ valparse=lambda s: int(s.split("=")[1]),
+ )
+ assert custom.unparse(7) == "v=7"
+ assert custom.parse("v=7") == 7
+ assert custom.for_length(1).unparse(7) == "v=7"
+
+
+def test_for_spec_errors_and_specfile(tmp_path):
+ with pytest.raises(ValueError):
+ ie.for_spec("")
+ with pytest.raises(ValueError):
+ ie.for_spec("not_a_known_ie")
+
+ specfile = tmp_path / "custom.iespec"
+ specfile.write_text(
+ "# comment line\n\nmyCustomIE(35566/42)[4]\n", encoding="utf-8"
+ )
+ ie.use_specfile(specfile)
+ e = ie.for_spec("myCustomIE")
+ assert (e.pen, e.num, e.length) == (35566, 42, 4)
diff --git a/tests/test_ieutils_cli.py b/tests/test_ieutils_cli.py
new file mode 100644
index 0000000..caf61b2
--- /dev/null
+++ b/tests/test_ieutils_cli.py
@@ -0,0 +1,145 @@
+import bz2
+import gzip
+import io
+import struct
+from ipaddress import ip_address
+
+import pytest
+
+import ipfix.cli as cli
+import ipfix.ie as ie
+import ipfix.ieutils as ieutils
+import ipfix.testutils as testutils
+
+
+@pytest.fixture(autouse=True)
+def setup_iana():
+ ie.clear_infomodel()
+ ie.use_iana_default()
+ yield
+ ie.clear_infomodel()
+
+
+def test_ieutils_csv_xml_reverse_and_write(tmp_path):
+ csv_data = io.StringIO(
+ "ElementID,Name,Abstract Data Type,Status\n"
+ "1,octetDeltaCount,unsigned64,current\n"
+ "520,tcpOptionsFull,unsigned256,current\n"
+ "291,basicListExample,basicList,current\n"
+ "0,Reserved,,\n"
+ )
+ specs = ieutils.parse_iana_csv(csv_data)
+ assert specs == [
+ "octetDeltaCount(1)[8]",
+ "tcpOptionsFull(520)[32]",
+ ]
+
+ xml_data = io.BytesIO(
+ b''
+ b' '
+ b" "
+ b" 1 "
+ b" octetDeltaCount "
+ b" unsigned64 "
+ b" ignoredNestedName"
+ b" "
+ b" "
+ b" 291"
+ b" basicListExample"
+ b" basicList"
+ b" "
+ b" "
+ b""
+ )
+ assert ieutils.parse_iana_xml(xml_data) == ["octetDeltaCount(1)[8]"]
+
+ assert (
+ ieutils.reverse_iespec("octetDeltaCount(1)[8]")
+ == "reverseOctetDeltaCount(29305/1)[8]"
+ )
+ assert (
+ ieutils.reverse_iespec("myMetric(35566/5)[4]")
+ == "reverseMyMetric(35566/16389)[4]"
+ )
+ assert ieutils.is_reversible_ie("octetDeltaCount") is True
+ assert ieutils.is_reversible_ie("sourceIPv4Address") is False
+ assert ieutils.is_reversible_ie("messageScope") is False
+
+ out = tmp_path / "out.iespec"
+ ieutils.write_specfile(out, specs)
+ assert out.read_text(encoding="utf-8").splitlines() == specs
+
+
+def test_cli_ipfix2csv_and_ipfixstat(tmp_path, capsys):
+ raw = testutils._stored_test_message
+ plain_file = tmp_path / "test.ipfix"
+ gz_file = tmp_path / "test.ipfix.gz"
+ bz2_file = tmp_path / "test.ipfix.bz2"
+ plain_file.write_bytes(raw)
+ with gzip.open(gz_file, "wb") as f:
+ f.write(raw)
+ with bz2.open(bz2_file, "wb") as f:
+ f.write(raw)
+
+ # stream_to_csv directly
+ out = io.StringIO()
+ cli.stream_to_csv(
+ io.BytesIO(raw), ["sourceIPv4Address", "packetDeltaCount"], outstream=out
+ )
+ lines = out.getvalue().strip().splitlines()
+ assert len(lines) == 129 # header + 128 records
+ assert '"sourceIPv4Address","packetDeltaCount"' in lines[0]
+
+ # main_ipfix2csv with plain, gzip, bzip2
+ for flag, path in [
+ ([], plain_file),
+ (["-z"], gz_file),
+ (["-j"], bz2_file),
+ ]:
+ cli.main_ipfix2csv([*flag, "-f", str(path), "sourceIPv4Address", "packetDeltaCount"])
+ captured = capsys.readouterr().out.splitlines()
+ assert len(captured) == 129
+
+ # Invalid argument combinations
+ with pytest.raises(ValueError):
+ cli.main_ipfix2csv(["-9", "-c", "tcp", "sourceIPv4Address"])
+ with pytest.raises(ValueError):
+ cli.main_ipfix2csv(["-z", "sourceIPv4Address"])
+ with pytest.raises(ValueError):
+ cli.main_ipfix2csv(["-c", "sctp", "sourceIPv4Address"])
+
+ # main_ipfixstat with plain, gzip, bzip2
+ for flag, path in [
+ ([], plain_file),
+ (["-z"], gz_file),
+ (["-j"], bz2_file),
+ ]:
+ cli.main_ipfixstat([*flag, "-f", str(path)])
+ report = capsys.readouterr().out
+ assert "1 templates, 1 template sets, 1 decodable sets" in report
+ assert "Template 257 in domain 8304" in report
+
+ # NetFlow v9 via ipfixstat
+ tset = struct.pack("!HH HH HH", 0, 12, 256, 1, 8, 4)
+ dset = struct.pack("!HH 4s", 256, 8, ip_address("10.0.0.1").packed)
+ v9_raw = struct.pack("!HHLLLL", 9, 1, 1000, 1700000000, 1, 7) + tset + dset
+ v9_file = tmp_path / "test.v9"
+ v9_file.write_bytes(v9_raw)
+ cli.main_ipfixstat(["-9", "-f", str(v9_file)])
+ v9_report = capsys.readouterr().out
+ assert "Template 256 in domain 7" in v9_report
+
+ # ipfixstat invalid stdin compression & zero IE cache pollution
+ with pytest.raises(ValueError):
+ cli.main_ipfixstat(["-z"])
+ with pytest.raises(SystemExit):
+ cli.main_ipfixstat(["-z", "-j", "-f", str(plain_file)])
+
+ ie.clear_infomodel()
+ ie.use_iana_default()
+ before_names = set(ie._ieForName)
+ before_nums = set(ie._ieForNum)
+ tss = cli.TemplateStatsSession(io.BytesIO(raw))
+ tss.run()
+ assert set(ie._ieForName) == before_names
+ assert set(ie._ieForNum) == before_nums
diff --git a/tests/test_reader_writer.py b/tests/test_reader_writer.py
new file mode 100644
index 0000000..84b9b0c
--- /dev/null
+++ b/tests/test_reader_writer.py
@@ -0,0 +1,143 @@
+import io
+from datetime import datetime
+from ipaddress import ip_address
+
+import pytest
+
+import ipfix.ie as ie
+import ipfix.reader as reader
+import ipfix.template as template
+import ipfix.writer as writer
+
+
+@pytest.fixture(autouse=True)
+def setup_iana():
+ ie.clear_infomodel()
+ ie.use_iana_default()
+ yield
+ ie.clear_infomodel()
+
+
+def test_writer_and_reader_multimessage_roundtrip():
+ buf = io.BytesIO()
+ # Small MTU forces multiple messages to be flushed automatically
+ w = writer.to_stream(buf, mtu=128)
+ w.set_domain(100)
+ tmpl = template.for_specs(
+ 256,
+ "flowStartMilliseconds",
+ "sourceIPv4Address",
+ "packetDeltaCount",
+ )
+ w.add_template(tmpl)
+ w.set_export_template(256)
+
+ expected = []
+ for i in range(25):
+ rec = {
+ "flowStartMilliseconds": datetime(2024, 1, 1, 0, 0, i),
+ "sourceIPv4Address": ip_address(0x0A000001 + i),
+ "packetDeltaCount": i * 10,
+ }
+ expected.append(rec)
+ if i % 2 == 0:
+ w.export_namedict(rec)
+ else:
+ w.export_tuple(
+ (
+ rec["flowStartMilliseconds"],
+ rec["sourceIPv4Address"],
+ rec["packetDeltaCount"],
+ )
+ )
+ w.flush()
+ assert w.msgcount > 1
+
+ # Namedict stream read
+ buf.seek(0)
+ r = reader.from_stream(buf)
+ got = list(r.namedict_iterator())
+ assert got == expected
+ assert r.msgcount == w.msgcount
+
+ # Tuple stream read
+ buf.seek(0)
+ r2 = reader.from_stream(buf)
+ ielist = ie.spec_list(["packetDeltaCount", "sourceIPv4Address"])
+ tups = list(r2.tuple_iterator(ielist))
+ assert tups == [
+ (rec["packetDeltaCount"], rec["sourceIPv4Address"]) for rec in expected
+ ]
+ assert r2.msgcount == w.msgcount
+
+
+def test_writer_set_domain_and_flush_edge_cases():
+ buf = io.BytesIO()
+ w = writer.to_stream(buf, mtu=96)
+ w.set_domain(1)
+ # Flush right after begin_export (empty message, cursetid is None) is a no-op
+ w.flush()
+ assert w.msgcount == 0
+
+ t1 = template.for_specs(256, "sourceIPv4Address", "packetDeltaCount")
+ w.add_template(t1)
+ w.set_export_template(256)
+ w.export_namedict(
+ {"sourceIPv4Address": ip_address("192.0.2.1"), "packetDeltaCount": 1}
+ )
+
+ # Switching domain flushes previous domain and increments msgcount
+ prev_count = w.msgcount
+ w.set_domain(2)
+ assert w.msgcount == prev_count + 1
+
+ t2 = template.for_specs(257, "sourceIPv4Address", "octetDeltaCount")
+ w.add_template(t2)
+ w.set_export_template(257)
+ w.export_namedict(
+ {"sourceIPv4Address": ip_address("192.0.2.2"), "octetDeltaCount": 500}
+ )
+ w.flush()
+
+ buf.seek(0)
+ r = reader.from_stream(buf)
+ recs = list(r.namedict_iterator())
+ assert len(recs) == 2
+ assert recs[0]["packetDeltaCount"] == 1
+ assert recs[1]["octetDeltaCount"] == 500
+
+
+def test_writer_without_set_domain_and_no_empty_sets():
+ buf = io.BytesIO()
+ w = writer.to_stream(buf, mtu=64)
+ t1 = template.for_specs(256, "sourceIPv4Address", "packetDeltaCount")
+ # Using writer without calling set_domain() defaults to ODID 0
+ w.add_template(t1)
+ w.flush()
+ w.set_export_template(256)
+ w.export_namedict(
+ {"sourceIPv4Address": ip_address("10.0.0.1"), "packetDeltaCount": 1}
+ )
+ w.flush()
+
+ # After set_domain(), exporting without set_export_template() raises IpfixEncodeError
+ w.set_domain(5)
+ with pytest.raises(writer.message.IpfixEncodeError):
+ w.export_namedict(
+ {"sourceIPv4Address": ip_address("10.0.0.2"), "packetDeltaCount": 2}
+ )
+
+ # Verify wire stream has no empty 4-byte sets and preserves ODID 0
+ buf.seek(0)
+ r = reader.from_stream(buf)
+ r.msg.read_message(buf)
+ assert r.msg.odid == 0
+ assert [(sid, slen) for _, sid, slen in r.msg.setlist] == [(2, 16)]
+ r.msg.read_message(buf)
+ assert [(sid, slen) for _, sid, slen in r.msg.setlist] == [(256, 16)]
+
+ buf.seek(0)
+ recs = list(reader.from_stream(buf).namedict_iterator())
+ assert recs == [
+ {"sourceIPv4Address": ip_address("10.0.0.1"), "packetDeltaCount": 1}
+ ]
diff --git a/tests/test_template_message.py b/tests/test_template_message.py
new file mode 100644
index 0000000..912a201
--- /dev/null
+++ b/tests/test_template_message.py
@@ -0,0 +1,497 @@
+import struct
+from datetime import datetime
+from ipaddress import ip_address
+
+import pytest
+
+import ipfix.ie as ie
+import ipfix.message as message
+import ipfix.template as template
+import ipfix.testutils as testutils
+from ipfix.template import IpfixDecodeError, IpfixEncodeError
+
+
+@pytest.fixture(autouse=True)
+def setup_iana():
+ ie.clear_infomodel()
+ ie.use_iana_default()
+ yield
+ ie.clear_infomodel()
+
+
+def test_stored_message_roundtrip():
+ generated = testutils.mktest_message().to_bytes()
+ assert testutils._stored_test_message == generated
+
+ msg = message.MessageBuffer()
+ msg.from_bytes(testutils._stored_test_message)
+ recs = list(msg.namedict_iterator())
+ assert len(recs) == 128
+ for i, rec in enumerate(recs):
+ trec = testutils.mktest_record(i)
+ assert rec["packetDeltaCount"] == trec["packetDeltaCount"]
+ assert rec["octetDeltaCount"] == trec["octetDeltaCount"]
+ assert rec["sourceIPv4Address"] == trec["sourceIPv4Address"]
+ assert rec["testString"] == trec["testString"]
+ assert testutils.fuzzy_datetime_compare(
+ rec["flowStartMilliseconds"], trec["flowStartMilliseconds"]
+ )
+
+
+def test_varlen_first_ie_issue24():
+ """Regression test for Issue #24 / PR #25 / PR #30: varlen as first IE."""
+ tmpl = template.for_specs(
+ 256,
+ "applicationName",
+ "flowStartMilliseconds",
+ "sourceIPv4Address",
+ "packetDeltaCount",
+ )
+ assert tmpl.varlenslice == 0
+
+ msg = message.MessageBuffer()
+ msg.begin_export(8304)
+ msg.add_template(tmpl)
+ msg.export_ensure_set(256)
+
+ long_name = "x" * 300 # also exercises 255-byte extended varlen encoding
+ rec_in = {
+ "applicationName": long_name,
+ "flowStartMilliseconds": datetime(2024, 1, 2, 3, 4, 5),
+ "sourceIPv4Address": ip_address("10.1.2.3"),
+ "packetDeltaCount": 99,
+ }
+ msg.export_namedict(rec_in)
+ raw = msg.to_bytes()
+
+ msg2 = message.MessageBuffer()
+ msg2.from_bytes(raw)
+ recs = list(msg2.namedict_iterator())
+ assert len(recs) == 1
+ assert recs[0] == rec_in
+
+ # Tuple iterator with varlen first IE
+ ielist = ie.spec_list(["packetDeltaCount", "applicationName"])
+ tups = list(msg2.tuple_iterator(ielist))
+ assert tups == [(99, long_name)]
+
+
+def test_template_set_padding_pr30():
+ """RFC 7011 §3.3.1: zero alignment padding at the end of a Template Set."""
+ tmpl = template.for_specs(256, "sourceIPv4Address", "packetDeltaCount")
+ for pad_len in (1, 2, 3, 4, 6):
+ # Build a message with a Template Set padded with pad_len zero bytes
+ tbuf = bytearray(64)
+ toff = tmpl.encode_template_to(tbuf, 0, template.TEMPLATE_SET_ID)
+ tset_body = bytes(tbuf[:toff]) + (b"\x00" * pad_len)
+ tset = struct.pack("!HH", template.TEMPLATE_SET_ID, 4 + len(tset_body)) + tset_body
+ raw = struct.pack("!HHLLL", 10, 16 + len(tset), 1700000000, 0, 1) + tset
+
+ msg = message.MessageBuffer()
+ msg.from_bytes(raw)
+ assert list(msg.namedict_iterator()) == []
+ assert (1, 256) in msg.templates
+
+ # Non-zero trailing bytes (< 4 bytes) must raise IpfixDecodeError
+ tbuf = bytearray(64)
+ toff = tmpl.encode_template_to(tbuf, 0, template.TEMPLATE_SET_ID)
+ tset_body = bytes(tbuf[:toff]) + b"\x00\x01"
+ tset = struct.pack("!HH", template.TEMPLATE_SET_ID, 4 + len(tset_body)) + tset_body
+ raw = struct.pack("!HHLLL", 10, 16 + len(tset), 1700000000, 0, 1) + tset
+ msg = message.MessageBuffer()
+ msg.from_bytes(raw)
+ with pytest.raises(IpfixDecodeError):
+ list(msg.namedict_iterator())
+
+
+def test_template_withdrawal_export_and_decode():
+ tmpl = template.for_specs(256, "sourceIPv4Address", "packetDeltaCount")
+ msg = message.MessageBuffer()
+ msg.begin_export(42)
+ msg.add_template(tmpl)
+ msg.export_ensure_set(256)
+ msg.export_namedict(
+ {"sourceIPv4Address": ip_address("192.0.2.1"), "packetDeltaCount": 5}
+ )
+ msg.delete_template(256, export=True)
+ raw = msg.to_bytes()
+
+ # Decode: data set decoded before withdrawal, template removed after withdrawal
+ seen_templates = []
+ msg2 = message.MessageBuffer()
+ msg2.template_record_hook = lambda m, t: seen_templates.append((t.tid, t.count()))
+ msg2.from_bytes(raw)
+ recs = list(msg2.namedict_iterator())
+ assert len(recs) == 1
+ assert (42, 256) not in msg2.templates
+ assert seen_templates == [(256, 2), (256, 0)]
+
+ # All-Templates Withdrawal (TID == 2, count == 0)
+ msg3 = message.MessageBuffer()
+ msg3.begin_export(42)
+ msg3.add_template(template.for_specs(256, "sourceIPv4Address"))
+ msg3.add_template(template.for_specs(257, "packetDeltaCount"))
+ msg3._export_template_withdrawal(template.TEMPLATE_SET_ID, template.TEMPLATE_SET_ID)
+ raw_all = msg3.to_bytes()
+
+ msg4 = message.MessageBuffer()
+ msg4.from_bytes(raw_all)
+ assert list(msg4.namedict_iterator()) == []
+ assert list(msg4.active_template_ids()) == []
+
+
+def test_options_template_and_validation():
+ otmpl = template.for_specs(260, "observationDomainId", "octetDeltaCount", scopecount=1)
+ assert otmpl.native_setid() == template.OPTIONS_SET_ID
+
+ msg = message.MessageBuffer()
+ msg.begin_export(7)
+ msg.add_template(otmpl)
+ msg.export_ensure_set(260)
+ msg.export_namedict({"observationDomainId": 7, "octetDeltaCount": 1234})
+ raw = msg.to_bytes()
+
+ msg2 = message.MessageBuffer()
+ msg2.from_bytes(raw)
+ recs = list(msg2.namedict_iterator())
+ assert recs == [{"observationDomainId": 7, "octetDeltaCount": 1234}]
+ assert msg2.template_for_id(260).scopecount == 1
+
+ # Invalid options template: scopecount == 0 with count > 0
+ bad_oset = struct.pack("!HH HHH HH", 3, 14, 261, 1, 0, 1, 8)
+ bad_msg = struct.pack("!HHLLL", 10, 16 + len(bad_oset), 1700000000, 0, 7) + bad_oset
+ msg3 = message.MessageBuffer()
+ msg3.from_bytes(bad_msg)
+ with pytest.raises(IpfixDecodeError):
+ list(msg3.namedict_iterator())
+
+
+def test_template_identical_to_checks_length():
+ t1 = template.for_specs(256, "octetDeltaCount")
+ t2 = template.for_specs(257, "octetDeltaCount[4]")
+ t3 = template.for_specs(258, "octetDeltaCount")
+ assert not t1.identical_to(t2)
+ assert t1.identical_to(t3)
+
+
+def test_begin_export_odid_zero_and_sequence_wrap():
+ msg = message.MessageBuffer()
+ msg.begin_export(100)
+ assert msg.odid == 100
+ msg.sequences[(0, 0)] = 0xFFFFFFFF
+ msg.begin_export(0)
+ assert msg.odid == 0
+ assert msg.sequence == 0xFFFFFFFF
+ msg._increment_sequence()
+ assert msg.sequences[(0, 0)] == 0
+
+
+def test_hooks_and_unknown_ignored_sets():
+ t1 = template.for_specs(256, "sourceIPv4Address", "packetDeltaCount")
+ msg = message.MessageBuffer()
+ msg.begin_export(1)
+ msg.add_template(t1)
+ msg.export_ensure_set(256)
+ msg.export_namedict(
+ {"sourceIPv4Address": ip_address("10.0.0.1"), "packetDeltaCount": 1}
+ )
+ raw = msg.to_bytes()
+
+ headers = []
+ ignored = []
+ msg2 = message.MessageBuffer()
+ msg2.message_header_hook = lambda m: headers.append(m.odid)
+ msg2.ignored_data_set_hook = lambda m, t, b: ignored.append((t.tid, len(b)))
+ msg2.from_bytes(raw)
+ # Request an IE not in template 256 -> ignored_data_set_hook called
+ assert list(msg2.tuple_iterator(ie.spec_list(["destinationIPv4Address"]))) == []
+ assert headers == [1]
+ assert len(ignored) == 1 and ignored[0][0] == 256
+
+ # Unknown data set (no template 300)
+ dset = struct.pack("!HH4s", 300, 8, b"\x01\x02\x03\x04")
+ raw_unk = struct.pack("!HHLLL", 10, 16 + len(dset), 1700000000, 0, 1) + dset
+ unknown = []
+ msg3 = message.MessageBuffer()
+ msg3.unknown_data_set_hook = lambda m, b: unknown.append(len(b))
+ msg3.from_bytes(raw_unk)
+ assert list(msg3.namedict_iterator()) == []
+ assert unknown == [8]
+
+
+def test_malformed_packet_security_dos_cases():
+ # 1. setlen == 0 (was infinite loop DoS!)
+ raw = struct.pack("!HHLLL HH", 10, 20, 0, 0, 0, 256, 0)
+ with pytest.raises(IpfixDecodeError):
+ message.MessageBuffer().from_bytes(raw)
+
+ # 2. setlen == 3 (< 4)
+ raw = struct.pack("!HHLLL HH", 10, 20, 0, 0, 0, 256, 3)
+ with pytest.raises(IpfixDecodeError):
+ message.MessageBuffer().from_bytes(raw)
+
+ # 3. Truncated set header at end of message (2 trailing bytes)
+ tset = struct.pack("!HH", 2, 4)
+ raw = struct.pack("!HHLLL", 10, 22, 0, 0, 0) + tset + b"\x00\x00"
+ with pytest.raises(IpfixDecodeError):
+ message.MessageBuffer().from_bytes(raw)
+
+ # 4. Zero-length IE in template
+ tset = struct.pack("!HH HH HH", 2, 12, 256, 1, 1, 0)
+ raw = struct.pack("!HHLLL", 10, 16 + len(tset), 0, 0, 0) + tset
+ msg = message.MessageBuffer()
+ msg.from_bytes(raw)
+ with pytest.raises(IpfixDecodeError):
+ list(msg.namedict_iterator())
+
+ # 5. Truncated enterprise PEN in template
+ tset = struct.pack("!HH HH HH", 2, 12, 256, 1, 0x8001, 4)
+ raw = struct.pack("!HHLLL", 10, 16 + len(tset), 0, 0, 0) + tset
+ msg = message.MessageBuffer()
+ msg.from_bytes(raw)
+ with pytest.raises(IpfixDecodeError):
+ list(msg.namedict_iterator())
+
+ # 6. Varlen length extending past setend (previously leaked stale mbuf bytes!)
+ tset = struct.pack("!HH HH HH", 2, 12, 256, 1, 96, 65535) # applicationName varlen
+ dset = struct.pack("!HH B 2s", 256, 7, 200, b"hi") # claims 200 bytes, only 2 present
+ raw = struct.pack("!HHLLL", 10, 16 + len(tset) + len(dset), 0, 0, 0) + tset + dset
+ msg = message.MessageBuffer()
+ msg.from_bytes(raw)
+ with pytest.raises(IpfixDecodeError):
+ list(msg.namedict_iterator())
+
+ # 7. Template with minlength == 0 manually injected must not infinite-loop
+ msg = message.MessageBuffer()
+ empty_t = template.Template(256)
+ empty_t.finalize()
+ msg.templates[(0, 256)] = empty_t
+ msg.accepted_tids.add((0, 256))
+ dset = struct.pack("!HH4s", 256, 8, b"\x00\x00\x00\x00")
+ raw = struct.pack("!HHLLL", 10, 16 + len(dset), 0, 0, 0) + dset
+ msg.from_bytes(raw)
+ with pytest.raises(IpfixDecodeError):
+ list(msg.namedict_iterator())
+
+
+def test_message_read_errors_and_eom():
+ # Short header, short body, bad version, bad length, bad set length
+ stored = testutils._stored_test_message
+ for bad in (
+ stored[:12],
+ stored[:33],
+ b"\x01\x02" + stored[2:],
+ stored[:2] + b"\x00\x11" + stored[4:],
+ stored[:18] + b"\x00\x01" + stored[20:],
+ stored[:18] + b"\xff\xff" + stored[20:],
+ ):
+ with pytest.raises(IpfixDecodeError):
+ message.MessageBuffer().from_bytes(bad)
+
+ # EOM on record overflow
+ with pytest.raises(message.EndOfMessage):
+ testutils.mktest_message(rec_count=65536)
+
+ # MTU too small
+ msg = message.MessageBuffer()
+ msg.mtu = 10
+ with pytest.raises(IpfixEncodeError):
+ msg.begin_export(1)
+
+ # Start set without template
+ msg = message.MessageBuffer()
+ msg.begin_export(1)
+ with pytest.raises(IpfixEncodeError):
+ msg.export_new_set(999)
+
+ # withdrawal_length raises (not returns) on bad set id
+ with pytest.raises(IpfixEncodeError):
+ template.withdrawal_length(99)
+ with pytest.raises(IpfixEncodeError):
+ template.encode_withdrawal_to(bytearray(16), 0, 99, 256)
+
+
+def test_unsigned256_in_message_roundtrip():
+ tmpl = template.for_specs(256, "tcpOptionsFull", "udpSafeOptions")
+ msg = message.MessageBuffer()
+ msg.begin_export(1)
+ msg.add_template(tmpl)
+ msg.export_ensure_set(256)
+ rec = {
+ "tcpOptionsFull": (1 << 255) | (1 << 128) | 1,
+ "udpSafeOptions": (1 << 200) | 0x42,
+ }
+ msg.export_namedict(rec)
+ raw = msg.to_bytes()
+
+ msg2 = message.MessageBuffer()
+ msg2.from_bytes(raw)
+ assert list(msg2.namedict_iterator()) == [rec]
+
+
+def test_accepted_tids_cache_switches_and_multidomain():
+ t1 = template.for_specs(256, "sourceIPv4Address", "packetDeltaCount")
+ t2 = template.for_specs(256, "sourceIPv4Address")
+
+ builder = message.MessageBuffer()
+ builder.begin_export(1)
+ builder.add_template(t1)
+ builder.export_ensure_set(256)
+ builder.export_namedict(
+ {"sourceIPv4Address": ip_address("10.0.0.1"), "packetDeltaCount": 1}
+ )
+ msg1_raw = builder.to_bytes()
+
+ builder.begin_export(1)
+ builder.export_ensure_set(256)
+ builder.export_namedict(
+ {"sourceIPv4Address": ip_address("10.0.0.2"), "packetDeltaCount": 2}
+ )
+ msg1_data_raw = builder.to_bytes()
+
+ # Switching from rejecting tuple_iterator back to namedict_iterator
+ dec = message.MessageBuffer()
+ dec.from_bytes(msg1_raw)
+ assert list(dec.tuple_iterator(ie.spec_list(["destinationIPv4Address"]))) == []
+ dec.from_bytes(msg1_data_raw)
+ assert list(dec.namedict_iterator()) == [
+ {"sourceIPv4Address": ip_address("10.0.0.2"), "packetDeltaCount": 2}
+ ]
+
+ # Multi-domain tuple_iterator with same ielist across domains
+ builder.begin_export(2)
+ builder.add_template(t2)
+ msg2_tmpl_raw = builder.to_bytes()
+ builder.begin_export(2)
+ builder.export_ensure_set(256)
+ builder.export_namedict({"sourceIPv4Address": ip_address("10.0.0.9")})
+ msg2_data_raw = builder.to_bytes()
+
+ dec2 = message.MessageBuffer()
+ dec2.from_bytes(msg1_raw)
+ assert len(list(dec2.namedict_iterator())) == 1
+ dec2.from_bytes(msg2_tmpl_raw)
+ assert list(dec2.namedict_iterator()) == []
+
+ iel = ie.spec_list(["packetDeltaCount"])
+ dec2.from_bytes(msg1_data_raw)
+ assert list(dec2.tuple_iterator(iel)) == [(2,)]
+ dec2.from_bytes(msg2_data_raw)
+ assert list(dec2.tuple_iterator(iel)) == []
+ assert list(dec2.namedict_iterator()) == [{"sourceIPv4Address": ip_address("10.0.0.9")}]
+
+ # Pre-seeded template via add_template() works with namedict_iterator
+ pre = message.MessageBuffer()
+ pre.odid = 1
+ pre.add_template(t1, export=False)
+ pre.from_bytes(msg1_data_raw)
+ assert list(pre.namedict_iterator()) == [
+ {"sourceIPv4Address": ip_address("10.0.0.2"), "packetDeltaCount": 2}
+ ]
+
+
+def test_no_empty_sets_and_delete_template_atomicity():
+ t1 = template.for_specs(256, "sourceIPv4Address", "packetDeltaCount")
+ t2 = template.for_specs(257, "sourceIPv4Address", "octetDeltaCount")
+
+ # export_template hitting EndOfMessage emits no trailing empty set
+ msg = message.MessageBuffer()
+ msg.mtu = 48
+ msg.begin_export(1)
+ msg.add_template(t1) # length = 32
+ msg.export_ensure_set(256) # length = 36
+ msg.export_namedict(
+ {"sourceIPv4Address": ip_address("10.0.0.1"), "packetDeltaCount": 1}
+ ) # length = 48
+ with pytest.raises(message.EndOfMessage):
+ msg.add_template(t2)
+ raw = msg.to_bytes()
+ chk = message.MessageBuffer()
+ chk.from_bytes(raw)
+ assert [(sid, slen) for _, sid, slen in chk.setlist] == [(2, 16), (256, 16)]
+
+ # delete_template(export=True) hitting EndOfMessage preserves template & emits no empty set
+ msg2 = message.MessageBuffer()
+ msg2.mtu = 52
+ msg2.begin_export(1)
+ msg2.add_template(t1) # 32
+ msg2.export_ensure_set(256) # 36
+ msg2.export_namedict(
+ {"sourceIPv4Address": ip_address("10.0.0.1"), "packetDeltaCount": 1}
+ ) # 48
+ with pytest.raises(message.EndOfMessage):
+ msg2.delete_template(256, export=True)
+ assert (1, 256) in msg2.templates
+ raw2 = msg2.to_bytes()
+ chk2 = message.MessageBuffer()
+ chk2.from_bytes(raw2)
+ assert [(sid, slen) for _, sid, slen in chk2.setlist] == [(2, 16), (256, 16)]
+
+ # Flush and retry delete_template(256, export=True)
+ msg2.begin_export(1)
+ msg2.delete_template(256, export=True)
+ assert (1, 256) not in msg2.templates
+
+ # delete_template(export=False) closes active set and clears curtmpl
+ msg3 = message.MessageBuffer()
+ msg3.begin_export(1)
+ msg3.add_template(t1)
+ msg3.export_ensure_set(256)
+ msg3.delete_template(256, export=False)
+ assert msg3.cursetid is None
+ assert msg3.curtmpl is None
+
+
+def test_export_record_errors_and_validation():
+ # No active data set
+ msg = message.MessageBuffer()
+ msg.begin_export(1)
+ with pytest.raises(IpfixEncodeError):
+ msg.export_namedict({"packetDeltaCount": 1})
+
+ # Out-of-range integer raises struct.error (NOT EndOfMessage)
+ t_fixed = template.for_specs(256, "sourceTransportPort", "packetDeltaCount")
+ msg.add_template(t_fixed)
+ msg.export_ensure_set(256)
+ saved_len = msg.length
+ with pytest.raises(struct.error):
+ msg.export_namedict({"sourceTransportPort": 70000, "packetDeltaCount": 1})
+ assert msg.length == saved_len
+
+ # Wrong-length tuple on fixed and varlen templates raises ValueError (NOT EndOfMessage)
+ with pytest.raises(ValueError):
+ msg.export_tuple((80,))
+ with pytest.raises(ValueError):
+ msg.export_tuple((80, 1, 2))
+ t_var = template.for_specs(257, "applicationName", "packetDeltaCount")
+ msg.add_template(t_var)
+ msg.export_ensure_set(257)
+ with pytest.raises(ValueError):
+ msg.export_tuple(("app",))
+
+ # Cross-set withdrawal TID must raise IpfixDecodeError
+ for setid, bad_tid in ((2, 3), (3, 2)):
+ body = (
+ struct.pack("!HH", bad_tid, 0)
+ if setid == 2
+ else struct.pack("!HHH", bad_tid, 0, 0)
+ )
+ wset = struct.pack("!HH", setid, 4 + len(body)) + body
+ wraw = struct.pack("!HHLLL", 10, 16 + len(wset), 0, 0, 1) + wset
+ dec = message.MessageBuffer()
+ dec.from_bytes(wraw)
+ with pytest.raises(IpfixDecodeError):
+ list(dec.namedict_iterator())
+
+ # Invalid scopecount on template creation
+ iel = ie.spec_list(["observationDomainId", "octetDeltaCount"])
+ with pytest.raises(ValueError):
+ template.from_ielist(260, iel, scopecount=-1)
+ with pytest.raises(ValueError):
+ template.from_ielist(260, iel, scopecount=3)
+
+ # Small buf_sz caps mtu, and Template.decode_from clamps setend to len(buf)
+ small_msg = message.MessageBuffer(buf_sz=128)
+ assert small_msg.mtu == 128
+ with pytest.raises(IpfixDecodeError):
+ t_fixed.decode_from(bytearray(4), 0, setend=9999)
diff --git a/tests/test_types.py b/tests/test_types.py
new file mode 100644
index 0000000..4f856b8
--- /dev/null
+++ b/tests/test_types.py
@@ -0,0 +1,282 @@
+import ipaddress
+import struct
+from datetime import UTC, datetime, timedelta, timezone
+
+import pytest
+
+import ipfix.types as types
+
+
+def test_for_name_unknown():
+ with pytest.raises(types.IpfixTypeError):
+ types.for_name("bogus")
+
+
+def test_exception_subclassable():
+ class SubTypeError(types.IpfixTypeError):
+ pass
+
+ err = SubTypeError("boom")
+ assert isinstance(err, types.IpfixTypeError)
+ assert str(err) == "boom"
+
+
+def test_all_builtin_types_roundtrip():
+ buf = memoryview(bytearray(64))
+ dt = datetime(2024, 5, 6, 7, 8, 9, 123000)
+
+ cases = [
+ ("octetArray", b"\xde\xad\xbe\xef", b"\xde\xad\xbe\xef"),
+ ("unsigned8", 255, 255),
+ ("unsigned16", 65535, 65535),
+ ("unsigned32", 2**32 - 1, 2**32 - 1),
+ ("unsigned64", 2**64 - 1, 2**64 - 1),
+ ("unsigned256", (1 << 255) | 0xCAFEBABE, (1 << 255) | 0xCAFEBABE),
+ ("signed8", -128, -128),
+ ("signed16", -32768, -32768),
+ ("signed32", -(2**31), -(2**31)),
+ ("signed64", -(2**63), -(2**63)),
+ ("float32", 3.5, 3.5),
+ ("float64", 3.141592653589793, 3.141592653589793),
+ ("boolean", True, True),
+ ("boolean", False, False),
+ ("macAddress", b"\x00\x11\x22\x33\x44\x55", b"\x00\x11\x22\x33\x44\x55"),
+ ("string", "hello Grüezi", "hello Grüezi"),
+ ("dateTimeSeconds", dt, datetime(2024, 5, 6, 7, 8, 9)),
+ ("dateTimeMilliseconds", dt, dt),
+ ("dateTimeMicroseconds", dt, dt),
+ ("dateTimeNanoseconds", dt, dt),
+ (
+ "ipv4Address",
+ ipaddress.ip_address("192.0.2.1"),
+ ipaddress.ip_address("192.0.2.1"),
+ ),
+ (
+ "ipv6Address",
+ ipaddress.ip_address("2001:db8::1"),
+ ipaddress.ip_address("2001:db8::1"),
+ ),
+ ]
+
+ for tname, val, expected in cases:
+ t = types.for_name(tname)
+ end = t.encode_single_value_to(val, buf, 0)
+ got = t.decode_single_value_from(buf, 0, end)
+ assert got == expected, f"Mismatch for {tname}: {got!r} != {expected!r}"
+
+
+def test_rle_power_of_two_and_arbitrary_widths():
+ buf = memoryview(bytearray(64))
+
+ # Power-of-two RLE
+ u64_2 = types.for_name("unsigned64").for_length(2)
+ assert u64_2.length == 2
+ end = u64_2.encode_single_value_to(0x1234, buf, 0)
+ assert end == 2
+ assert u64_2.decode_single_value_from(buf, 0, 2) == 0x1234
+ # Regression: valstr and valparse preserved on RLE types
+ assert u64_2.valstr(42) == "42"
+ assert u64_2.valparse("42") == 42
+
+ # Non-power-of-two RLE (RFC 7011 §6.2)
+ u32_3 = types.for_name("unsigned32").for_length(3)
+ end = u32_3.encode_single_value_to(0xABCDEF, buf, 0)
+ assert end == 3
+ assert u32_3.decode_single_value_from(buf, 0, 3) == 0xABCDEF
+
+ s32_3 = types.for_name("signed32").for_length(3)
+ end = s32_3.encode_single_value_to(-123456, buf, 0)
+ assert end == 3
+ assert s32_3.decode_single_value_from(buf, 0, 3) == -123456
+
+ u256_16 = types.for_name("unsigned256").for_length(16)
+ val = (1 << 120) + 7
+ end = u256_16.encode_single_value_to(val, buf, 0)
+ assert end == 16
+ assert u256_16.decode_single_value_from(buf, 0, 16) == val
+
+ f64_4 = types.for_name("float64").for_length(4)
+ end = f64_4.encode_single_value_to(1.5, buf, 0)
+ assert end == 4
+ assert f64_4.decode_single_value_from(buf, 0, 4) == 1.5
+
+ # Invalid RLE lengths
+ with pytest.raises(types.IpfixTypeError):
+ types.for_name("unsigned16").for_length(4)
+ with pytest.raises(types.IpfixTypeError):
+ types.for_name("ipv4Address").for_length(2)
+ with pytest.raises(types.IpfixTypeError):
+ types.for_name("unsigned32").for_length(types.VARLEN)
+ with pytest.raises(types.IpfixTypeError):
+ types.for_name("octetArray").for_length(-1)
+ for dt_name, bad_len in (
+ ("dateTimeSeconds", 2),
+ ("dateTimeMilliseconds", 4),
+ ("dateTimeMicroseconds", 4),
+ ("dateTimeNanoseconds", 4),
+ ):
+ with pytest.raises(types.IpfixTypeError):
+ types.for_name(dt_name).for_length(bad_len)
+
+ # Resizing reduced types back to native width & unsigned256 fast struct RLE
+ assert u64_2.for_length(8) is types.for_name("unsigned64")
+ assert u256_16.for_length(32) is types.for_name("unsigned256")
+ assert f64_4.for_length(8) is types.for_name("float64")
+ u256_4 = types.for_name("unsigned256").for_length(4)
+ assert u256_4.stel == "L"
+ assert u256_4.length == 4
+
+ # _make_int_encoder rejects non-integers and out-of-range ints
+ enc3 = types._make_int_encoder(3, signed=False)
+ with pytest.raises(TypeError):
+ enc3(1.5)
+ with pytest.raises(TypeError):
+ enc3("42")
+ with pytest.raises(OverflowError):
+ enc3(1 << 24)
+ with pytest.raises(OverflowError):
+ enc3(-1)
+
+
+def test_fixed_length_string_and_octet_array():
+ buf = memoryview(bytearray(32))
+
+ # Fixed-length string: trailing NUL padding stripped on decode (Issue #21)
+ s14 = types.for_name("string").for_length(14)
+ end = s14.encode_single_value_to("ietf-a-v6only", buf, 0)
+ assert end == 14
+ assert bytes(buf[:14]) == b"ietf-a-v6only\x00"
+ assert s14.decode_single_value_from(buf, 0, 14) == "ietf-a-v6only"
+ assert s14.valstr("abc") == "abc"
+ assert s14.valparse("abc") == "abc"
+
+ # Re-sizing fixed-length string and back to VARLEN
+ s16 = s14.for_length(16)
+ assert s16.length == 16
+ assert s14.for_length(types.VARLEN) is types.for_name("string")
+
+ # Oversized UTF-8 string raises ValueError instead of silent mid-codepoint truncation
+ s4 = types.for_name("string").for_length(4)
+ with pytest.raises(ValueError):
+ s4.encode_single_value_to("Grüezi", buf, 0)
+
+ # Fixed-length octetArray + re-sizing and back to VARLEN
+ oa4 = types.for_name("octetArray").for_length(4)
+ assert oa4.length == 4
+ oa8 = oa4.for_length(8)
+ assert oa8.length == 8
+ assert oa8.valstr(b"\xab") == b"ab"
+ assert oa4.for_length(types.VARLEN) is types.for_name("octetArray")
+
+
+def test_boolean_validation_and_str():
+ buf = memoryview(bytearray(4))
+ btype = types.for_name("boolean")
+ buf[0] = 3
+ with pytest.raises(ValueError):
+ btype.decode_single_value_from(buf, 0, 1)
+
+ assert btype.valstr(True) == "true"
+ assert btype.valstr(False) == "false"
+ assert btype.valparse("true") is True
+ assert btype.valparse("false") is False
+
+
+def test_use_integer_ipv4_and_restore():
+ buf = memoryview(bytearray(4))
+ try:
+ types.use_integer_ipv4()
+ t = types.for_name("ipv4Address")
+ end = t.encode_single_value_to(0xC0000201, buf, 0)
+ assert end == 4
+ assert t.decode_single_value_from(buf, 0, 4) == 0xC0000201
+ with pytest.raises(types.IpfixTypeError):
+ t.for_length(2)
+ finally:
+ types.use_ipaddress_ipv4()
+
+ t = types.for_name("ipv4Address")
+ assert t.decode_single_value_from(buf, 0, 4) == ipaddress.IPv4Address("192.0.2.1")
+
+
+def test_datetime_aware_and_naive_encode_and_parse():
+ buf = memoryview(bytearray(8))
+ naive = datetime(2024, 6, 15, 12, 30, 45, 500000)
+ aware_utc = datetime(2024, 6, 15, 12, 30, 45, 500000, tzinfo=UTC)
+ aware_plus2 = datetime(
+ 2024, 6, 15, 14, 30, 45, 500000, tzinfo=timezone(timedelta(hours=2))
+ )
+
+ for tname in ("dateTimeSeconds", "dateTimeMilliseconds", "dateTimeMicroseconds"):
+ t = types.for_name(tname)
+ t.encode_single_value_to(naive, buf, 0)
+ b_naive = bytes(buf[: t.length])
+ t.encode_single_value_to(aware_utc, buf, 0)
+ b_utc = bytes(buf[: t.length])
+ t.encode_single_value_to(aware_plus2, buf, 0)
+ b_plus2 = bytes(buf[: t.length])
+ assert b_naive == b_utc == b_plus2
+
+ decoded = t.decode_single_value_from(buf, 0, t.length)
+ assert decoded.tzinfo is None
+
+ # ISO 8601 parse/unparse with Z and offset
+ assert types.for_name("dateTimeSeconds").valparse("2024-06-15T12:30:45Z") == datetime(
+ 2024, 6, 15, 12, 30, 45
+ )
+ assert types.for_name("dateTimeMilliseconds").valparse(
+ "2024-06-15 12:30:45.123+00:00"
+ ) == datetime(2024, 6, 15, 12, 30, 45, 123000)
+ assert types.for_name("dateTimeMicroseconds").valparse(
+ "2024-06-15 12:30:45.123456Z"
+ ) == datetime(2024, 6, 15, 12, 30, 45, 123456)
+ assert types.for_name("dateTimeSeconds").valstr(naive) == "2024-06-15 12:30:45"
+ assert (
+ types.for_name("dateTimeMilliseconds").valstr(naive)
+ == "2024-06-15 12:30:45.500"
+ )
+ assert (
+ types.for_name("dateTimeMicroseconds").valstr(naive)
+ == "2024-06-15 12:30:45.500000"
+ )
+
+ # Aware non-UTC datetime round-trips consistently via valstr -> valparse
+ for tname in ("dateTimeSeconds", "dateTimeMilliseconds", "dateTimeMicroseconds"):
+ t = types.for_name(tname)
+ t.encode_single_value_to(aware_plus2, buf, 0)
+ decoded = t.decode_single_value_from(buf, 0, t.length)
+ assert t.valparse(t.valstr(aware_plus2)) == decoded
+
+
+def test_varlen_encode_decode_and_bounds():
+ buf = memoryview(bytearray(16))
+
+ off = types.encode_varlen(buf, 0, 10)
+ assert off == 1
+ assert types.decode_varlen(buf, 0) == (10, 1)
+
+ off = types.encode_varlen(buf, 0, 255)
+ assert off == 3
+ assert types.decode_varlen(buf, 0) == (255, 3)
+
+ off = types.encode_varlen(buf, 0, 1024)
+ assert off == 3
+ assert types.decode_varlen(buf, 0) == (1024, 3)
+
+ # Truncated varlen prefix
+ with pytest.raises(struct.error):
+ types.decode_varlen(buf, 0, end=0)
+ with pytest.raises(struct.error):
+ types.decode_varlen(buf, 0, end=2) # 255 prefix needs 3 bytes
+
+
+def test_type_ordering_and_length_mismatch():
+ u8 = types.for_name("unsigned8")
+ u16 = types.for_name("unsigned16")
+ assert u8 < u16
+ assert str(u8) == ""
+ assert repr(u8) == "ipfix.types.for_name('unsigned8')"
+
+ buf = memoryview(bytearray(4))
+ with pytest.raises(types.IpfixTypeError):
+ u16.decode_single_value_from(buf, 0, 4)
diff --git a/tests/test_v9pdu.py b/tests/test_v9pdu.py
new file mode 100644
index 0000000..1b83c83
--- /dev/null
+++ b/tests/test_v9pdu.py
@@ -0,0 +1,192 @@
+import io
+import struct
+from datetime import datetime
+from ipaddress import ip_address
+
+import pytest
+
+import ipfix.ie as ie
+import ipfix.v9pdu as v9pdu
+from ipfix.template import IpfixDecodeError
+
+
+@pytest.fixture(autouse=True)
+def setup_iana():
+ ie.clear_infomodel()
+ ie.use_iana_default()
+ yield
+ ie.clear_infomodel()
+
+
+def _build_v9_pdu(
+ sets,
+ *,
+ reccount=1,
+ sysuptime_ms=60000,
+ export_epoch=1700000000,
+ sequence=1,
+ odid=42,
+):
+ hdr = struct.pack(
+ "!HHLLLL",
+ v9pdu.NETFLOW9_VERSION,
+ reccount,
+ sysuptime_ms,
+ export_epoch,
+ sequence,
+ odid,
+ )
+ return hdr + b"".join(sets)
+
+
+def _v9_template_set(tid, fields, pad=0):
+ body = struct.pack("!HH", tid, len(fields))
+ for num, length in fields:
+ body += struct.pack("!HH", num, length)
+ body += b"\x00" * pad
+ return struct.pack("!HH", 0, 4 + len(body)) + body
+
+
+def _v9_data_set(tid, payload):
+ return struct.pack("!HH", tid, 4 + len(payload)) + payload
+
+
+def test_single_pdu_and_stream_pdu_roundtrip():
+ # Template 256: sourceIPv4Address (8, 4), packetDeltaCount (2, 4),
+ # flowStartSysUpTime (22, 4), flowEndSysUpTime (21, 4)
+ tset = _v9_template_set(256, [(8, 4), (2, 4), (22, 4), (21, 4)], pad=2)
+ rec1 = struct.pack("!4sLLL", ip_address("198.51.100.1").packed, 10, 50000, 55000)
+ rec2 = struct.pack("!4sLLL", ip_address("198.51.100.2").packed, 20, 51000, 59000)
+ dset = _v9_data_set(256, rec1 + rec2)
+ pdu = _build_v9_pdu([tset, dset], reccount=2)
+
+ # SinglePduBuffer
+ sp = v9pdu.SinglePduBuffer(pdu)
+ assert "PduBuffer" in repr(sp)
+ recs = list(sp.namedict_iterator())
+ assert len(recs) == 2
+ assert recs[0]["sourceIPv4Address"] == ip_address("198.51.100.1")
+ assert recs[0]["packetDeltaCount"] == 10
+ assert list(sp.active_template_ids()) == [256]
+
+ # Save / restore state -> both namedict_iterator and tuple_iterator work
+ state = sp.save_state()
+ sp2 = v9pdu.SinglePduBuffer(_build_v9_pdu([dset], reccount=2))
+ sp2.restore_state(state)
+ restored_recs = list(sp2.namedict_iterator())
+ assert len(restored_recs) == 2
+ assert restored_recs[0]["packetDeltaCount"] == 10
+
+ sp3 = v9pdu.SinglePduBuffer(_build_v9_pdu([dset], reccount=2))
+ sp3.restore_state(state)
+ ielist = ie.spec_list(["packetDeltaCount", "sourceIPv4Address"])
+ tups = list(sp3.tuple_iterator(ielist))
+ assert tups == [
+ (10, ip_address("198.51.100.1")),
+ (20, ip_address("198.51.100.2")),
+ ]
+
+ # Sequence count matches decoded data records (no double-counting)
+ assert sp.sequences[42] == 2
+
+ # StreamPduBuffer across two concatenated PDUs
+ pdu2 = _build_v9_pdu([dset], reccount=2, sequence=2)
+ stream = io.BytesIO(pdu + pdu2)
+ sb = v9pdu.from_stream(stream)
+ stream_recs = list(sb.namedict_iterator())
+ assert len(stream_recs) == 4
+ assert sb.sequences[42] == 4
+
+
+def test_time_adapter_namedict_and_tuple():
+ # export_epoch=1700000000, sysuptime_ms=60000 -> basetime=1699999940
+ # flowStartSysUpTime=50000 -> 1699999990.0 (2023-11-14 22:13:10)
+ # flowEndSysUpTime=55500 -> 1699999995.5 (2023-11-14 22:13:15.500000)
+ tset = _v9_template_set(256, [(8, 4), (22, 4), (21, 4)])
+ rec = struct.pack("!4sLL", ip_address("10.0.0.1").packed, 50000, 55500)
+ pdu = _build_v9_pdu([tset, _v9_data_set(256, rec)])
+
+ ta = v9pdu.TimeAdapter(v9pdu.SinglePduBuffer(pdu))
+ recs = list(ta.namedict_iterator())
+ assert len(recs) == 1
+ assert recs[0]["flowStartMilliseconds"] == datetime(2023, 11, 14, 22, 13, 10)
+ assert recs[0]["flowEndMilliseconds"] == datetime(2023, 11, 14, 22, 13, 15, 500000)
+
+ # Tuple iterator with sysuptime fields
+ ta2 = v9pdu.TimeAdapter(v9pdu.SinglePduBuffer(pdu))
+ ielist = ie.spec_list(
+ ["sourceIPv4Address", "flowStartSysUpTime", "flowEndSysUpTime"]
+ )
+ tups = list(ta2.tuple_iterator(ielist))
+ assert len(tups) == 1
+ assert tups[0][3] == datetime(2023, 11, 14, 22, 13, 10)
+ assert tups[0][4] == datetime(2023, 11, 14, 22, 13, 15, 500000)
+
+ # Tuple iterator without sysuptime fields passes through unchanged
+ ta3 = v9pdu.TimeAdapter(v9pdu.SinglePduBuffer(pdu))
+ tups3 = list(ta3.tuple_iterator(ie.spec_list(["sourceIPv4Address"])))
+ assert tups3 == [(ip_address("10.0.0.1"),)]
+
+
+def test_v9_malformed_inputs():
+ # Short PDU
+ with pytest.raises(IpfixDecodeError):
+ v9pdu.SinglePduBuffer(b"\x00\x09\x00\x00")
+
+ # Wrong version
+ with pytest.raises(IpfixDecodeError):
+ v9pdu.SinglePduBuffer(struct.pack("!HHLLLL", 10, 0, 0, 0, 0, 0))
+
+ # Zero-length set (was infinite loop DoS!)
+ bad_zero = _build_v9_pdu([struct.pack("!HH", 256, 0)])
+ with pytest.raises(IpfixDecodeError):
+ list(v9pdu.SinglePduBuffer(bad_zero).namedict_iterator())
+ with pytest.raises(IpfixDecodeError):
+ list(v9pdu.from_stream(io.BytesIO(bad_zero)).namedict_iterator())
+
+ # Set extending past PDU
+ bad_long = _build_v9_pdu([struct.pack("!HH", 256, 100)])
+ with pytest.raises(IpfixDecodeError):
+ list(v9pdu.SinglePduBuffer(bad_long).namedict_iterator())
+
+ # Enterprise bit set in v9 template
+ bad_pen = _build_v9_pdu([_v9_template_set(256, [(0x8001, 4)])])
+ with pytest.raises(IpfixDecodeError):
+ list(v9pdu.SinglePduBuffer(bad_pen).namedict_iterator())
+
+ # 0-field v9 template rejected
+ bad_empty = _build_v9_pdu([_v9_template_set(256, [])])
+ with pytest.raises(IpfixDecodeError):
+ list(v9pdu.SinglePduBuffer(bad_empty).namedict_iterator())
+
+ # StreamPduBuffer rejects non-v9 (e.g. IPFIX v10) stream
+ ipfix_header_stream = io.BytesIO(struct.pack("!HHLLL", 10, 20, 0, 0, 1) + b"\x00\x02\x00\x04")
+ with pytest.raises(IpfixDecodeError):
+ list(v9pdu.from_stream(ipfix_header_stream).namedict_iterator())
+
+
+def test_v9_options_template_rfc3954():
+ # RFC 3954 §6.1: FlowSet ID=1, Option Scope Length=4 (1 scope field: System=1, len=4),
+ # Option Length=4 (1 option field: octetDeltaCount=1, len=8)
+ oset_body = struct.pack("!HHH HH HH", 256, 4, 4, 1, 4, 1, 8)
+ oset = struct.pack("!HH", 1, 4 + len(oset_body) + 2) + oset_body + b"\x00\x00"
+ dset = _v9_data_set(256, struct.pack("!4sQ", b"\x00\x00\x00\x07", 987654321))
+ pdu = _build_v9_pdu([oset, dset], reccount=1)
+
+ sp = v9pdu.SinglePduBuffer(pdu)
+ recs = list(sp.namedict_iterator())
+ assert recs == [{"v9ScopeSystem": b"\x00\x00\x00\x07", "octetDeltaCount": 987654321}]
+ assert sp.templates[(0, 42, 256)].scopecount == 1
+
+ # Scope field ID 1 (System) must NOT collide with IANA IE 1 (octetDeltaCount)
+ sp2 = v9pdu.SinglePduBuffer(pdu)
+ tups = list(sp2.tuple_iterator(ie.spec_list(["octetDeltaCount"])))
+ assert tups == [(987654321,)]
+
+ # Invalid v9 options templates (non-multiple-of-4 lengths, zero scope length)
+ for scope_len, opt_len in ((3, 4), (4, 2), (0, 4)):
+ bad_body = struct.pack("!HHH", 256, scope_len, opt_len) + b"\x00\x01\x00\x04"
+ bad_oset = struct.pack("!HH", 1, 4 + len(bad_body)) + bad_body
+ bad_pdu = _build_v9_pdu([bad_oset])
+ with pytest.raises(IpfixDecodeError):
+ list(v9pdu.SinglePduBuffer(bad_pdu).namedict_iterator())
diff --git a/vis-package/setup.py b/vis-package/setup.py
deleted file mode 100755
index 4c98f00..0000000
--- a/vis-package/setup.py
+++ /dev/null
@@ -1,21 +0,0 @@
-#!/usr/bin/env python3
-
-from setuptools import setup
-
-setup(name='visipfix',
- version='0.1.0',
- description='IPFIX message visualizer for Python 3.3',
- author='Brian Trammell',
- author_email='brian@trammell.ch',
- url='http://github.com/britram/python-ipfix',
- packages=['visipfix'],
- requires='ipfix',
- classifiers=["Development Status :: 3 - Alpha",
- "Intended Audience :: Developers",
- "License :: OSI Approved :: "
- "GNU Lesser General Public License v3 or later (LGPLv3+)",
- "Operating System :: OS Independent",
- "Programming Language :: Python :: 3.3",
- "Topic :: System :: Networking"]
- )
-
diff --git a/vis-package/visipfix/__init__.py b/vis-package/visipfix/__init__.py
deleted file mode 100644
index 72501e2..0000000
--- a/vis-package/visipfix/__init__.py
+++ /dev/null
@@ -1,466 +0,0 @@
-#
-# python-ipfix (c) 2013 Brian Trammell.
-#
-# Many thanks to the mPlane consortium (http://www.ict-mplane.eu) for
-# its material support of this effort.
-#
-# This program is free software: you can redistribute it and/or modify it under
-# the terms of the GNU Lesser General Public License as published by the Free
-# Software Foundation, either version 3 of the License, or (at your option) any
-# later version.
-#
-# This program is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
-# details.
-#
-# You should have received a copy of the GNU General Public License along with
-# this program. If not, see .
-#
-
-# This file is not part of the main ipfix distribution;
-# it exists for interactive visualization of IPFIX messages.
-# It's basically a sick hack pulled together over a couple of hours.
-# It's not documented, and that's intentional.
-# It's entirely possible that I'll come back and clean this up one day.
-
-from ipfix import message, template, types, compat
-from __future__ import division
-from .compat import izip
-
-from datetime import datetime
-
-import math
-
-import svgwrite
-import string
-import random
-
-def scale_tuple(t, scale):
- return tuple([x * s for x,s in izip(t, scale)])
-
-def scale_tupletuple(tt, scale):
- return tuple([scale_tuple(x, scale) for x in tt])
-
-def render_dt8601(dt):
- return dt.strftime("%Y-%m-%d %H:%M:%S.%f %Z")
-
-def render_ienumber(ie):
- if ie.pen:
- num = ie.num + 0x8000
- else:
- num = ie.num
- return midtrunc(ie.name,6,4) + "(" + str(num) + ")"
-
-def random_id(length = 16):
- return ''.join(random.choice(string.ascii_lowercase + string.digits) for x in xrange(length))
-
-def midtrunc(s, front, back):
- if len(s) <= (front + back + 3):
- return s
- else:
- return s[:front] + "..." + s[-back:]
-
-class OctetField(object):
- def __init__(self, origin, size, value, label, fill):
- self.origin = origin;
- self.size = size;
- self.value = value
- self.label = label
- self.fill = fill
- self.textorigin = (origin[0] + size[0] / 2, origin[1] + size[1] / 2)
-
- def text(self):
- if (self.label):
- return str(self.label)+": "+str(self.value)
- else:
- return str(self.value)
-
-class RectField(OctetField):
- def __init__(self, col, row, width, height, value, label, fill):
- origin = (col, row)
- size = (width, height)
- super(self.__class__, self).__init__(origin, size, value, label, fill)
-
- def add_box_to_drawing(self, g, dwg, scale):
- g.add(dwg.rect(insert = scale_tuple(self.origin, scale),
- size = scale_tuple(self.size, scale),
- fill = self.fill))
-
- def add_text_to_drawing(self, g, dwg, scale):
- g.add(dwg.text(self.text(), scale_tuple(self.textorigin, scale),
- style="text-anchor: middle; "
- "dominant-baseline: hanging;"))
-
-class PolylineField(OctetField):
- def __init__(self, points, origin, size, value, label, fill):
- super(self.__class__, self).__init__(origin, size, value, label, fill)
- self.points = points
-
- def add_box_to_drawing(self, g, dwg, scale):
- g.add(dwg.polyline(scale_tupletuple(self.points, scale),
- fill = self.fill))
-
- def add_text_to_drawing(self, g, dwg, scale):
- g.add(dwg.text(self.text(), scale_tuple(self.textorigin, scale),
- style="text-anchor: middle; "
- "dominant-baseline: hanging;"))
-
-class LeftPolylineField(PolylineField):
- def __init__(self, row, width, height, botwidth,
- value, label, fill):
- points = ((0, row),
- (width, row),
- (width, row + height - 1),
- (botwidth, row + height - 1),
- (botwidth, row + height),
- (0, row + height),
- (0, row))
- origin = (0, row)
- size = (width, height-1)
- super(self.__class__, self).__init__(points, origin, size, value, label, fill)
-
-class RightPolylineField(PolylineField):
- def __init__(self, row, width, height, topwidth,
- value, label, fill):
- points = ((width - topwidth, row),
- (width, row),
- (width, row + height),
- (0, row + height),
- (0, row + 1),
- (width - topwidth, row + 1),
- (width - topwidth, row))
- origin = (0, row+1)
- size = (width, height-1)
- super(self.__class__, self).__init__(points, origin, size, value, label, fill)
-
-class MidPolylineField(PolylineField):
- def __init__(self, row, width, height, topwidth, botwidth,
- value, label, fill):
- points = ((width - topwidth, row),
- (width, row),
- (width, row + height - 1),
- (botwidth, row + height - 1),
- (botwidth, row + height),
- (0, row + height),
- (0, row + 1),
- (width - topwidth, row + 1),
- (width - topwidth, row))
- origin = (0, row+1)
- size = (width, height-2)
- super(self.__class__, self).__init__(points, origin, size, value, label, fill)
-
-class OctetFieldDrawing(object):
-
- def __init__(self, raster=8, offset=0):
- self.raster = raster
- self.col = 0
- self.row = 0
- self.fields = []
- self.rowaddrs = [offset]
- self.fill="white"
-
- def set_fill(self, fill):
- self.fill = fill
-
- def _add_field(self, length, field):
- self.fields.append(field)
-
- def _row_extend(self, count):
- for i in xrange(count):
- self.row += 1
- self.rowaddrs.append(self.rowaddrs[-1] + self.raster)
-
- def add(self, length, value,
- render_fn=str, label=None, rowbreak=False):
-
- # Increment row on rowbreak, or at end of row
- if (self.col >= self.raster) or (rowbreak and self.col):
- self.row += 1
- self.rowaddrs.append(self.rowaddrs[-1] + self.col)
- self.col = 0
-
- #print ("draw field length "+str(length)+
- # " at ("+str(self.col)+", "+str(self.row)+")")
-
- # Case 0: could fit on a single row
- if length <= self.raster:
- # Case 0a: fits on row, simple rect
- if (self.col + length) <= self.raster:
- #print(" fit, simple rect")
- self._add_field(length,
- RectField(self.col, self.row, length, 1,
- render_fn(value), label, self.fill))
- self.col += length
- # Case 0b: doesn't fit on row, force rowbreak
- else:
- #print(" short field doesn't fit, force rowbreak")
- self.add(length, value, render_fn, label, True)
-
- # Case 1: flush left but too big to fit
- elif self.col == 0 and length > self.raster:
- # Case 1a: even multiple, multirow rect
- if length % self.raster == 0:
- #print(" perfect fit, "+str(length/self.raster)+"-row rect")
- self._add_field(length,
- RectField(self.col, self.row,
- self.raster, length / self.raster,
- render_fn(value), label, self.fill))
- self._row_extend(int(length / self.raster))
- # Case 1b: not even multiple, left tetronimo
- else:
- #print(" long flush left tetronimo")
- self._add_field(length,
- LeftPolylineField(self.row, self.raster,
- math.ceil(length / self.raster),
- length % self.raster,
- render_fn(value), label, self.fill))
- self._row_extend(int(math.floor(length / self.raster)))
- self.col = length % self.raster;
-
- # Case 2: flush right
- elif (self.col + length) % self.raster == 0:
- #print(" long flush right tetronimo")
- self._add_field(length,
- RightPolylineField(self.row, self.raster,
- math.ceil(length / self.raster),
- self.raster - self.col,
- render_fn(value), label, self.fill))
- self._row_extend(int(math.ceil(length / self.raster)))
- self.col = 0
-
- # Case 3: polyline middle tetronimo; too lazy for this
- # corner case now, bail and force a left tetronimo
- else:
- #print(" too lazy for mid tetronimo, force rowbreak")
- self.add(length, value, render_fn, label, True)
-
- def _render_fields(self, dwg, origin, scale, fontsize):
- rid = random_id()
- # create a boxgroup to contain the fields
- gb = dwg.g(id="boxes-"+rid, stroke="black", stroke_width=2)
-
- # create a textgroup to contain the fields
- gt = dwg.g(id="text-"+rid, font_size=fontsize)
-
- # add each field to the group
- for field in self.fields:
- field.add_box_to_drawing(gb, dwg, scale)
- field.add_text_to_drawing(gt, dwg, scale)
-
- # use the groups in the drawing
- dwg.defs.add(gb)
- ub = dwg.use(gb, insert=origin)
- dwg.add(ub)
-
- dwg.defs.add(gt)
- ut = dwg.use(gt, insert=origin)
- dwg.add(ut)
-
- def _render_colhdr(self, dwg, origin, scale, fontsize):
- # create a group to contain the column addresses
- gc = dwg.g(id=random_id(),
- font_size=fontsize)
-
- # draw text where appropriate
- for i in xrange(0, self.raster):
- gc.add(dwg.text(i, ((i + 1) * scale[0] - scale[0]/5, 0),
- style="text-anchor: right; "
- "dominant-baseline: hanging;"))
-
- # use the coladdr group in the drawing
- dwg.defs.add(gc)
- uc = dwg.use(gc, insert = origin)
- dwg.add(uc)
-
- def _render_rowhdr(self, dwg, origin, scale, fontsize):
-
- # create a group to contain the row addresses
- gr = dwg.g(id=random_id(),
- font_size=fontsize)
-
- # draw text where appropriate
- for i, a in enumerate(self.rowaddrs):
- gr.add(dwg.text(hex(a), (0, i * scale[1]),
- style="text-anchor: left; "
- "dominant-baseline: hanging;"))
-
- # use the rowaddr group in the drawing
- dwg.defs.add(gr)
- ur = dwg.use(gr, insert = origin)
- dwg.add(ur)
-
- def render(self, scale):
- # new drawing
- dwg = svgwrite.Drawing(size=(scale[0] * (self.raster + 1),
- scale[1] * (self.row + 2)))
-
- # render column header
- self._render_colhdr(dwg, (scale[0], 0), scale, int(scale[1]/1.75))
-
- # render row header
- self._render_rowhdr(dwg, (0, scale[1]/2), scale, int(scale[1]/1.75))
-
- # render fields
- self._render_fields(dwg, (scale[0], scale[1]/2), scale, int(scale[1]/2))
-
- # return document
- return dwg.tostring()
-
-def draw_msg_header(ofd, version, length, export_time, sequence, odid):
- ofd.add(2, version, label="Version")
- ofd.add(2, length, label="Length")
- ofd.add(4, export_time, render_fn=render_dt8601, label="Export Time")
- ofd.add(4, sequence, label="Sequence")
- ofd.add(4, odid, label="Observation Domain")
-
-def draw_set_header(ofd, setid, setlen):
- ofd.add(2, setid, label="Set ID")
- ofd.add(2, setlen, label="Set Length")
-
-def draw_template(ofd, tmpl, setid=None):
- if not setid:
- setid = tmpl.native_setid()
-
- ofd.add(2, tmpl.tid, label="ID")
- ofd.add(2, tmpl.count(), label="Count")
- if (setid == template.OPTIONS_SET_ID):
- ofd.add(2, tmpl.scopecount, label="Scope")
- for ie in tmpl.ies:
- ofd.add(2, ie, label="IE", render_fn=render_ienumber)
- ofd.add(2, ie.length, label="Len")
- if ie.pen:
- ofd.add(4, ie.pen, label="PEN")
-
-class MessageBufferRenderer(object):
- def __init__(self, msg, scale=(90,30), raster=8):
- self.msg = msg
- self.scale = scale
- self.raster = raster
-
- # FIXME this really, really should be done in a stylesheet.
- self.msg_header_fill = "rgb(255,216,216)"
- self.set_header_fill = "rgb(240,192,216)"
- self.template_fill = "rgb(224,224,255)"
- self.record_fill = [ "rgb(255,255,216)",
- "rgb(216,255,216)" ]
-
- self.ofd = OctetFieldDrawing(self.raster)
-
- def add_msg_header(self, fill=None):
- if fill:
- self.ofd.set_fill(fill)
-
- draw_msg_header(self.ofd, 10, self.msg.length, self.msg.sequence,
- self.msg.get_export_time(), self.msg.odid)
-
- def add_set_header(self, setid, setlen, fill=None):
- if fill:
- self.ofd.set_fill(fill)
-
- draw_set_header(self.ofd, setid, setlen)
-
- def add_template(self, tmpl, fill=None, setid=None):
- if fill:
- self.ofd.set_fill(fill)
-
- draw_template(self.ofd, tmpl, setid=setid)
-
- def add_record_at_offset(self, offset, tmpl, fill=None):
- if fill:
- self.ofd.set_fill(fill)
-
- (values, offset) = tmpl.decode_tuple_from(self.msg.mbuf, offset)
- for v, ie in izip(values, tmpl.ies):
- # prefix with varlen
- if ie.length == types.VARLEN:
- ielen = len(ie.type.valenc(v))
- if ielen > 254:
- self.ofd.add(1, 255)
- self.odd.add(2, ielen, label="varlen")
- else:
- self.ofd.add(1, ielen, label="varlen")
- else:
- ielen = ie.length
-
- if ielen < 2:
- label = midtrunc(ie.name,4,4)
- elif ielen < 4:
- label = midtrunc(ie.name,8,4)
- else:
- label = midtrunc(ie.name,8,8)
-
- if isinstance(v, datetime):
- self.ofd.add(ielen, v, render_fn=render_dt8601, label=label)
- else:
- self.ofd.add(ielen, v, label=label)
-
- return offset
-
- def render(self, start=0, length=65535):
- # record count for color rotation
- reccount = 0
-
- # start the drawing from scratch
- self.ofd = OctetFieldDrawing(self.raster, start)
-
- # prepare the message for rendering
- self.msg.to_bytes()
- self.msg._scan_setlist()
-
- # dump message header
- if start == 0:
- self.add_msg_header(self.msg_header_fill)
-
- # iterate the setlist
- for (offset, setid, setlen) in self.msg.setlist:
- # only render sets within the window
- if offset < start:
- continue
- if offset > start + length:
- break
-
- # add set header
- self.add_set_header(setid, setlen, self.set_header_fill)
-
- setend = offset + setlen
- offset += message._sethdr_st.size # skip set header in decode
- if setid == template.TEMPLATE_SET_ID or \
- setid == template.OPTIONS_SET_ID:
- while offset < setend:
- (tmpl, offset) = template.decode_template_from(
- self.msg.mbuf, offset, setid)
- self.add_template(tmpl, fill=self.template_fill, setid=setid)
- elif setid < 256:
- warn("skipping illegal set id "+str(setid)+" in render")
-
- else:
- try:
- tmpl = self.msg.templates[(self.msg.odid, setid)]
- while (offset + tmpl.minlength <= setend) and\
- (offset < start + length):
- fill = self.record_fill[reccount % len(self.record_fill)]
- offset = self.add_record_at_offset(offset, tmpl, fill)
- reccount += 1
-
- except KeyError:
- while offset < setend:
- self.add_byte(self.msg.mbuf[offset], "white")
- offset += 1
-
- except EOFError:
- pass
-
- return self.ofd.render(self.scale)
-
-class MessageStreamRenderer(MessageBufferRenderer):
- def __init__(self, stream, scale=(90,30), raster=8):
- super(self.__class__, self).__init__(message.MessageBuffer(), scale, raster)
- self.stream = stream
-
- def render_next_message(self, length=65535):
- self.msg.read_message(self.stream)
- # must decode the message to ensure all templates loaded into the TIB
- for rec in self.msg.namedict_iterator():
- pass
- return self.render(length=length)