From: Mats Klepsland Date: Fri, 23 Oct 2015 10:55:34 +0000 (+0200) Subject: util-time: add function to parse a date string based on patterns X-Git-Tag: suricata-3.2beta1~289 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=c49cb053992f5a4675782c81e585bdcea773427e;p=thirdparty%2Fsuricata.git util-time: add function to parse a date string based on patterns Add function SCStringPatternToTime to parse a date string based on an array of pattern strings. --- diff --git a/src/util-time.c b/src/util-time.c index 352c041fad..992650e317 100644 --- a/src/util-time.c +++ b/src/util-time.c @@ -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; +} diff --git a/src/util-time.h b/src/util-time.h index 2b4944528a..c2cbd5a22b 100644 --- a/src/util-time.h +++ b/src/util-time.h @@ -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__ */