summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorRafael Zalamena <rzalamena@opensourcerouting.org>2023-01-19 12:16:11 -0300
committerRafael Zalamena <rzalamena@opensourcerouting.org>2023-01-20 15:40:28 -0300
commitfce7f209fce60f0d8aff7af3df3e0a5434fc456f (patch)
tree5eeb8b5b75b964ddbd3a76379c6c98c6cd5cf560 /lib
parentb6ee94b5b1f0a0652455264fa62a92ed5abbf855 (diff)
*: introduce function for sequence numbers
Don't directly use `time()` for generating sequence numbers for two reasons: 1. `time()` can go backwards (due to NTP or time adjustments) 2. Coverity Scan warns every time we truncate a `time_t` variable for good reason (verify that we are Y2K38 ready). Found by Coverity Scan (CID 1519812, 1519786, 1519783 and 1519772) Signed-off-by: Rafael Zalamena <rzalamena@opensourcerouting.org>
Diffstat (limited to 'lib')
-rw-r--r--lib/network.c21
-rw-r--r--lib/network.h18
2 files changed, 39 insertions, 0 deletions
diff --git a/lib/network.c b/lib/network.c
index b60ad9a57c..cd62b8b593 100644
--- a/lib/network.c
+++ b/lib/network.c
@@ -122,3 +122,24 @@ float ntohf(float net)
{
return htonf(net);
}
+
+uint64_t frr_sequence_next(void)
+{
+ static uint64_t last_sequence;
+ struct timespec ts;
+
+ (void)clock_gettime(CLOCK_MONOTONIC, &ts);
+ if (last_sequence == (uint64_t)ts.tv_sec) {
+ last_sequence++;
+ return last_sequence;
+ }
+
+ last_sequence = ts.tv_sec;
+ return last_sequence;
+}
+
+uint32_t frr_sequence32_next(void)
+{
+ /* coverity[Y2K38_SAFETY] */
+ return (uint32_t)frr_sequence_next();
+}
diff --git a/lib/network.h b/lib/network.h
index 10ed917572..c163eab8f7 100644
--- a/lib/network.h
+++ b/lib/network.h
@@ -82,6 +82,24 @@ extern float ntohf(float);
#endif
/**
+ * Generate a sequence number using monotonic clock with a same second call
+ * protection to help guarantee a unique incremental sequence number that never
+ * goes back (except when wrapping/overflow).
+ *
+ * **NOTE** this function is not thread safe since it uses `static` variable.
+ *
+ * This function and `frr_sequence32_next` should be used to initialize
+ * sequence numbers without directly calling other `time_t` returning
+ * functions because of `time_t` truncation warnings.
+ *
+ * \returns `uint64_t` number based on the monotonic clock.
+ */
+extern uint64_t frr_sequence_next(void);
+
+/** Same as `frr_sequence_next` but returns truncated number. */
+extern uint32_t frr_sequence32_next(void);
+
+/**
* Helper function that returns a random long value. The main purpose of
* this function is to hide a `random()` call that gets flagged by coverity
* scan and put it into one place.