Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGES.txt
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,15 @@ v0.10.0, 2026-11-20 -- Modernize packaging (pyproject.toml, Python 3.11+, drop
accept timezone-aware datetimes on encode while
eliminating Python 3.12+ deprecation warnings; expand
pytest test suite.

v1.0.0, 2026-11-21 -- Separate IPFIX session state into ipfix.session.Session
(templates, UDP template lifetimes, sequence checking);
add DatagramReader, DatagramWriter (with UDP MTU default
and RFC 7011 periodic template refresh), and UDP collect
support in ipfix2csv; switch decoded datetimes and
get_export_time() to timezone-aware UTC (breaking) with
RFC 5905 NTP Era 1 (2036) rollover handling; support
repeated IEs in templates; add PEP 484 type annotations
with py.typed and Hypothesis fuzz tests; add 0.x -> 1.0
migration guide in README.md.

55 changes: 48 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@

IPFIX (RFC 7011) implementation for Python 3.11+.

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.
This package provides a Python interface to IPFIX message streams and UDP
datagrams, tools for building IPFIX Exporting and Collecting Processes, a
bridge between IPFIX abstract data types (ADTs) and native Python data types,
and a read-only NetFlow v9 PDU decoder.

## Installation

Expand Down Expand Up @@ -39,8 +38,50 @@ msg.add_template(tmpl)
msg.export_ensure_set(256)
```

Command-line utilities `ipfix2csv` and `ipfixstat` are installed as console
scripts.
For UDP collectors and exporters, use `ipfix.session.Session` with
`ipfix.reader.DatagramReader` and `ipfix.writer.DatagramWriter` so template
state, UDP template lifetimes, and periodic template refreshes are managed
automatically across datagrams.

Command-line utilities `ipfix2csv` (supporting files, TCP, and UDP) and
`ipfixstat` are installed as console scripts.

## Migrating from 0.x to 1.0

`v1.0.0` completes the modernization started in `v0.10.0` with a small set of
intentional breaking changes:

1. **Timezone-aware UTC `datetime` returns:**
All decoded `dateTime*` Information Elements, `MessageBuffer.get_export_time()`,
`ipfix.ie.InformationElement.parse()` for datetime types, and
`ipfix.v9pdu.TimeAdapter` now return **timezone-aware UTC** `datetime`
objects (`tzinfo=datetime.timezone.utc`) instead of naive `datetime`s.
- Encoding (`export_*`) continues to accept both timezone-aware (converted
to UTC) and naive (assumed UTC) `datetime` objects.
- If your code compares or subtracts decoded timestamps against naive
`datetime`s, update your reference timestamps to use `tzinfo=datetime.UTC`
(or `datetime.now(datetime.UTC)`).
- `dateTimeMicroseconds` and `dateTimeNanoseconds` now handle RFC 5905 NTP
Era 1 rollover (February 7, 2036).
2. **Separated `Session` state & UDP helpers:**
Templates, UDP template lifetimes, and sequence numbers now live in
`ipfix.session.Session`. `MessageBuffer()` continues to create an internal
default `Session` (and exposes `.templates` and `.sequences` properties) for
backwards compatibility, so existing TCP/file code works unchanged. UDP
collectors and exporters should migrate to `DatagramReader` /
`DatagramWriter` (or pass a shared `Session` to `MessageBuffer(session=...)`).
3. **Repeated IEs in a single template:**
If a template contains multiple occurrences of the same IE name (RFC 7011 §8),
`namedict_iterator()` now returns a `list` of values under that key instead
of silently overwriting earlier occurrences. Templates with unique IE names
are unaffected.
4. **Fixed-length `string` encoding (introduced in `0.10.0`):**
Encoding a UTF-8 string whose byte length exceeds a fixed-length `string[N]`
field now raises `ValueError` instead of silently truncating mid-codepoint,
and trailing `\x00` padding is stripped on decode.
5. **Python 3.11+ only:**
Python 2.7 compatibility (`ipfix.compat`) and `vis-package` have been
removed.

## Development

Expand Down
6 changes: 3 additions & 3 deletions ipfix/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@

"""

from . import ie, message, template, types
from . import ie, message, session, template, types

__version__ = "0.10.0"
__version__ = "1.0.0"

__all__ = ["types", "ie", "template", "message", "__version__"]
__all__ = ["types", "ie", "template", "session", "message", "__version__"]
25 changes: 24 additions & 1 deletion ipfix/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,32 @@ def handle(self):

with socketserver.TCPServer((args.bind, args.port), TcpCsvHandler) as ss:
ss.serve_forever()
elif args.collect == "udp":
sys.stderr.write(
f"starting UDP CP on {args.bind}:{args.port}; Ctrl-C to stop\n"
)
sys.stderr.flush()
cols = ie.spec_list(args.ienames)
dg_reader = reader.DatagramReader()
csv_writer = csv.writer(sys.stdout, dialect="unix")
csv_writer.writerow([e.name for e in cols])
sys.stdout.flush()

class UdpCsvHandler(socketserver.DatagramRequestHandler):
def handle(self):
for rec in dg_reader.tuple_iterator(
self.packet, cols, peer=self.client_address
):
csv_writer.writerow(
[col.unparse(val) for val, col in zip(rec, cols, strict=True)]
)
sys.stdout.flush()

with socketserver.UDPServer((args.bind, args.port), UdpCsvHandler) as ss:
ss.serve_forever()
elif args.collect:
raise ValueError(
f"Unsupported transport {args.collect}; must be 'tcp' in this revision"
f"Unsupported transport {args.collect}; must be 'tcp' or 'udp'"
)
elif args.file:
with _open_input(args.file, args.gzip, args.bzip2) as f:
Expand Down
97 changes: 61 additions & 36 deletions ipfix/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,9 +151,9 @@
... print("{}: {}".format(key, value))
...
>>> 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))]
[('destinationIPv4Address', IPv4Address('10.5.6.7')), ('flowStartMilliseconds', datetime.datetime(2013, 6, 21, 14, 0, tzinfo=datetime.timezone.utc)), ('packetDeltaCount', 27), ('sourceIPv4Address', IPv4Address('10.1.2.3'))]
[('destinationIPv4Address', IPv4Address('10.12.13.14')), ('flowStartMilliseconds', datetime.datetime(2013, 6, 21, 14, 0, 2, tzinfo=datetime.timezone.utc)), ('packetDeltaCount', 33), ('sourceIPv4Address', IPv4Address('10.8.9.11'))]
[('flowStartMilliseconds', datetime.datetime(2013, 6, 21, 14, 0, 4, tzinfo=datetime.timezone.utc))]
myNewInformationElement: Grüezi, Y'all

The tuple interface for reading messages is designed for applications with a
Expand All @@ -167,8 +167,8 @@
>>> for rec in msg.tuple_iterator(ielist):
... print(rec)
...
(datetime.datetime(2013, 6, 21, 14, 0), 27)
(datetime.datetime(2013, 6, 21, 14, 0, 2), 33)
(datetime.datetime(2013, 6, 21, 14, 0, tzinfo=datetime.timezone.utc), 27)
(datetime.datetime(2013, 6, 21, 14, 0, 2, tzinfo=datetime.timezone.utc), 33)

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.
Expand All @@ -188,6 +188,7 @@
from warnings import warn

from . import template, types
from .session import Session
from .template import IpfixDecodeError, IpfixEncodeError

_sethdr_st = struct.Struct("!HH")
Expand All @@ -214,20 +215,25 @@ class MessageBuffer:
Implements a buffer for reading or writing IPFIX messages.
"""

def __init__(self, buf_sz=65536):
"""Create a new MessageBuffer instance."""
def __init__(self, buf_sz: int = 65536, session: Session | None = None) -> None:
"""Create a new MessageBuffer instance.

:param buf_sz: Internal buffer size in bytes (default 65536).
:param session: Optional :class:`ipfix.session.Session` holding
template and sequence state. If omitted, a private
default :class:`Session` is created.
"""
self.mbuf = memoryview(bytearray(buf_sz))
self.length = 0
self.sequence = None
self.export_epoch = None
self.odid = 0
self.streamid = 0

self.templates = {}
self.accepted_tids = set()
self.sequences = {}
self.session: Session = session if session is not None else Session()
self.accepted_tids: set[tuple[int, int]] = set()

self.setlist = []
self.setlist: list[tuple[int, int, int]] = []

self.auto_export_time = True
self.cursetoff = 0
Expand All @@ -243,6 +249,16 @@ def __init__(self, buf_sz=65536):
self.ignored_data_set_hook = None
self.message_header_hook = None

@property
def templates(self) -> dict[tuple[int, int], template.Template]:
"""Active templates dictionary (delegated to :attr:`session`)."""
return self.session.templates

@property
def sequences(self) -> dict[tuple[int, int], int]:
"""Sequence numbers dictionary (delegated to :attr:`session`)."""
return self.session.sequences

def __repr__(self):
if self.cursetid:
addinf = f" (writing set {self.cursetid})"
Expand Down Expand Up @@ -281,8 +297,7 @@ def set_export_time(self, dt=None):
self.auto_export_time = False

def _increment_sequence(self):
key = (self.odid, self.streamid)
self.sequences[key] = (self.sequences.get(key, 0) + 1) & 0xFFFFFFFF
self.session.increment_sequence(self.odid, self.streamid, 1)

def _scan_setlist(self):
# We've read a message. Discard all export state.
Expand Down Expand Up @@ -343,6 +358,9 @@ def read_message(self, stream):
)
self.mbuf[_msghdr_st.size : self.length] = msgbody

# verify sequence number against session state
self.session.check_sequence(self.odid, self.streamid, self.sequence)

# call the message header hook
if self.message_header_hook:
self.message_header_hook(self)
Expand All @@ -366,18 +384,13 @@ def from_bytes(self, 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)
for removed_tid in self.session.withdraw_all_templates(
self.odid, setid=setid
):
self.accepted_tids.discard((self.odid, removed_tid))
else:
key = (self.odid, tid)
self.templates.pop(key, None)
self.accepted_tids.discard(key)
self.session.delete_template(self.odid, tid)
self.accepted_tids.discard((self.odid, tid))

def record_iterator(
self,
Expand Down Expand Up @@ -432,7 +445,7 @@ def record_iterator(
if tmpl.count() == 0:
self._handle_template_withdrawal(setid, tmpl.tid)
else:
self.templates[(self.odid, tmpl.tid)] = tmpl
self.session.add_template(self.odid, tmpl)
if tmplaccept_fn(tmpl):
self.accepted_tids.add((self.odid, tmpl.tid))
else:
Expand All @@ -445,14 +458,18 @@ def record_iterator(
warn("skipping illegal set id " + str(setid), stacklevel=2)
else:
try:
tmpl = self.templates[(self.odid, setid)]
tmpl = self.session.get_template(self.odid, setid)
except KeyError:
self.accepted_tids.discard((self.odid, setid))
if self.unknown_data_set_hook:
self.unknown_data_set_hook(
self, self.mbuf[offset - _sethdr_st.size : setend]
)
continue

if (self.odid, setid) not in self.accepted_tids and tmplaccept_fn(tmpl):
self.accepted_tids.add((self.odid, setid))

if (self.odid, setid) in self.accepted_tids:
if tmpl.minlength <= 0:
raise IpfixDecodeError(
Expand Down Expand Up @@ -494,8 +511,17 @@ def tuple_iterator(self, ielist):
listing IEs to return as a tuple
:returns: a tuple iterator for tuples as in ielist order
"""
# Also ensure tuple_iterator checks multiplicity for repeated IEs
def tmplaccept_fn(tmpl):
return all(elem in tmpl.ies for elem in ielist)
needed: dict[tuple[int, int], int] = {}
for elem in ielist:
key = (elem.pen, elem.num)
needed[key] = needed.get(key, 0) + 1
avail: dict[tuple[int, int], int] = {}
for elem in tmpl.ies:
key = (elem.pen, elem.num)
avail[key] = avail.get(key, 0) + 1
return all(avail.get(k, 0) >= cnt for k, cnt in needed.items())

if (
self.last_tuple_iterator_ielist is None
Expand Down Expand Up @@ -546,15 +572,15 @@ def write_message(self, stream):

def add_template(self, tmpl, export=True):
"""
Add a template to this MessageBuffer. Adding a template makes it
Add a template to this MessageBuffer's Session. Adding a template makes it
available for use for exporting records; see :meth:`export_new_set`.

:param tmpl: the template to add
:param export: If True, export this template to the MessageBuffer
after adding it.
:raises: EndOfMessage
"""
self.templates[(self.odid, tmpl.tid)] = tmpl
self.session.add_template(self.odid, tmpl)

if export:
self.export_template(tmpl.tid)
Expand All @@ -564,15 +590,16 @@ def add_template(self, tmpl, export=True):

def delete_template(self, tid, export=True):
"""
Delete a template by ID from this MessageBuffer.
Delete a template by ID from this MessageBuffer's Session.

:param tid: ID of the template to delete
:param export: if True, export a Template Withdrawal for this
Template after deleting it
:raises: EndOfMessage, KeyError
"""
setid = self.templates[(self.odid, tid)].native_setid()
del self.templates[(self.odid, tid)]
tmpl = self.session.get_template(self.odid, tid)
setid = tmpl.native_setid()
self.session.delete_template(self.odid, tid)
self.accepted_tids.discard((self.odid, tid))
if export:
self._export_template_withdrawal(setid, tid)
Expand All @@ -585,9 +612,7 @@ def active_template_ids(self):

:returns: a template ID iterator
"""
for odid, tid in self.templates:
if odid == self.odid:
yield tid
yield from self.session.active_template_ids(self.odid)

def template_for_id(self, tid):
"""
Expand All @@ -597,7 +622,7 @@ def template_for_id(self, tid):
:returns: the template
:raises: KeyError
"""
return self.templates[(self.odid, tid)]
return self.session.get_template(self.odid, tid)

def begin_export(self, odid=None):
"""
Expand Down
Empty file added ipfix/py.typed
Empty file.
Loading
Loading