#include <config.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef HAVE_STDBOOL_H
# include <stdbool.h>
#else
# include "compat/stdbool.h"
#endif
#ifdef HAVE_STRING_H
# include <string.h>
#endif
#ifdef HAVE_STRINGS_H
# include <strings.h>
#endif
#include <ctype.h>
#include <time.h>
#include "sudo_compat.h"
#include "sudoers_debug.h"
#include "parse.h"
time_t
parse_gentime(const char *timestr)
{
char tcopy[sizeof("yyyymmddHHMMSS.F")];
const char *cp;
time_t result;
struct tm tm;
size_t len;
int items, tzoff = 0;
bool islocal = false;
debug_decl(parse_gentime, SUDOERS_DEBUG_PARSER)
len = strspn(timestr, "0123456789.,");
if (len >= sizeof(tcopy)) {
sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO,
"unable to parse general time string %s", timestr);
debug_return_time_t(-1);
}
memcpy(tcopy, timestr, len);
tcopy[len] = '\0';
memset(&tm, 0, sizeof(tm));
items = sscanf(tcopy, "%4d%2d%2d%2d%2d%2d", &tm.tm_year, &tm.tm_mon,
&tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec);
if (items == EOF || items < 4) {
sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO,
"only parsed %d items in general time string %s", items, timestr);
debug_return_time_t(-1);
}
cp = timestr + ((items + 1) * 2);
if ((cp[0] == '.' || cp[0] == ',') && isdigit((unsigned char)cp[1])) {
int frac = cp[1] - '0';
switch (items) {
case 4:
tm.tm_min += 60 / 10 * frac;
break;
case 5:
tm.tm_sec += 60 / 10 * frac;
break;
case 6:
break;
}
cp += 2;
}
switch (*cp) {
case '-':
case '+': {
int hour = 0, min = 0;
tm.tm_isdst = 0;
items = sscanf(cp + 1, "%2d%2d", &hour, &min);
if (items == EOF || items < 1) {
sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO,
"unable to parse time zone offset in %s, items %d",
timestr, items);
debug_return_time_t(-1);
}
if (*cp == '-')
tzoff = -((hour * 60) + min) * 60;
else
tzoff = ((hour * 60) + min) * 60;
cp += 1 + (items * 2);
break;
}
case 'Z':
tm.tm_isdst = 0;
cp++;
break;
case '\0':
tm.tm_isdst = -1;
islocal = true;
break;
default:
sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO,
"unable to parse general time string %s", timestr);
debug_return_time_t(-1);
}
if (*cp != '\0') {
sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO,
"trailing garbage in general time string %s", timestr);
debug_return_time_t(-1);
}
tm.tm_year -= 1900;
tm.tm_mon--;
result = mktime(&tm);
if (result != -1) {
if (!islocal) {
result += get_gmtoff(&result);
result -= tzoff;
}
}
debug_return_time_t(result);
}