#include <sys/cdefs.h>
#if 0
static const char rcsid[] = "Id: ns_date.c,v 1.6 2005/04/27 04:56:39 sra Exp ";
#else
__RCSID("$NetBSD: ns_date.c,v 1.2 2018/12/13 08:39:34 maya Exp $");
#endif
#include "port_before.h"
#include <arpa/nameser.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "port_after.h"
static int datepart(const char *, int, int, int, int *);
u_int32_t
ns_datetosecs(const char *cp, int *errp) {
struct tm tim;
u_int32_t result;
int mdays, i;
static const int days_per_month[12] =
{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (strlen(cp) != 14U) {
*errp = 1;
return (0);
}
*errp = 0;
memset(&tim, 0, sizeof tim);
tim.tm_year = datepart(cp + 0, 4, 1990, 9999, errp) - 1900;
tim.tm_mon = datepart(cp + 4, 2, 01, 12, errp) - 1;
tim.tm_mday = datepart(cp + 6, 2, 01, 31, errp);
tim.tm_hour = datepart(cp + 8, 2, 00, 23, errp);
tim.tm_min = datepart(cp + 10, 2, 00, 59, errp);
tim.tm_sec = datepart(cp + 12, 2, 00, 59, errp);
if (*errp)
return (0);
#define SECS_PER_DAY ((u_int32_t)24*60*60)
#define isleap(y) ((((y) % 4) == 0 && ((y) % 100) != 0) || ((y) % 400) == 0)
result = tim.tm_sec;
result += tim.tm_min * 60;
result += tim.tm_hour * (60*60);
result += (tim.tm_mday - 1) * SECS_PER_DAY;
mdays = 0;
for (i = 0; i < tim.tm_mon; i++)
mdays += days_per_month[i];
result += mdays * SECS_PER_DAY;
if (tim.tm_mon > 1 && isleap(1900+tim.tm_year))
result += SECS_PER_DAY;
result += (tim.tm_year - 70) * (SECS_PER_DAY*365);
for (i = 70; i < tim.tm_year; i++)
if (isleap(1900+i))
result += SECS_PER_DAY;
return (result);
}
static int
datepart(const char *buf, int size, int min, int max, int *errp) {
int result = 0;
int i;
for (i = 0; i < size; i++) {
if (!isdigit((unsigned char)(buf[i])))
*errp = 1;
result = (result * 10) + buf[i] - '0';
}
if (result < min)
*errp = 1;
if (result > max)
*errp = 1;
return (result);
}