From 53f28d19139cc23f56d40e02c5d8856d9984547d Mon Sep 17 00:00:00 2001
From: Martin Teichmann <martin.teichmann@gmail.com>
Date: Sat, 4 Feb 2023 14:27:52 +0000
Subject: [PATCH] add the prandom function to ebpf

and use it instead of our own random number generator for the
missed packages simulator
---
 ebpfcat/ebpf.py    | 15 +++++++++++++++
 ebpfcat/ebpfcat.py | 10 ++++------
 2 files changed, 19 insertions(+), 6 deletions(-)

diff --git a/ebpfcat/ebpf.py b/ebpfcat/ebpf.py
index 6fd6e59..a615bcf 100644
--- a/ebpfcat/ebpf.py
+++ b/ebpfcat/ebpf.py
@@ -902,6 +902,21 @@ class ktime(Expression):
             yield dst, True, False
 
 
+class prandom(Expression):
+    """a function that returns the current ktime in ns"""
+    def __init__(self, ebpf):
+        self.ebpf = ebpf
+
+    @contextmanager
+    def calculate(self, dst, long, signed, force=False):
+        with self.ebpf.get_free_register(dst) as dst:
+            with self.ebpf.save_registers([i for i in range(6) if i != dst]):
+                self.ebpf.call(FuncId.get_prandom_u32)
+                if dst != 0:
+                    self.ebpf.r[dst] = self.ebpf.r0
+            yield dst, True, False
+
+
 class RegisterDesc:
     def __init__(self, no, array):
         self.no = no
diff --git a/ebpfcat/ebpfcat.py b/ebpfcat/ebpfcat.py
index bf6b91c..c73ec4f 100644
--- a/ebpfcat/ebpfcat.py
+++ b/ebpfcat/ebpfcat.py
@@ -21,7 +21,7 @@ from struct import pack, unpack, calcsize, pack_into, unpack_from
 from time import time
 from .arraymap import ArrayMap, ArrayGlobalVarDesc
 from .ethercat import ECCmd, EtherCat, Packet, Terminal
-from .ebpf import FuncId, MemoryDesc, SubProgram, ktime
+from .ebpf import FuncId, MemoryDesc, SubProgram, prandom
 from .xdp import XDP, XDPExitCode
 from .bpf import (
     ProgType, MapType, create_map, update_elem, prog_test_run, lookup_elem)
@@ -277,11 +277,9 @@ class EtherXDP(XDP):
     rate = 0
 
     def program(self):
-        with self.tmp:
-            self.ebpf.tmp = ktime(self.ebpf)
-            self.ebpf.tmp = self.ebpf.tmp * 0xcf019d85 + 1
-            with self.ebpf.tmp & 0xffff < self.rate:
-                self.ebpf.exit(XDPExitCode.DROP)
+        with prandom(self.ebpf) & 0xffff < self.rate:
+            self.dropcounter += 1
+            self.ebpf.exit(XDPExitCode.DROP)
         with self.packetSize > 24 as p, p.pH[12] == 0xA488, p.pB[16] == 0:
             self.r3 = p.pI[18]
             with self.counters.get_address(None, False, False) as (dst, _), \
-- 
GitLab