]> git.ipfire.org Git - thirdparty/suricata.git/commitdiff
util-time: add function to parse a date string based on patterns
authorMats Klepsland <mats.klepsland@gmail.com>
Fri, 23 Oct 2015 10:55:34 +0000 (12:55 +0200)
committerVictor Julien <victor@inliniac.net>
Sun, 25 Sep 2016 20:35:34 +0000 (22:35 +0200)
Add function SCStringPatternToTime to parse a date string based on an
array of pattern strings.

src/util-time.c
src/util-time.h

index 352c041fad7abe2d72676e5277691ac55ba0af4b..992650e317d6056086f61596b82577487608c911 100644 (file)
@@ -392,3 +392,57 @@ time_t SCMkTimeUtc (struct tm *tp)
         result -= tp->tm_gmtoff;
     return result;
 }
+
+/**
+ * \brief Parse a date string based on specified patterns.
+ *
+ * This function is based on GNU C library getdate.
+ *
+ * \param string       Date string to parse.
+ * \param patterns     String array containing patterns.
+ * \param num_patterns Number of patterns to check.
+ * \param tp           Pointer to broken-down time.
+ *
+ * \retval 0 on success.
+ * \retval 1 on failure.
+ */
+int SCStringPatternToTime (char *string, char **patterns, int num_patterns,
+                           struct tm *tp)
+{
+    char *result = NULL;
+    int i = 0;
+
+    /* Do the pattern matching */
+    for (i = 0; i < num_patterns; i++)
+    {
+        if (patterns[i] == NULL)
+            continue;
+
+        tp->tm_hour = tp->tm_min = tp->tm_sec = 0;
+        tp->tm_year = tp->tm_mon = tp->tm_mday = tp->tm_wday = INT_MIN;
+        tp->tm_isdst = -1;
+        tp->tm_gmtoff = 0;
+        tp->tm_zone = NULL;
+        result = strptime(string, patterns[i], tp);
+
+        if (result && *result == '\0')
+            break;
+    }
+
+    /* Return if no patterns matched */
+    if (result == NULL || *result != '\0')
+        return 1;
+
+    /* Return if no date is given */
+    if (tp->tm_year == INT_MIN && tp->tm_mon == INT_MIN &&
+            tp->tm_mday == INT_MIN)
+        return 1;
+
+    /* The first of the month is assumed, if only year and
+       month is given */
+    if (tp->tm_year != INT_MIN && tp->tm_mon != INT_MIN &&
+            tp->tm_mday <= 0)
+        tp->tm_mday = 1;
+
+    return 0;
+}
index 2b4944528ab42aa001d78e2ead22d38efdb4633b..c2cbd5a22bebfe4b8ff4ee337c29165515bffc5f 100644 (file)
@@ -54,6 +54,8 @@ struct tm *SCLocalTime(time_t timep, struct tm *result);
 void CreateTimeString (const struct timeval *ts, char *str, size_t size);
 void CreateIsoTimeString (const struct timeval *ts, char *str, size_t size);
 time_t SCMkTimeUtc (struct tm *tp);
+int SCStringPatternToTime (char *string, char **patterns,
+                           int num_patterns, struct tm *time);
 
 #endif /* __UTIL_TIME_H__ */