Skip to content
Myr

util.c

This file

Path

src/util.c

1,268 lines · 36.8 KiB · C

Last changed by

Strip UTF-8 BOM at the start of each input file (#3657)itchynybefore adoptione001deb

History of this file

Take it

1/*-2 * Parts (strptime()) Copyright (c) 1997, 1998, 2005, 2008 The NetBSD Foundation, Inc.3 * All rights reserved.4 *5 * This code was contributed to The NetBSD Foundation by Klaus Klein.6 * Heavily optimised by David Laight7 *8 * Redistribution and use in source and binary forms, with or without9 * modification, are permitted provided that the following conditions10 * are met:11 * 1. Redistributions of source code must retain the above copyright12 *    notice, this list of conditions and the following disclaimer.13 * 2. Redistributions in binary form must reproduce the above copyright14 *    notice, this list of conditions and the following disclaimer in the15 *    documentation and/or other materials provided with the distribution.16 *17 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS18 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED19 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR20 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS21 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN25 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE27 * POSSIBILITY OF SUCH DAMAGE.28 */2930#include <sys/types.h>31#include <sys/stat.h>32#include <assert.h>33#include <errno.h>34#include <fcntl.h>35#include <limits.h>36#include <string.h>37#include <unistd.h>38#include <stdlib.h>39#include <stddef.h>40#ifdef HAVE_ALLOCA_H41# include <alloca.h>42#elif !defined alloca43# ifdef __GNUC__44#  define alloca __builtin_alloca45# elif defined _MSC_VER46#  include <malloc.h>47#  define alloca _alloca48# elif !defined HAVE_ALLOCA49#  ifdef  __cplusplus50extern "C"51#  endif52void *alloca (size_t);53# endif54#endif5556#ifdef WIN3257#include <windows.h>58#include <processenv.h>59#include <shellapi.h>60#include <wchar.h>61#include <wtypes.h>62#endif636465#include "util.h"66#include "jq.h"67#include "jv_alloc.h"68#include "jv_unicode.h"6970#ifdef WIN3271FILE *fopen(const char *fname, const char *mode) {72  size_t sz = sizeof(wchar_t) * MultiByteToWideChar(CP_UTF8, 0, fname, -1, NULL, 0);73  wchar_t *wfname = alloca(sz + 2); // +2 is not needed, but just in case74  MultiByteToWideChar(CP_UTF8, 0, fname, -1, wfname, sz);7576  sz = sizeof(wchar_t) * MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);77  wchar_t *wmode = alloca(sz + 2); // +2 is not needed, but just in case78  MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, sz);79  return _wfopen(wfname, wmode);80}81#endif8283jv expand_path(jv path) {84  assert(jv_get_kind(path) == JV_KIND_STRING);85  const char *pstr = jv_string_value(path);86  jv ret = path;87  if (jv_string_length_bytes(jv_copy(path)) > 1 && pstr[0] == '~' && pstr[1] == '/') {88    jv home = get_home();89    if (jv_is_valid(home)) {90      ret = jv_string_fmt("%s/%s",jv_string_value(home),pstr+2);91      jv_free(home);92    } else {93      jv emsg = jv_invalid_get_msg(home);94      ret = jv_invalid_with_msg(jv_string_fmt("Could not expand %s. (%s)", pstr, jv_string_value(emsg)));95      jv_free(emsg);96    }97    jv_free(path);98  }99  return ret;100}101102jv get_home(void) {103  jv ret;104  char *home = getenv("HOME");105  if (!home) {106#ifndef WIN32107    ret = jv_invalid_with_msg(jv_string("Could not find home directory."));108#else109    home = getenv("USERPROFILE");110    if (!home) {111      home = getenv("HOMEPATH");112      if (!home) {113        ret = jv_invalid_with_msg(jv_string("Could not find home directory."));114      } else {115        const char *hd = getenv("HOMEDRIVE");116        if (!hd) hd = "";117        ret = jv_string_fmt("%s%s",hd,home);118      }119    } else {120      ret = jv_string(home);121    }122#endif123  } else {124    ret = jv_string(home);125  }126  return ret;127}128129130jv jq_realpath(jv path) {131  int path_max;132  char *buf = NULL;133#ifdef _PC_PATH_MAX134  path_max = pathconf(jv_string_value(path),_PC_PATH_MAX);135#else136  path_max = PATH_MAX;137#endif138  if (path_max > 0) {139     buf = jv_mem_alloc(path_max);140  }141#ifdef WIN32142  char *tmp = _fullpath(buf, jv_string_value(path), path_max);143#else144  char *tmp = realpath(jv_string_value(path), buf);145#endif146  if (tmp == NULL) {147    free(buf);148    return path;149  }150  jv_free(path);151  path = jv_string(tmp);152  free(tmp);153  return path;154}155156const void *_jq_memmem(const void *haystack, size_t haystacklen,157                       const void *needle, size_t needlelen) {158#ifdef HAVE_MEMMEM159  return (const void*)memmem(haystack, haystacklen, needle, needlelen);160#else161  const char *h = haystack;162  const char *n = needle;163  size_t hi, hi2, ni;164165  if (haystacklen < needlelen || haystacklen == 0)166    return NULL;167  for (hi = 0; hi < (haystacklen - needlelen + 1); hi++) {168    for (ni = 0, hi2 = hi; ni < needlelen; ni++, hi2++) {169      if (h[hi2] != n[ni])170        goto not_this;171    }172173    return &h[hi];174175not_this:176    continue;177  }178  return NULL;179#endif /* !HAVE_MEMMEM */180}181182struct jq_util_input_state {183  jq_util_msg_cb err_cb;184  void *err_cb_data;185  jv_parser *parser;186  FILE* current_input;187  char **files;188  int nfiles;189  int curr_file;190  int failures;191  jv slurped;192  char buf[4096];193  size_t buf_valid_len;194  jv current_filename;195  size_t current_line;196  int at_file_start;197};198199static void fprinter(void *data, const char *fname) {200  fprintf((FILE *)data, "jq: error: Could not open file %s: %s\n", fname, strerror(errno));201}202203// If parser == NULL -> RAW204jq_util_input_state *jq_util_input_init(jq_util_msg_cb err_cb, void *err_cb_data) {205  if (err_cb == NULL) {206    err_cb = fprinter;207    err_cb_data = stderr;208  }209  jq_util_input_state *new_state = jv_mem_calloc(1, sizeof(*new_state));210  new_state->err_cb = err_cb;211  new_state->err_cb_data = err_cb_data;212  new_state->slurped = jv_invalid();213  new_state->current_filename = jv_invalid();214215  return new_state;216}217218void jq_util_input_set_parser(jq_util_input_state *state, jv_parser *parser, int slurp) {219  assert(!jv_is_valid(state->slurped));220  state->parser = parser;221222  if (parser == NULL && slurp)223    state->slurped = jv_string("");224  else if (slurp)225    state->slurped = jv_array();226  else227    state->slurped = jv_invalid();228}229230void jq_util_input_free(jq_util_input_state **state) {231  jq_util_input_state *old_state = *state;232  *state = NULL;233  if (old_state == NULL)234    return;235236  if (old_state->parser != NULL)237    jv_parser_free(old_state->parser);238  for (int i = 0; i < old_state->nfiles; i++)239    free(old_state->files[i]);240  free(old_state->files);241  jv_free(old_state->slurped);242  jv_free(old_state->current_filename);243  jv_mem_free(old_state);244}245246void jq_util_input_add_input(jq_util_input_state *state, const char *fname) {247  state->files = jv_mem_realloc(state->files, (state->nfiles + 1) * sizeof(state->files[0]));248  state->files[state->nfiles++] = jv_mem_strdup(fname);249}250251int jq_util_input_errors(jq_util_input_state *state) {252  return state->failures;253}254255static const char *next_file(jq_util_input_state *state) {256  if (state->curr_file < state->nfiles)257    return state->files[state->curr_file++];258  return NULL;259}260261static int jq_util_input_read_more(jq_util_input_state *state) {262  if (!state->current_input || feof(state->current_input) || ferror(state->current_input)) {263    if (state->current_input && ferror(state->current_input)) {264      // System-level input error on the stream. It will be closed (below).265      // TODO: report it. Can't use 'state->err_cb()' as it is hard-coded for266      //       'open' related problems.267      fprintf(stderr,"jq: error: %s\n", strerror(errno));268    }269    if (state->current_input) {270      if (state->current_input == stdin) {271        clearerr(stdin); // perhaps we can read again; anyways, we don't fclose(stdin)272      } else {273        fclose(state->current_input);274      }275      state->current_input = NULL;276    }277    const char *f = next_file(state);278    if (f != NULL) {279      jv_free(state->current_filename);280      state->current_line = 0;281      state->at_file_start = 1;282      if (!strcmp(f, "-")) {283        state->current_input = stdin;284        state->current_filename = jv_string("<stdin>");285      } else {286        state->current_input = fopen(f, "r");287        state->current_filename = jv_string(f);288        if (!state->current_input) {289          state->err_cb(state->err_cb_data, f);290          state->failures++;291        }292      }293    }294  }295296  state->buf[0] = 0;297  state->buf_valid_len = 0;298  if (state->current_input) {299    char *res;300    memset(state->buf, 0xff, sizeof(state->buf));301302    const int max_utf8_len = 4;303    const int max_gets_len = sizeof(state->buf) - max_utf8_len;304    while (!(res = fgets(state->buf, max_gets_len, state->current_input)) &&305           ferror(state->current_input) && errno == EINTR)306      clearerr(state->current_input);307    if (res == NULL) {308      state->buf[0] = 0;309      if (ferror(state->current_input))310        state->failures++;311    } else {312      const char *p = memchr(state->buf, '\n', max_gets_len);313314      if (p != NULL)315        state->current_line++;316317      if (p == NULL && feof(state->current_input)) {318        size_t i;319320        /*321         * XXX We don't know how many bytes we've read!322         *323         * We can't use getline() because there need not be any newlines324         * in the input.  The only entirely correct choices are: use325         * fgetc() or fread().  Using fread() will complicate buffer326         * management here.327         *328         * For now we check how much fgets() read by scanning backwards for the329         * terminating '\0'. This only works because we previously memset our330         * buffer with something nonzero.331         */332        for (i = max_gets_len - 1; i > 0; i--) {333          if (state->buf[i] == '\0')334            break;335        }336        state->buf_valid_len = i;337      } else if (p == NULL) {338        state->buf_valid_len = max_gets_len - 1;339        char *end = state->buf + state->buf_valid_len;340        int len = 0;341        if (jvp_utf8_backtrack(end - 1, state->buf, &len) && len > 0) {342          state->buf_valid_len += fread(end, 1, len, state->current_input);343        }344      } else {345        state->buf_valid_len = (p - state->buf) + 1;346      }347    }348    if (state->at_file_start) {349      // Strip UTF-8 BOM at the start of each file350      if (state->buf_valid_len >= 3 && !memcmp(state->buf, "\xEF\xBB\xBF", 3)) {351        state->buf_valid_len -= 3;352        memmove(state->buf, state->buf + 3, state->buf_valid_len);353      }354      state->at_file_start = 0;355    }356  }357  return state->curr_file == state->nfiles && !state->current_input;358}359360jv jq_util_input_next_input_cb(jq_state *jq, void *data) {361  return jq_util_input_next_input((jq_util_input_state *)data);362}363364// Return the current_filename:current_line365jv jq_util_input_get_position(jq_state *jq) {366  jq_input_cb cb = NULL;367  void *cb_data = NULL;368  jq_get_input_cb(jq, &cb, &cb_data);369  assert(cb == jq_util_input_next_input_cb);370  if (cb != jq_util_input_next_input_cb)371    return jv_invalid_with_msg(jv_string("Invalid jq_util_input API usage"));372  jq_util_input_state *s = (jq_util_input_state *)cb_data;373374  // We can't assert that current_filename is a string because if375  // the error was a JSON parser error then we may not have set376  // current_filename yet.377  if (jv_get_kind(s->current_filename) != JV_KIND_STRING)378    return jv_string("<unknown>");379380  jv v = jv_string_fmt("%s:%lu", jv_string_value(s->current_filename), (unsigned long)s->current_line);381  return v;382}383384jv jq_util_input_get_current_filename(jq_state* jq) {385  jq_input_cb cb=NULL;386  void *cb_data=NULL;387  jq_get_input_cb(jq, &cb, &cb_data);388  if (cb != jq_util_input_next_input_cb)389    return jv_invalid_with_msg(jv_string("Unknown input filename"));390  jq_util_input_state *s = (jq_util_input_state *)cb_data;391  jv v = jv_copy(s->current_filename);392  return v;393}394395jv jq_util_input_get_current_line(jq_state* jq) {396  jq_input_cb cb=NULL;397  void *cb_data=NULL;398  jq_get_input_cb(jq, &cb, &cb_data);399  if (cb != jq_util_input_next_input_cb)400    return jv_invalid_with_msg(jv_string("Unknown input line number"));401  jq_util_input_state *s = (jq_util_input_state *)cb_data;402  jv v = jv_number(s->current_line);403  return v;404}405406407// Blocks to read one more input from stdin and/or given files408// When slurping, it returns just one value409jv jq_util_input_next_input(jq_util_input_state *state) {410  int is_last = 0;411  jv value = jv_invalid(); // need more input412  do {413    if (state->parser == NULL) {414      // Raw input415      is_last = jq_util_input_read_more(state);416      if (state->buf_valid_len == 0)417        continue;418      if (jv_is_valid(state->slurped)) {419        // Slurped raw input420        state->slurped = jv_string_concat(state->slurped, jv_string_sized(state->buf, state->buf_valid_len));421      } else {422        if (!jv_is_valid(value))423          value = jv_string("");424        if (state->buf[state->buf_valid_len-1] == '\n') {425          // whole line426          state->buf[state->buf_valid_len-1] = 0;427          return jv_string_concat(value, jv_string_sized(state->buf, state->buf_valid_len-1));428        }429        value = jv_string_concat(value, jv_string_sized(state->buf, state->buf_valid_len));430        state->buf[0] = '\0';431        state->buf_valid_len = 0;432      }433    } else {434      if (jv_parser_remaining(state->parser) == 0) {435        is_last = jq_util_input_read_more(state);436        jv_parser_set_buf(state->parser, state->buf, state->buf_valid_len, !is_last);437      }438      value = jv_parser_next(state->parser);439      if (jv_is_valid(state->slurped)) {440        if (jv_is_valid(value)) {441          state->slurped = jv_array_append(state->slurped, value);442          value = jv_invalid();443        } else if (jv_invalid_has_msg(jv_copy(value)))444          return value; // Not slurped parsed input445      } else if (jv_is_valid(value) || jv_invalid_has_msg(jv_copy(value))) {446        return value;447      }448    }449  } while (!is_last);450451  if (jv_is_valid(state->slurped)) {452    value = state->slurped;453    state->slurped = jv_invalid();454  }455  return value;456}457458#ifndef HAVE_STRPTIME459/* http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/lib/libc/time/strptime.c?only_with_tag=HEAD460 * NetBSD implementation strptime().461 * Format description: https://netbsd.gw.com/cgi-bin/man-cgi?strptime+3+NetBSD-current462 * Adapted by https://github.com/res2001 (https://github.com/res2001/strptime).463*/464465#include <ctype.h>466#include <string.h>467#include <time.h>468#include <stdint.h>469470static const unsigned char *conv_num(const unsigned char *, int *, unsigned int, unsigned int);471static const unsigned char *find_string(const unsigned char *, int *, const char * const *, const char * const *, int);472473/*474 * We do not implement alternate representations. However, we always475 * check whether a given modifier is allowed for a certain conversion.476 */477#define ALT_E			0x01478#define ALT_O			0x02479#define LEGAL_ALT(x)	{ if (alt_format & ~(x)) return NULL; }480481#define TM_YEAR_BASE	1900482483#define TM_SUNDAY       0484#define TM_MONDAY       1485#define TM_TUESDAY      2486#define TM_WEDNESDAY    3487#define TM_THURSDAY     4488#define TM_FRIDAY       5489#define TM_SATURDAY     6490491#define S_YEAR			(1 << 0)492#define S_MON			(1 << 1)493#define S_YDAY			(1 << 2)494#define S_MDAY			(1 << 3)495#define S_WDAY			(1 << 4)496#define S_HOUR			(1 << 5)497498#define HAVE_MDAY(s)	(s & S_MDAY)499#define HAVE_MON(s)		(s & S_MON)500#define HAVE_WDAY(s)	(s & S_WDAY)501#define HAVE_YDAY(s)	(s & S_YDAY)502#define HAVE_YEAR(s)	(s & S_YEAR)503#define HAVE_HOUR(s)	(s & S_HOUR)504505#define SECSPERMIN      60506#define MINSPERHOUR     60507#define SECSPERHOUR     (SECSPERMIN * MINSPERHOUR)508#define HOURSPERDAY     24509510#define HERE_D_T_FMT    "%a %b %e %H:%M:%S %Y"511#define HERE_D_FMT      "%y/%m/%d"512#define HERE_T_FMT_AMPM "%I:%M:%S %p"513#define HERE_T_FMT      "%H:%M:%S"514515#define isleap(y) (((y) % 4) == 0 && (((y) % 100) != 0 || ((y) % 400) == 0))516517/*518** Since everything in isleap is modulo 400 (or a factor of 400), we know that519**	isleap(y) == isleap(y % 400)520** and so521**	isleap(a + b) == isleap((a + b) % 400)522** or523**	isleap(a + b) == isleap(a % 400 + b % 400)524** This is true even if % means modulo rather than Fortran remainder525** (which is allowed by C89 but not by C99 or later).526** We use this to avoid addition overflow problems.527*/528529#define isleap_sum(a, b)	isleap((a) % 400 + (b) % 400)530531#ifdef _MSC_VER532#define tzname              _tzname533#define strncasecmp         _strnicmp534#endif535536#ifdef TM_ZONE537static char* utc = "UTC";538#endif539/* RFC-822/RFC-2822 */540static const char *const nast[] = {541       "EST",    "CST",    "MST",    "PST",    "\0\0\0"542};543static const char *const nadt[] = {544       "EDT",    "CDT",    "MDT",    "PDT",    "\0\0\0"545};546static const char *const weekday_name[] =547{548    "Sunday", "Monday", "Tuesday", "Wednesday",549    "Thursday", "Friday", "Saturday"550};551static const char *const ab_weekday_name[] =552{553    "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"554};555static const char *const month_name[] =556{557    "January", "February", "March", "April", "May", "June",558    "July", "August", "September", "October", "November", "December"559};560static const char *const ab_month_name[] =561{562    "Jan", "Feb", "Mar", "Apr", "May", "Jun",563    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"564};565static const char *const am_pm[] = {"AM", "PM"};566567568/*569 * Table to determine the ordinal date for the start of a month.570 * Ref: http://en.wikipedia.org/wiki/ISO_week_date571 */572static const int start_of_month[2][13] = {573    /* non-leap year */574    { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },575    /* leap year */576    { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }577};578579/*580 * Calculate the week day of the first day of a year. Valid for581 * the Gregorian calendar, which began Sept 14, 1752 in the UK582 * and its colonies. Ref:583 * http://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week584 */585586static int587first_wday_of(int yr)588{589    return ((2 * (3 - (yr / 100) % 4)) + (yr % 100) + ((yr % 100) /  4) +590        (isleap(yr) ? 6 : 0) + 1) % 7;591}592593#define delim(p)	((p) == '\0' || isspace((unsigned char)(p)))594595static int596fromzone(const unsigned char **bp, struct tm *tm, int mandatory)597{598//    timezone_t tz;599    char buf[512], *p;600    const unsigned char *rp;601602    for (p = buf, rp = *bp; !delim(*rp) && p < &buf[sizeof(buf) - 1]; rp++)603        *p++ = *rp;604    *p = '\0';605606    if (mandatory)607        *bp = rp;608    if (!isalnum((unsigned char)*buf))609        return 0;610//    tz = tzalloc(buf);611//    if (tz == NULL)612//        return 0;613614    *bp = rp;615    tm->tm_isdst = 0;	/* XXX */616#ifdef TM_GMTOFF617    tm->TM_GMTOFF = tzgetgmtoff(tz, tm->tm_isdst);618#endif619#ifdef TM_ZONE620    // Can't use tzgetname() here because we are going to free()621    tm->TM_ZONE = NULL; /* XXX */622#endif623//    tzfree(tz);624    return 1;625}626627char* strptime(const char *buf, const char *fmt, struct tm *tm)628{629    unsigned char c;630    const unsigned char *bp, *ep, *zname;631    int alt_format, i, split_year = 0, neg = 0, state = 0,632        day_offset = -1, week_offset = 0, offs, mandatory;633    const char *new_fmt;634635    bp = (const unsigned char *)buf;636637    while (bp != NULL && (c = *fmt++) != '\0') {638        /* Clear `alternate' modifier prior to new conversion. */639        alt_format = 0;640        i = 0;641642        /* Eat up white-space. */643        if (isspace(c)) {644            while (isspace(*bp))645                bp++;646            continue;647        }648649        if (c != '%')650            goto literal;651652653again:		switch (c = *fmt++) {654        case '%':	/* "%%" is converted to "%". */655literal:656            if (c != *bp++)657                return NULL;658            LEGAL_ALT(0);659            continue;660661        /*662         * "Alternative" modifiers. Just set the appropriate flag663         * and start over again.664         */665        case 'E':	/* "%E?" alternative conversion modifier. */666            LEGAL_ALT(0);667            alt_format |= ALT_E;668            goto again;669670        case 'O':	/* "%O?" alternative conversion modifier. */671            LEGAL_ALT(0);672            alt_format |= ALT_O;673            goto again;674675        /*676         * "Complex" conversion rules, implemented through recursion.677         */678        case 'c':	/* Date and time, using the locale's format. */679//            new_fmt = _TIME_LOCALE(loc)->d_t_fmt;680            new_fmt = HERE_D_T_FMT;681            state |= S_WDAY | S_MON | S_MDAY | S_YEAR;682            goto recurse;683684        case 'F':	/* The date as "%Y-%m-%d". */685            new_fmt = "%Y-%m-%d";686            LEGAL_ALT(0);687            state |= S_MON | S_MDAY | S_YEAR;688            goto recurse;689690        case 'R':	/* The time as "%H:%M". */691            new_fmt = "%H:%M";692            LEGAL_ALT(0);693            goto recurse;694695        case 'r':	/* The time in 12-hour clock representation. */696//            new_fmt = _TIME_LOCALE(loc)->t_fmt_ampm;697            new_fmt = HERE_T_FMT_AMPM;698            LEGAL_ALT(0);699            goto recurse;700701        case 'X':	/* The time, using the locale's format. */702            /* fall through */703704        case 'T':	/* The time as "%H:%M:%S". */705            new_fmt = HERE_T_FMT;706            LEGAL_ALT(0);707708recurse:709            bp = (const unsigned char *)strptime((const char *)bp,710                                new_fmt, tm);711            LEGAL_ALT(ALT_E);712            continue;713714        case 'x':	/* The date, using the locale's format. */715            /* fall through */716717        case 'D':	/* The date as "%y/%m/%d". */718        {719            new_fmt = HERE_D_FMT;720            LEGAL_ALT(0);721            state |= S_MON | S_MDAY | S_YEAR;722            const int year = split_year ? tm->tm_year : 0;723724            bp = (const unsigned char *)strptime((const char *)bp,725                                new_fmt, tm);726            LEGAL_ALT(ALT_E);727            tm->tm_year += year;728            if (split_year && tm->tm_year % (2000 - TM_YEAR_BASE) <= 68)729                tm->tm_year -= 2000 - TM_YEAR_BASE;730            split_year = 1;731            continue;732        }733        /*734         * "Elementary" conversion rules.735         */736        case 'A':	/* The day of week, using the locale's form. */737        case 'a':738            bp = find_string(bp, &tm->tm_wday, weekday_name, ab_weekday_name, 7);739            LEGAL_ALT(0);740            state |= S_WDAY;741            continue;742743        case 'B':	/* The month, using the locale's form. */744        case 'b':745        case 'h':746            bp = find_string(bp, &tm->tm_mon, month_name, ab_month_name, 12);747            LEGAL_ALT(0);748            state |= S_MON;749            continue;750751        case 'C':	/* The century number. */752            i = 20;753            bp = conv_num(bp, &i, 0, 99);754755            i = i * 100 - TM_YEAR_BASE;756            if (split_year)757                i += tm->tm_year % 100;758            split_year = 1;759            tm->tm_year = i;760            LEGAL_ALT(ALT_E);761            state |= S_YEAR;762            continue;763764        case 'd':	/* The day of month. */765        case 'e':766            bp = conv_num(bp, &tm->tm_mday, 1, 31);767            LEGAL_ALT(ALT_O);768            state |= S_MDAY;769            continue;770771        case 'k':	/* The hour (24-hour clock representation). */772            LEGAL_ALT(0);773            /* FALLTHROUGH */774        case 'H':775            bp = conv_num(bp, &tm->tm_hour, 0, 23);776            LEGAL_ALT(ALT_O);777            state |= S_HOUR;778            continue;779780        case 'l':	/* The hour (12-hour clock representation). */781            LEGAL_ALT(0);782            /* FALLTHROUGH */783        case 'I':784            bp = conv_num(bp, &tm->tm_hour, 1, 12);785            if (tm->tm_hour == 12)786                tm->tm_hour = 0;787            LEGAL_ALT(ALT_O);788            state |= S_HOUR;789            continue;790791        case 'j':	/* The day of year. */792            i = 1;793            bp = conv_num(bp, &i, 1, 366);794            tm->tm_yday = i - 1;795            LEGAL_ALT(0);796            state |= S_YDAY;797            continue;798799        case 'M':	/* The minute. */800            bp = conv_num(bp, &tm->tm_min, 0, 59);801            LEGAL_ALT(ALT_O);802            continue;803804        case 'm':	/* The month. */805            i = 1;806            bp = conv_num(bp, &i, 1, 12);807            tm->tm_mon = i - 1;808            LEGAL_ALT(ALT_O);809            state |= S_MON;810            continue;811812        case 'p':	/* The locale's equivalent of AM/PM. */813            bp = find_string(bp, &i, am_pm, NULL, 2);814            if (HAVE_HOUR(state) && tm->tm_hour > 11)815                return NULL;816            tm->tm_hour += i * 12;817            LEGAL_ALT(0);818            continue;819820        case 'S':	/* The seconds. */821            bp = conv_num(bp, &tm->tm_sec, 0, 61);822            LEGAL_ALT(ALT_O);823            continue;824825        case 's': {     /* seconds since the epoch */826#ifdef _WIN32827            const time_t TIME_MAX = INT32_MAX;828#else829            const time_t TIME_MAX = INT64_MAX;830#endif831            time_t sse, d;832833            if (*bp < '0' || *bp > '9') {834                bp = NULL;835                continue;836            }837838            sse = *bp++ - '0';839            while (*bp >= '0' && *bp <= '9') {840                d = *bp++ - '0';841                if (sse > TIME_MAX/10) {842                    bp = NULL;843                    break;844                }845                sse *= 10;846                if (sse > TIME_MAX - d) {847                    bp = NULL;848                    break;849                }850                sse += d;851            }852            if (bp == NULL)853                continue;854855#ifdef _WIN32856            if (localtime_s(tm, &sse))857#else858            if (localtime_r(&sse, tm) == NULL)859#endif860                bp = NULL;861            else862                state |= S_YDAY | S_WDAY | S_MON | S_MDAY | S_YEAR;863            continue;864            }865866        case 'U':	/* The week of year, beginning on sunday. */867        case 'W':	/* The week of year, beginning on monday. */868            /*869             * This is bogus, as we can not assume any valid870             * information present in the tm structure at this871             * point to calculate a real value, so save the872             * week for now in case it can be used later.873             */874            bp = conv_num(bp, &i, 0, 53);875            LEGAL_ALT(ALT_O);876            if (c == 'U')877                day_offset = TM_SUNDAY;878            else879                day_offset = TM_MONDAY;880            week_offset = i;881            continue;882883        case 'w':	/* The day of week, beginning on sunday. */884            bp = conv_num(bp, &tm->tm_wday, 0, 6);885            LEGAL_ALT(ALT_O);886            state |= S_WDAY;887            continue;888889        case 'u':	/* The day of week, monday = 1. */890            bp = conv_num(bp, &i, 1, 7);891            tm->tm_wday = i % 7;892            LEGAL_ALT(ALT_O);893            state |= S_WDAY;894            continue;895896        case 'g':	/* The year corresponding to the ISO week897                 * number but without the century.898                 */899            bp = conv_num(bp, &i, 0, 99);900            continue;901902        case 'G':	/* The year corresponding to the ISO week903                 * number with century.904                 */905            do906                bp++;907            while (isdigit(*bp));908            continue;909910        case 'V':	/* The ISO 8601:1988 week number as decimal */911            bp = conv_num(bp, &i, 0, 53);912            continue;913914        case 'Y':	/* The year. */915            i = TM_YEAR_BASE;	/* just for data sanity... */916            bp = conv_num(bp, &i, 0, 9999);917            tm->tm_year = i - TM_YEAR_BASE;918            LEGAL_ALT(ALT_E);919            state |= S_YEAR;920            continue;921922        case 'y':	/* The year within 100 years of the epoch. */923            /* LEGAL_ALT(ALT_E | ALT_O); */924            bp = conv_num(bp, &i, 0, 99);925926            if (split_year)927                /* preserve century */928                i += (tm->tm_year / 100) * 100;929            else {930                split_year = 1;931                if (i <= 68)932                    i = i + 2000 - TM_YEAR_BASE;933            }934            tm->tm_year = i;935            state |= S_YEAR;936            continue;937938        case 'Z':       // time zone name939        case 'z':       //940#ifdef _WIN32941            _tzset();942#else943            tzset();944#endif945            mandatory = c == 'z';946            /*947             * We recognize all ISO 8601 formats:948             * Z	= Zulu time/UTC949             * [+-]hhmm950             * [+-]hh:mm951             * [+-]hh952             * We recognize all RFC-822/RFC-2822 formats:953             * UT|GMT954             *          North American : UTC offsets955             * E[DS]T = Eastern : -4 | -5956             * C[DS]T = Central : -5 | -6957             * M[DS]T = Mountain: -6 | -7958             * P[DS]T = Pacific : -7 | -8959             *          Nautical/Military960             * [A-IL-M] = -1 ... -9 (J not used)961             * [N-Y]  = +1 ... +12962             * Note: J maybe used to denote non-nautical963             *       local time964             */965            if (mandatory)966                while (isspace(*bp))967                    bp++;968969            zname = bp;970            switch (*bp++) {971            case 'G':972                if (*bp++ != 'M')973                    goto namedzone;974                /*FALLTHROUGH*/975            case 'U':976                if (*bp++ != 'T')977                    goto namedzone;978                else if (!delim(*bp) && *bp++ != 'C')979                    goto namedzone;980                /*FALLTHROUGH*/981            case 'Z':982                if (!delim(*bp))983                    goto namedzone;984                tm->tm_isdst = 0;985#ifdef TM_GMTOFF986                tm->TM_GMTOFF = 0;987#endif988#ifdef TM_ZONE989                tm->TM_ZONE = utc;990#endif991                continue;992            case '+':993                neg = 0;994                break;995            case '-':996                neg = 1;997                break;998            default:999namedzone:1000                bp = zname;10011002                /* Nautical / Military style */1003                if (delim(bp[1]) &&1004                    ((*bp >= 'A' && *bp <= 'I') ||1005                     (*bp >= 'L' && *bp <= 'Y'))) {1006#ifdef TM_GMTOFF1007                    /* Argh! No 'J'! */1008                    if (*bp >= 'A' && *bp <= 'I')1009                        tm->TM_GMTOFF =1010                            (int)*bp - ('A' - 1);1011                    else if (*bp >= 'L' && *bp <= 'M')1012                        tm->TM_GMTOFF = (int)*bp - 'A';1013                    else if (*bp >= 'N' && *bp <= 'Y')1014                        tm->TM_GMTOFF = 'M' - (int)*bp;1015                    tm->TM_GMTOFF *= SECSPERHOUR;1016#endif1017#ifdef TM_ZONE1018                    tm->TM_ZONE = NULL; /* XXX */1019#endif1020                    bp++;1021                    continue;1022                }1023                /* 'J' is local time */1024                if (delim(bp[1]) && *bp == 'J') {1025#ifdef TM_GMTOFF1026                    tm->TM_GMTOFF = -timezone;1027#endif1028#ifdef TM_ZONE1029                    tm->TM_ZONE = NULL; /* XXX */1030#endif1031                    bp++;1032                    continue;1033                }10341035                /*1036                 * From our 3 letter hard-coded table1037                 * XXX: Can be removed, handled by tzload()1038                 */1039                if (delim(bp[0]) || delim(bp[1]) ||1040                    delim(bp[2]) || !delim(bp[3]))1041                    goto loadzone;1042                ep = find_string(bp, &i, nast, NULL, 4);1043                if (ep != NULL) {1044#ifdef TM_GMTOFF1045                    tm->TM_GMTOFF = (-5 - i) * SECSPERHOUR;1046#endif1047#ifdef TM_ZONE1048                    tm->TM_ZONE = __UNCONST(nast[i]);1049#endif1050                    bp = ep;1051                    continue;1052                }1053                ep = find_string(bp, &i, nadt, NULL, 4);1054                if (ep != NULL) {1055                    tm->tm_isdst = 1;1056#ifdef TM_GMTOFF1057                    tm->TM_GMTOFF = (-4 - i) * SECSPERHOUR;1058#endif1059#ifdef TM_ZONE1060                    tm->TM_ZONE = __UNCONST(nadt[i]);1061#endif1062                    bp = ep;1063                    continue;1064                }1065                /*1066                 * Our current timezone1067                 */1068                ep = find_string(bp, &i,1069                             (const char * const *)tzname,1070                              NULL, 2);1071                if (ep != NULL) {1072                    tm->tm_isdst = i;1073#ifdef TM_GMTOFF1074                    tm->TM_GMTOFF = -timezone;1075#endif1076#ifdef TM_ZONE1077                    tm->TM_ZONE = tzname[i];1078#endif1079                    bp = ep;1080                    continue;1081                }1082loadzone:1083                /*1084                 * The hard way, load the zone!1085                 */1086                if (fromzone(&bp, tm, mandatory))1087                    continue;1088                goto out;1089            }1090            offs = 0;1091            for (i = 0; i < 4; ) {1092                if (isdigit(*bp)) {1093                    offs = offs * 10 + (*bp++ - '0');1094                    i++;1095                    continue;1096                }1097                if (i == 2 && *bp == ':') {1098                    bp++;1099                    continue;1100                }1101                break;1102            }1103            if (isdigit(*bp))1104                goto out;1105            switch (i) {1106            case 2:1107                offs *= SECSPERHOUR;1108                break;1109            case 4:1110                i = offs % 100;1111                offs /= 100;1112                if (i >= SECSPERMIN)1113                    goto out;1114                /* Convert minutes into decimal */1115                offs = offs * SECSPERHOUR + i * SECSPERMIN;1116                break;1117            default:1118out:1119                if (mandatory)1120                    return NULL;1121                bp = zname;1122                continue;1123            }1124            /* ISO 8601 & RFC 3339 limit to 23:59 max */1125            if (offs >= (HOURSPERDAY * SECSPERHOUR))1126                goto out;1127            if (neg)1128                offs = -offs;1129            tm->tm_isdst = 0;	/* XXX */1130#ifdef TM_GMTOFF1131            tm->TM_GMTOFF = offs;1132#endif1133#ifdef TM_ZONE1134            tm->TM_ZONE = NULL;	/* XXX */1135#endif1136            continue;11371138        /*1139         * Miscellaneous conversions.1140         */1141        case 'n':	/* Any kind of white-space. */1142        case 't':1143            while (isspace(*bp))1144                bp++;1145            LEGAL_ALT(0);1146            continue;114711481149        default:	/* Unknown/unsupported conversion. */1150            return NULL;1151        }1152    }11531154    if (!HAVE_YDAY(state) && HAVE_YEAR(state)) {1155        if (HAVE_MON(state) && HAVE_MDAY(state)) {1156            /* calculate day of year (ordinal date) */1157            tm->tm_yday =  start_of_month[isleap_sum(tm->tm_year,1158                TM_YEAR_BASE)][tm->tm_mon] + (tm->tm_mday - 1);1159            state |= S_YDAY;1160        } else if (day_offset != -1) {1161            /*1162             * Set the date to the first Sunday (or Monday)1163             * of the specified week of the year.1164             */1165            if (!HAVE_WDAY(state)) {1166                tm->tm_wday = day_offset;1167                state |= S_WDAY;1168            }1169            tm->tm_yday = (7 -1170                first_wday_of(tm->tm_year + TM_YEAR_BASE) +1171                day_offset) % 7 + (week_offset - 1) * 7 +1172                tm->tm_wday  - day_offset;1173            state |= S_YDAY;1174        }1175    }11761177    if (HAVE_YDAY(state) && HAVE_YEAR(state)) {1178        int isleap;11791180        if (!HAVE_MON(state)) {1181            /* calculate month of day of year */1182            i = 0;1183            isleap = isleap_sum(tm->tm_year, TM_YEAR_BASE);1184            while (tm->tm_yday >= start_of_month[isleap][i])1185                i++;1186            if (i > 12) {1187                i = 1;1188                tm->tm_yday -= start_of_month[isleap][12];1189                tm->tm_year++;1190            }1191            tm->tm_mon = i - 1;1192            state |= S_MON;1193        }11941195        if (!HAVE_MDAY(state)) {1196            /* calculate day of month */1197            isleap = isleap_sum(tm->tm_year, TM_YEAR_BASE);1198            tm->tm_mday = tm->tm_yday -1199                start_of_month[isleap][tm->tm_mon] + 1;1200            state |= S_MDAY;1201        }12021203        if (!HAVE_WDAY(state)) {1204            /* calculate day of week */1205            i = 0;1206            week_offset = first_wday_of(tm->tm_year);1207            while (i++ <= tm->tm_yday) {1208                if (week_offset++ >= 6)1209                    week_offset = 0;1210            }1211            tm->tm_wday = week_offset;1212            state |= S_WDAY;1213        }1214    }12151216    return (char*)bp;1217}121812191220static const unsigned char *1221conv_num(const unsigned char *buf, int *dest, unsigned int llim, unsigned int ulim)1222{1223    unsigned int result = 0;1224    unsigned char ch;12251226    /* The limit also determines the number of valid digits. */1227    unsigned int rulim = ulim;12281229    ch = *buf;1230    if (ch < '0' || ch > '9')1231        return NULL;12321233    do {1234        result *= 10;1235        result += ch - '0';1236        rulim /= 10;1237        ch = *++buf;1238    } while ((result <= ulim) && rulim && ch >= '0' && ch <= '9');12391240    if (result < llim || result > ulim)1241        return NULL;12421243    *dest = result;1244    return buf;1245}12461247static const unsigned char *1248find_string(const unsigned char *bp, int *tgt, const char * const *n1,1249        const char * const *n2, int c)1250{1251    int i;1252    size_t len;12531254    /* check full name - then abbreviated ones */1255    for (; n1 != NULL; n1 = n2, n2 = NULL) {1256        for (i = 0; i < c; i++, n1++) {1257            len = strlen(*n1);1258            if (strncasecmp(*n1, (const char *)bp, len) == 0) {1259                *tgt = i;1260                return bp + len;1261            }1262        }1263    }12641265    /* Nothing matched */1266    return NULL;1267}1268#endif