Skip to content

Commit

Permalink
decoder: isolate the matching routine in one class
Browse files Browse the repository at this point in the history
  • Loading branch information
svinota committed Mar 19, 2024
1 parent cd28b69 commit 40d17fe
Showing 1 changed file with 14 additions and 14 deletions.
28 changes: 14 additions & 14 deletions pyroute2/decoder/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def __repr__(self):
)


class Match:
class MatchOps:

@staticmethod
def AND():
Expand Down Expand Up @@ -106,7 +106,7 @@ def f(packet_header, ll_header, raw, data_offset, stack):
return f


class Parser:
class Matcher:
def __init__(self, script):
self.parsed = []
self.filters = []
Expand All @@ -117,16 +117,16 @@ def __init__(self, script):
token = self.get_token(ignore=',')
if token == '':
break
method = getattr(Match, token)
method = getattr(MatchOps, token)
if token in ('AND', 'OR'):
op = method
continue
kwarg = {}
token = self.get_token(expect='{')
while token != '}':
while True:
token = self.get_token(ignore=',')
if token == '}':
continue
if token in ('}', ''):
break
self.get_token(expect='=')
value = self.get_token()
try:
Expand All @@ -149,6 +149,12 @@ def get_token(self, expect=None, ignore=None):
self.parsed.append(token)
return token

def match(self, packet_header, ll_header, data, offset):
stack = []
for method in self.filters:
stack.append(method(packet_header, ll_header, data, offset, stack))
return all(stack)


class LoaderPcap:

Expand All @@ -158,7 +164,7 @@ def __init__(self, data, cls, script):
self.metadata = PcapMetaData(*struct.unpack("IHHiIII", self.raw[:24]))
self.offset = 24
self.cls = cls
self.parser = Parser(script)
self.matcher = Matcher(script)

def decode_packet_header(self, data, offset):
return PcapPacketHeader(
Expand All @@ -170,12 +176,6 @@ def decode_ll_header(self, data, offset):
*struct.unpack(">HHIIHH", data[offset : offset + 16]) + (16,)
)

def match(self, packet_header, ll_header, data, offset):
stack = []
for method in self.parser.filters:
stack.append(method(packet_header, ll_header, data, offset, stack))
return all(stack)

@property
def data(self):
while self.offset < len(self.raw):
Expand All @@ -184,7 +184,7 @@ def data(self):
ll_header = self.decode_ll_header(self.raw, self.offset)
self.offset += ll_header.header_len
length = packet_header.incl_len - ll_header.header_len
if self.match(packet_header, ll_header, self.raw, self.offset):
if self.matcher.match(packet_header, ll_header, self.raw, self.offset):
msg = Message(
packet_header,
ll_header,
Expand Down

0 comments on commit 40d17fe

Please sign in to comment.