date.con commit date: recognize bogus FreeBSD gmtime output (6654754)
   1/*
   2 * GIT - The information manager from hell
   3 *
   4 * Copyright (C) Linus Torvalds, 2005
   5 */
   6
   7#include "cache.h"
   8
   9/*
  10 * This is like mktime, but without normalization of tm_wday and tm_yday.
  11 */
  12static time_t tm_to_time_t(const struct tm *tm)
  13{
  14        static const int mdays[] = {
  15            0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
  16        };
  17        int year = tm->tm_year - 70;
  18        int month = tm->tm_mon;
  19        int day = tm->tm_mday;
  20
  21        if (year < 0 || year > 129) /* algo only works for 1970-2099 */
  22                return -1;
  23        if (month < 0 || month > 11) /* array bounds */
  24                return -1;
  25        if (month < 2 || (year + 2) % 4)
  26                day--;
  27        if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_sec < 0)
  28                return -1;
  29        return (year * 365 + (year + 1) / 4 + mdays[month] + day) * 24*60*60UL +
  30                tm->tm_hour * 60*60 + tm->tm_min * 60 + tm->tm_sec;
  31}
  32
  33static const char *month_names[] = {
  34        "January", "February", "March", "April", "May", "June",
  35        "July", "August", "September", "October", "November", "December"
  36};
  37
  38static const char *weekday_names[] = {
  39        "Sundays", "Mondays", "Tuesdays", "Wednesdays", "Thursdays", "Fridays", "Saturdays"
  40};
  41
  42static time_t gm_time_t(unsigned long time, int tz)
  43{
  44        int minutes;
  45
  46        minutes = tz < 0 ? -tz : tz;
  47        minutes = (minutes / 100)*60 + (minutes % 100);
  48        minutes = tz < 0 ? -minutes : minutes;
  49        return time + minutes * 60;
  50}
  51
  52/*
  53 * The "tz" thing is passed in as this strange "decimal parse of tz"
  54 * thing, which means that tz -0100 is passed in as the integer -100,
  55 * even though it means "sixty minutes off"
  56 */
  57static struct tm *time_to_tm(unsigned long time, int tz)
  58{
  59        time_t t = gm_time_t(time, tz);
  60        return gmtime(&t);
  61}
  62
  63/*
  64 * What value of "tz" was in effect back then at "time" in the
  65 * local timezone?
  66 */
  67static int local_tzoffset(unsigned long time)
  68{
  69        time_t t, t_local;
  70        struct tm tm;
  71        int offset, eastwest;
  72
  73        t = time;
  74        localtime_r(&t, &tm);
  75        t_local = tm_to_time_t(&tm);
  76
  77        if (t_local < t) {
  78                eastwest = -1;
  79                offset = t - t_local;
  80        } else {
  81                eastwest = 1;
  82                offset = t_local - t;
  83        }
  84        offset /= 60; /* in minutes */
  85        offset = (offset % 60) + ((offset / 60) * 100);
  86        return offset * eastwest;
  87}
  88
  89void show_date_relative(unsigned long time, int tz,
  90                               const struct timeval *now,
  91                               struct strbuf *timebuf)
  92{
  93        unsigned long diff;
  94        if (now->tv_sec < time) {
  95                strbuf_addstr(timebuf, _("in the future"));
  96                return;
  97        }
  98        diff = now->tv_sec - time;
  99        if (diff < 90) {
 100                strbuf_addf(timebuf,
 101                         Q_("%lu second ago", "%lu seconds ago", diff), diff);
 102                return;
 103        }
 104        /* Turn it into minutes */
 105        diff = (diff + 30) / 60;
 106        if (diff < 90) {
 107                strbuf_addf(timebuf,
 108                         Q_("%lu minute ago", "%lu minutes ago", diff), diff);
 109                return;
 110        }
 111        /* Turn it into hours */
 112        diff = (diff + 30) / 60;
 113        if (diff < 36) {
 114                strbuf_addf(timebuf,
 115                         Q_("%lu hour ago", "%lu hours ago", diff), diff);
 116                return;
 117        }
 118        /* We deal with number of days from here on */
 119        diff = (diff + 12) / 24;
 120        if (diff < 14) {
 121                strbuf_addf(timebuf,
 122                         Q_("%lu day ago", "%lu days ago", diff), diff);
 123                return;
 124        }
 125        /* Say weeks for the past 10 weeks or so */
 126        if (diff < 70) {
 127                strbuf_addf(timebuf,
 128                         Q_("%lu week ago", "%lu weeks ago", (diff + 3) / 7),
 129                         (diff + 3) / 7);
 130                return;
 131        }
 132        /* Say months for the past 12 months or so */
 133        if (diff < 365) {
 134                strbuf_addf(timebuf,
 135                         Q_("%lu month ago", "%lu months ago", (diff + 15) / 30),
 136                         (diff + 15) / 30);
 137                return;
 138        }
 139        /* Give years and months for 5 years or so */
 140        if (diff < 1825) {
 141                unsigned long totalmonths = (diff * 12 * 2 + 365) / (365 * 2);
 142                unsigned long years = totalmonths / 12;
 143                unsigned long months = totalmonths % 12;
 144                if (months) {
 145                        struct strbuf sb = STRBUF_INIT;
 146                        strbuf_addf(&sb, Q_("%lu year", "%lu years", years), years);
 147                        /* TRANSLATORS: "%s" is "<n> years" */
 148                        strbuf_addf(timebuf,
 149                                 Q_("%s, %lu month ago", "%s, %lu months ago", months),
 150                                 sb.buf, months);
 151                        strbuf_release(&sb);
 152                } else
 153                        strbuf_addf(timebuf,
 154                                 Q_("%lu year ago", "%lu years ago", years), years);
 155                return;
 156        }
 157        /* Otherwise, just years. Centuries is probably overkill. */
 158        strbuf_addf(timebuf,
 159                 Q_("%lu year ago", "%lu years ago", (diff + 183) / 365),
 160                 (diff + 183) / 365);
 161}
 162
 163const char *show_date(unsigned long time, int tz, enum date_mode mode)
 164{
 165        struct tm *tm;
 166        static struct strbuf timebuf = STRBUF_INIT;
 167
 168        if (mode == DATE_RAW) {
 169                strbuf_reset(&timebuf);
 170                strbuf_addf(&timebuf, "%lu %+05d", time, tz);
 171                return timebuf.buf;
 172        }
 173
 174        if (mode == DATE_RELATIVE) {
 175                struct timeval now;
 176
 177                strbuf_reset(&timebuf);
 178                gettimeofday(&now, NULL);
 179                show_date_relative(time, tz, &now, &timebuf);
 180                return timebuf.buf;
 181        }
 182
 183        if (mode == DATE_LOCAL)
 184                tz = local_tzoffset(time);
 185
 186        tm = time_to_tm(time, tz);
 187        if (!tm) {
 188                tm = time_to_tm(0, 0);
 189                tz = 0;
 190        }
 191
 192        strbuf_reset(&timebuf);
 193        if (mode == DATE_SHORT)
 194                strbuf_addf(&timebuf, "%04d-%02d-%02d", tm->tm_year + 1900,
 195                                tm->tm_mon + 1, tm->tm_mday);
 196        else if (mode == DATE_ISO8601)
 197                strbuf_addf(&timebuf, "%04d-%02d-%02d %02d:%02d:%02d %+05d",
 198                                tm->tm_year + 1900,
 199                                tm->tm_mon + 1,
 200                                tm->tm_mday,
 201                                tm->tm_hour, tm->tm_min, tm->tm_sec,
 202                                tz);
 203        else if (mode == DATE_RFC2822)
 204                strbuf_addf(&timebuf, "%.3s, %d %.3s %d %02d:%02d:%02d %+05d",
 205                        weekday_names[tm->tm_wday], tm->tm_mday,
 206                        month_names[tm->tm_mon], tm->tm_year + 1900,
 207                        tm->tm_hour, tm->tm_min, tm->tm_sec, tz);
 208        else
 209                strbuf_addf(&timebuf, "%.3s %.3s %d %02d:%02d:%02d %d%c%+05d",
 210                                weekday_names[tm->tm_wday],
 211                                month_names[tm->tm_mon],
 212                                tm->tm_mday,
 213                                tm->tm_hour, tm->tm_min, tm->tm_sec,
 214                                tm->tm_year + 1900,
 215                                (mode == DATE_LOCAL) ? 0 : ' ',
 216                                tz);
 217        return timebuf.buf;
 218}
 219
 220/*
 221 * Check these. And note how it doesn't do the summer-time conversion.
 222 *
 223 * In my world, it's always summer, and things are probably a bit off
 224 * in other ways too.
 225 */
 226static const struct {
 227        const char *name;
 228        int offset;
 229        int dst;
 230} timezone_names[] = {
 231        { "IDLW", -12, 0, },    /* International Date Line West */
 232        { "NT",   -11, 0, },    /* Nome */
 233        { "CAT",  -10, 0, },    /* Central Alaska */
 234        { "HST",  -10, 0, },    /* Hawaii Standard */
 235        { "HDT",  -10, 1, },    /* Hawaii Daylight */
 236        { "YST",   -9, 0, },    /* Yukon Standard */
 237        { "YDT",   -9, 1, },    /* Yukon Daylight */
 238        { "PST",   -8, 0, },    /* Pacific Standard */
 239        { "PDT",   -8, 1, },    /* Pacific Daylight */
 240        { "MST",   -7, 0, },    /* Mountain Standard */
 241        { "MDT",   -7, 1, },    /* Mountain Daylight */
 242        { "CST",   -6, 0, },    /* Central Standard */
 243        { "CDT",   -6, 1, },    /* Central Daylight */
 244        { "EST",   -5, 0, },    /* Eastern Standard */
 245        { "EDT",   -5, 1, },    /* Eastern Daylight */
 246        { "AST",   -3, 0, },    /* Atlantic Standard */
 247        { "ADT",   -3, 1, },    /* Atlantic Daylight */
 248        { "WAT",   -1, 0, },    /* West Africa */
 249
 250        { "GMT",    0, 0, },    /* Greenwich Mean */
 251        { "UTC",    0, 0, },    /* Universal (Coordinated) */
 252        { "Z",      0, 0, },    /* Zulu, alias for UTC */
 253
 254        { "WET",    0, 0, },    /* Western European */
 255        { "BST",    0, 1, },    /* British Summer */
 256        { "CET",   +1, 0, },    /* Central European */
 257        { "MET",   +1, 0, },    /* Middle European */
 258        { "MEWT",  +1, 0, },    /* Middle European Winter */
 259        { "MEST",  +1, 1, },    /* Middle European Summer */
 260        { "CEST",  +1, 1, },    /* Central European Summer */
 261        { "MESZ",  +1, 1, },    /* Middle European Summer */
 262        { "FWT",   +1, 0, },    /* French Winter */
 263        { "FST",   +1, 1, },    /* French Summer */
 264        { "EET",   +2, 0, },    /* Eastern Europe, USSR Zone 1 */
 265        { "EEST",  +2, 1, },    /* Eastern European Daylight */
 266        { "WAST",  +7, 0, },    /* West Australian Standard */
 267        { "WADT",  +7, 1, },    /* West Australian Daylight */
 268        { "CCT",   +8, 0, },    /* China Coast, USSR Zone 7 */
 269        { "JST",   +9, 0, },    /* Japan Standard, USSR Zone 8 */
 270        { "EAST", +10, 0, },    /* Eastern Australian Standard */
 271        { "EADT", +10, 1, },    /* Eastern Australian Daylight */
 272        { "GST",  +10, 0, },    /* Guam Standard, USSR Zone 9 */
 273        { "NZT",  +12, 0, },    /* New Zealand */
 274        { "NZST", +12, 0, },    /* New Zealand Standard */
 275        { "NZDT", +12, 1, },    /* New Zealand Daylight */
 276        { "IDLE", +12, 0, },    /* International Date Line East */
 277};
 278
 279static int match_string(const char *date, const char *str)
 280{
 281        int i = 0;
 282
 283        for (i = 0; *date; date++, str++, i++) {
 284                if (*date == *str)
 285                        continue;
 286                if (toupper(*date) == toupper(*str))
 287                        continue;
 288                if (!isalnum(*date))
 289                        break;
 290                return 0;
 291        }
 292        return i;
 293}
 294
 295static int skip_alpha(const char *date)
 296{
 297        int i = 0;
 298        do {
 299                i++;
 300        } while (isalpha(date[i]));
 301        return i;
 302}
 303
 304/*
 305* Parse month, weekday, or timezone name
 306*/
 307static int match_alpha(const char *date, struct tm *tm, int *offset)
 308{
 309        int i;
 310
 311        for (i = 0; i < 12; i++) {
 312                int match = match_string(date, month_names[i]);
 313                if (match >= 3) {
 314                        tm->tm_mon = i;
 315                        return match;
 316                }
 317        }
 318
 319        for (i = 0; i < 7; i++) {
 320                int match = match_string(date, weekday_names[i]);
 321                if (match >= 3) {
 322                        tm->tm_wday = i;
 323                        return match;
 324                }
 325        }
 326
 327        for (i = 0; i < ARRAY_SIZE(timezone_names); i++) {
 328                int match = match_string(date, timezone_names[i].name);
 329                if (match >= 3 || match == strlen(timezone_names[i].name)) {
 330                        int off = timezone_names[i].offset;
 331
 332                        /* This is bogus, but we like summer */
 333                        off += timezone_names[i].dst;
 334
 335                        /* Only use the tz name offset if we don't have anything better */
 336                        if (*offset == -1)
 337                                *offset = 60*off;
 338
 339                        return match;
 340                }
 341        }
 342
 343        if (match_string(date, "PM") == 2) {
 344                tm->tm_hour = (tm->tm_hour % 12) + 12;
 345                return 2;
 346        }
 347
 348        if (match_string(date, "AM") == 2) {
 349                tm->tm_hour = (tm->tm_hour % 12) + 0;
 350                return 2;
 351        }
 352
 353        /* BAD CRAP */
 354        return skip_alpha(date);
 355}
 356
 357static int is_date(int year, int month, int day, struct tm *now_tm, time_t now, struct tm *tm)
 358{
 359        if (month > 0 && month < 13 && day > 0 && day < 32) {
 360                struct tm check = *tm;
 361                struct tm *r = (now_tm ? &check : tm);
 362                time_t specified;
 363
 364                r->tm_mon = month - 1;
 365                r->tm_mday = day;
 366                if (year == -1) {
 367                        if (!now_tm)
 368                                return 1;
 369                        r->tm_year = now_tm->tm_year;
 370                }
 371                else if (year >= 1970 && year < 2100)
 372                        r->tm_year = year - 1900;
 373                else if (year > 70 && year < 100)
 374                        r->tm_year = year;
 375                else if (year < 38)
 376                        r->tm_year = year + 100;
 377                else
 378                        return 0;
 379                if (!now_tm)
 380                        return 1;
 381
 382                specified = tm_to_time_t(r);
 383
 384                /* Be it commit time or author time, it does not make
 385                 * sense to specify timestamp way into the future.  Make
 386                 * sure it is not later than ten days from now...
 387                 */
 388                if (now + 10*24*3600 < specified)
 389                        return 0;
 390                tm->tm_mon = r->tm_mon;
 391                tm->tm_mday = r->tm_mday;
 392                if (year != -1)
 393                        tm->tm_year = r->tm_year;
 394                return 1;
 395        }
 396        return 0;
 397}
 398
 399static int match_multi_number(unsigned long num, char c, const char *date, char *end, struct tm *tm)
 400{
 401        time_t now;
 402        struct tm now_tm;
 403        struct tm *refuse_future;
 404        long num2, num3;
 405
 406        num2 = strtol(end+1, &end, 10);
 407        num3 = -1;
 408        if (*end == c && isdigit(end[1]))
 409                num3 = strtol(end+1, &end, 10);
 410
 411        /* Time? Date? */
 412        switch (c) {
 413        case ':':
 414                if (num3 < 0)
 415                        num3 = 0;
 416                if (num < 25 && num2 >= 0 && num2 < 60 && num3 >= 0 && num3 <= 60) {
 417                        tm->tm_hour = num;
 418                        tm->tm_min = num2;
 419                        tm->tm_sec = num3;
 420                        break;
 421                }
 422                return 0;
 423
 424        case '-':
 425        case '/':
 426        case '.':
 427                now = time(NULL);
 428                refuse_future = NULL;
 429                if (gmtime_r(&now, &now_tm))
 430                        refuse_future = &now_tm;
 431
 432                if (num > 70) {
 433                        /* yyyy-mm-dd? */
 434                        if (is_date(num, num2, num3, refuse_future, now, tm))
 435                                break;
 436                        /* yyyy-dd-mm? */
 437                        if (is_date(num, num3, num2, refuse_future, now, tm))
 438                                break;
 439                }
 440                /* Our eastern European friends say dd.mm.yy[yy]
 441                 * is the norm there, so giving precedence to
 442                 * mm/dd/yy[yy] form only when separator is not '.'
 443                 */
 444                if (c != '.' &&
 445                    is_date(num3, num, num2, refuse_future, now, tm))
 446                        break;
 447                /* European dd.mm.yy[yy] or funny US dd/mm/yy[yy] */
 448                if (is_date(num3, num2, num, refuse_future, now, tm))
 449                        break;
 450                /* Funny European mm.dd.yy */
 451                if (c == '.' &&
 452                    is_date(num3, num, num2, refuse_future, now, tm))
 453                        break;
 454                return 0;
 455        }
 456        return end - date;
 457}
 458
 459/*
 460 * Have we filled in any part of the time/date yet?
 461 * We just do a binary 'and' to see if the sign bit
 462 * is set in all the values.
 463 */
 464static inline int nodate(struct tm *tm)
 465{
 466        return (tm->tm_year &
 467                tm->tm_mon &
 468                tm->tm_mday &
 469                tm->tm_hour &
 470                tm->tm_min &
 471                tm->tm_sec) < 0;
 472}
 473
 474/*
 475 * We've seen a digit. Time? Year? Date?
 476 */
 477static int match_digit(const char *date, struct tm *tm, int *offset, int *tm_gmt)
 478{
 479        int n;
 480        char *end;
 481        unsigned long num;
 482
 483        num = strtoul(date, &end, 10);
 484
 485        /*
 486         * Seconds since 1970? We trigger on that for any numbers with
 487         * more than 8 digits. This is because we don't want to rule out
 488         * numbers like 20070606 as a YYYYMMDD date.
 489         */
 490        if (num >= 100000000 && nodate(tm)) {
 491                time_t time = num;
 492                if (gmtime_r(&time, tm)) {
 493                        *tm_gmt = 1;
 494                        return end - date;
 495                }
 496        }
 497
 498        /*
 499         * Check for special formats: num[-.:/]num[same]num
 500         */
 501        switch (*end) {
 502        case ':':
 503        case '.':
 504        case '/':
 505        case '-':
 506                if (isdigit(end[1])) {
 507                        int match = match_multi_number(num, *end, date, end, tm);
 508                        if (match)
 509                                return match;
 510                }
 511        }
 512
 513        /*
 514         * None of the special formats? Try to guess what
 515         * the number meant. We use the number of digits
 516         * to make a more educated guess..
 517         */
 518        n = 0;
 519        do {
 520                n++;
 521        } while (isdigit(date[n]));
 522
 523        /* Four-digit year or a timezone? */
 524        if (n == 4) {
 525                if (num <= 1400 && *offset == -1) {
 526                        unsigned int minutes = num % 100;
 527                        unsigned int hours = num / 100;
 528                        *offset = hours*60 + minutes;
 529                } else if (num > 1900 && num < 2100)
 530                        tm->tm_year = num - 1900;
 531                return n;
 532        }
 533
 534        /*
 535         * Ignore lots of numerals. We took care of 4-digit years above.
 536         * Days or months must be one or two digits.
 537         */
 538        if (n > 2)
 539                return n;
 540
 541        /*
 542         * NOTE! We will give precedence to day-of-month over month or
 543         * year numbers in the 1-12 range. So 05 is always "mday 5",
 544         * unless we already have a mday..
 545         *
 546         * IOW, 01 Apr 05 parses as "April 1st, 2005".
 547         */
 548        if (num > 0 && num < 32 && tm->tm_mday < 0) {
 549                tm->tm_mday = num;
 550                return n;
 551        }
 552
 553        /* Two-digit year? */
 554        if (n == 2 && tm->tm_year < 0) {
 555                if (num < 10 && tm->tm_mday >= 0) {
 556                        tm->tm_year = num + 100;
 557                        return n;
 558                }
 559                if (num >= 70) {
 560                        tm->tm_year = num;
 561                        return n;
 562                }
 563        }
 564
 565        if (num > 0 && num < 13 && tm->tm_mon < 0)
 566                tm->tm_mon = num-1;
 567
 568        return n;
 569}
 570
 571static int match_tz(const char *date, int *offp)
 572{
 573        char *end;
 574        int hour = strtoul(date + 1, &end, 10);
 575        int n = end - (date + 1);
 576        int min = 0;
 577
 578        if (n == 4) {
 579                /* hhmm */
 580                min = hour % 100;
 581                hour = hour / 100;
 582        } else if (n != 2) {
 583                min = 99; /* random crap */
 584        } else if (*end == ':') {
 585                /* hh:mm? */
 586                min = strtoul(end + 1, &end, 10);
 587                if (end - (date + 1) != 5)
 588                        min = 99; /* random crap */
 589        } /* otherwise we parsed "hh" */
 590
 591        /*
 592         * Don't accept any random crap. Even though some places have
 593         * offset larger than 12 hours (e.g. Pacific/Kiritimati is at
 594         * UTC+14), there is something wrong if hour part is much
 595         * larger than that. We might also want to check that the
 596         * minutes are divisible by 15 or something too. (Offset of
 597         * Kathmandu, Nepal is UTC+5:45)
 598         */
 599        if (min < 60 && hour < 24) {
 600                int offset = hour * 60 + min;
 601                if (*date == '-')
 602                        offset = -offset;
 603                *offp = offset;
 604        }
 605        return end - date;
 606}
 607
 608static int date_string(unsigned long date, int offset, char *buf, int len)
 609{
 610        int sign = '+';
 611
 612        if (offset < 0) {
 613                offset = -offset;
 614                sign = '-';
 615        }
 616        return snprintf(buf, len, "%lu %c%02d%02d", date, sign, offset / 60, offset % 60);
 617}
 618
 619/*
 620 * Parse a string like "0 +0000" as ancient timestamp near epoch, but
 621 * only when it appears not as part of any other string.
 622 */
 623static int match_object_header_date(const char *date, unsigned long *timestamp, int *offset)
 624{
 625        char *end;
 626        unsigned long stamp;
 627        int ofs;
 628
 629        if (*date < '0' || '9' < *date)
 630                return -1;
 631        stamp = strtoul(date, &end, 10);
 632        if (*end != ' ' || stamp == ULONG_MAX || (end[1] != '+' && end[1] != '-'))
 633                return -1;
 634        date = end + 2;
 635        ofs = strtol(date, &end, 10);
 636        if ((*end != '\0' && (*end != '\n')) || end != date + 4)
 637                return -1;
 638        ofs = (ofs / 100) * 60 + (ofs % 100);
 639        if (date[-1] == '-')
 640                ofs = -ofs;
 641        *timestamp = stamp;
 642        *offset = ofs;
 643        return 0;
 644}
 645
 646/* Gr. strptime is crap for this; it doesn't have a way to require RFC2822
 647   (i.e. English) day/month names, and it doesn't work correctly with %z. */
 648int parse_date_basic(const char *date, unsigned long *timestamp, int *offset)
 649{
 650        struct tm tm;
 651        int tm_gmt;
 652        unsigned long dummy_timestamp;
 653        int dummy_offset;
 654
 655        if (!timestamp)
 656                timestamp = &dummy_timestamp;
 657        if (!offset)
 658                offset = &dummy_offset;
 659
 660        memset(&tm, 0, sizeof(tm));
 661        tm.tm_year = -1;
 662        tm.tm_mon = -1;
 663        tm.tm_mday = -1;
 664        tm.tm_isdst = -1;
 665        tm.tm_hour = -1;
 666        tm.tm_min = -1;
 667        tm.tm_sec = -1;
 668        *offset = -1;
 669        tm_gmt = 0;
 670
 671        if (*date == '@' &&
 672            !match_object_header_date(date + 1, timestamp, offset))
 673                return 0; /* success */
 674        for (;;) {
 675                int match = 0;
 676                unsigned char c = *date;
 677
 678                /* Stop at end of string or newline */
 679                if (!c || c == '\n')
 680                        break;
 681
 682                if (isalpha(c))
 683                        match = match_alpha(date, &tm, offset);
 684                else if (isdigit(c))
 685                        match = match_digit(date, &tm, offset, &tm_gmt);
 686                else if ((c == '-' || c == '+') && isdigit(date[1]))
 687                        match = match_tz(date, offset);
 688
 689                if (!match) {
 690                        /* BAD CRAP */
 691                        match = 1;
 692                }
 693
 694                date += match;
 695        }
 696
 697        /* mktime uses local timezone */
 698        *timestamp = tm_to_time_t(&tm);
 699        if (*offset == -1)
 700                *offset = ((time_t)*timestamp - mktime(&tm)) / 60;
 701
 702        if (*timestamp == -1)
 703                return -1;
 704
 705        if (!tm_gmt)
 706                *timestamp -= *offset * 60;
 707        return 0; /* success */
 708}
 709
 710int parse_date(const char *date, char *result, int maxlen)
 711{
 712        unsigned long timestamp;
 713        int offset;
 714        if (parse_date_basic(date, &timestamp, &offset))
 715                return -1;
 716        return date_string(timestamp, offset, result, maxlen);
 717}
 718
 719enum date_mode parse_date_format(const char *format)
 720{
 721        if (!strcmp(format, "relative"))
 722                return DATE_RELATIVE;
 723        else if (!strcmp(format, "iso8601") ||
 724                 !strcmp(format, "iso"))
 725                return DATE_ISO8601;
 726        else if (!strcmp(format, "rfc2822") ||
 727                 !strcmp(format, "rfc"))
 728                return DATE_RFC2822;
 729        else if (!strcmp(format, "short"))
 730                return DATE_SHORT;
 731        else if (!strcmp(format, "local"))
 732                return DATE_LOCAL;
 733        else if (!strcmp(format, "default"))
 734                return DATE_NORMAL;
 735        else if (!strcmp(format, "raw"))
 736                return DATE_RAW;
 737        else
 738                die("unknown date format %s", format);
 739}
 740
 741void datestamp(char *buf, int bufsize)
 742{
 743        time_t now;
 744        int offset;
 745
 746        time(&now);
 747
 748        offset = tm_to_time_t(localtime(&now)) - now;
 749        offset /= 60;
 750
 751        date_string(now, offset, buf, bufsize);
 752}
 753
 754/*
 755 * Relative time update (eg "2 days ago").  If we haven't set the time
 756 * yet, we need to set it from current time.
 757 */
 758static unsigned long update_tm(struct tm *tm, struct tm *now, unsigned long sec)
 759{
 760        time_t n;
 761
 762        if (tm->tm_mday < 0)
 763                tm->tm_mday = now->tm_mday;
 764        if (tm->tm_mon < 0)
 765                tm->tm_mon = now->tm_mon;
 766        if (tm->tm_year < 0) {
 767                tm->tm_year = now->tm_year;
 768                if (tm->tm_mon > now->tm_mon)
 769                        tm->tm_year--;
 770        }
 771
 772        n = mktime(tm) - sec;
 773        localtime_r(&n, tm);
 774        return n;
 775}
 776
 777static void date_now(struct tm *tm, struct tm *now, int *num)
 778{
 779        update_tm(tm, now, 0);
 780}
 781
 782static void date_yesterday(struct tm *tm, struct tm *now, int *num)
 783{
 784        update_tm(tm, now, 24*60*60);
 785}
 786
 787static void date_time(struct tm *tm, struct tm *now, int hour)
 788{
 789        if (tm->tm_hour < hour)
 790                date_yesterday(tm, now, NULL);
 791        tm->tm_hour = hour;
 792        tm->tm_min = 0;
 793        tm->tm_sec = 0;
 794}
 795
 796static void date_midnight(struct tm *tm, struct tm *now, int *num)
 797{
 798        date_time(tm, now, 0);
 799}
 800
 801static void date_noon(struct tm *tm, struct tm *now, int *num)
 802{
 803        date_time(tm, now, 12);
 804}
 805
 806static void date_tea(struct tm *tm, struct tm *now, int *num)
 807{
 808        date_time(tm, now, 17);
 809}
 810
 811static void date_pm(struct tm *tm, struct tm *now, int *num)
 812{
 813        int hour, n = *num;
 814        *num = 0;
 815
 816        hour = tm->tm_hour;
 817        if (n) {
 818                hour = n;
 819                tm->tm_min = 0;
 820                tm->tm_sec = 0;
 821        }
 822        tm->tm_hour = (hour % 12) + 12;
 823}
 824
 825static void date_am(struct tm *tm, struct tm *now, int *num)
 826{
 827        int hour, n = *num;
 828        *num = 0;
 829
 830        hour = tm->tm_hour;
 831        if (n) {
 832                hour = n;
 833                tm->tm_min = 0;
 834                tm->tm_sec = 0;
 835        }
 836        tm->tm_hour = (hour % 12);
 837}
 838
 839static void date_never(struct tm *tm, struct tm *now, int *num)
 840{
 841        time_t n = 0;
 842        localtime_r(&n, tm);
 843}
 844
 845static const struct special {
 846        const char *name;
 847        void (*fn)(struct tm *, struct tm *, int *);
 848} special[] = {
 849        { "yesterday", date_yesterday },
 850        { "noon", date_noon },
 851        { "midnight", date_midnight },
 852        { "tea", date_tea },
 853        { "PM", date_pm },
 854        { "AM", date_am },
 855        { "never", date_never },
 856        { "now", date_now },
 857        { NULL }
 858};
 859
 860static const char *number_name[] = {
 861        "zero", "one", "two", "three", "four",
 862        "five", "six", "seven", "eight", "nine", "ten",
 863};
 864
 865static const struct typelen {
 866        const char *type;
 867        int length;
 868} typelen[] = {
 869        { "seconds", 1 },
 870        { "minutes", 60 },
 871        { "hours", 60*60 },
 872        { "days", 24*60*60 },
 873        { "weeks", 7*24*60*60 },
 874        { NULL }
 875};
 876
 877static const char *approxidate_alpha(const char *date, struct tm *tm, struct tm *now, int *num, int *touched)
 878{
 879        const struct typelen *tl;
 880        const struct special *s;
 881        const char *end = date;
 882        int i;
 883
 884        while (isalpha(*++end));
 885                ;
 886
 887        for (i = 0; i < 12; i++) {
 888                int match = match_string(date, month_names[i]);
 889                if (match >= 3) {
 890                        tm->tm_mon = i;
 891                        *touched = 1;
 892                        return end;
 893                }
 894        }
 895
 896        for (s = special; s->name; s++) {
 897                int len = strlen(s->name);
 898                if (match_string(date, s->name) == len) {
 899                        s->fn(tm, now, num);
 900                        *touched = 1;
 901                        return end;
 902                }
 903        }
 904
 905        if (!*num) {
 906                for (i = 1; i < 11; i++) {
 907                        int len = strlen(number_name[i]);
 908                        if (match_string(date, number_name[i]) == len) {
 909                                *num = i;
 910                                *touched = 1;
 911                                return end;
 912                        }
 913                }
 914                if (match_string(date, "last") == 4) {
 915                        *num = 1;
 916                        *touched = 1;
 917                }
 918                return end;
 919        }
 920
 921        tl = typelen;
 922        while (tl->type) {
 923                int len = strlen(tl->type);
 924                if (match_string(date, tl->type) >= len-1) {
 925                        update_tm(tm, now, tl->length * *num);
 926                        *num = 0;
 927                        *touched = 1;
 928                        return end;
 929                }
 930                tl++;
 931        }
 932
 933        for (i = 0; i < 7; i++) {
 934                int match = match_string(date, weekday_names[i]);
 935                if (match >= 3) {
 936                        int diff, n = *num -1;
 937                        *num = 0;
 938
 939                        diff = tm->tm_wday - i;
 940                        if (diff <= 0)
 941                                n++;
 942                        diff += 7*n;
 943
 944                        update_tm(tm, now, diff * 24 * 60 * 60);
 945                        *touched = 1;
 946                        return end;
 947                }
 948        }
 949
 950        if (match_string(date, "months") >= 5) {
 951                int n;
 952                update_tm(tm, now, 0); /* fill in date fields if needed */
 953                n = tm->tm_mon - *num;
 954                *num = 0;
 955                while (n < 0) {
 956                        n += 12;
 957                        tm->tm_year--;
 958                }
 959                tm->tm_mon = n;
 960                *touched = 1;
 961                return end;
 962        }
 963
 964        if (match_string(date, "years") >= 4) {
 965                update_tm(tm, now, 0); /* fill in date fields if needed */
 966                tm->tm_year -= *num;
 967                *num = 0;
 968                *touched = 1;
 969                return end;
 970        }
 971
 972        return end;
 973}
 974
 975static const char *approxidate_digit(const char *date, struct tm *tm, int *num)
 976{
 977        char *end;
 978        unsigned long number = strtoul(date, &end, 10);
 979
 980        switch (*end) {
 981        case ':':
 982        case '.':
 983        case '/':
 984        case '-':
 985                if (isdigit(end[1])) {
 986                        int match = match_multi_number(number, *end, date, end, tm);
 987                        if (match)
 988                                return date + match;
 989                }
 990        }
 991
 992        /* Accept zero-padding only for small numbers ("Dec 02", never "Dec 0002") */
 993        if (date[0] != '0' || end - date <= 2)
 994                *num = number;
 995        return end;
 996}
 997
 998/*
 999 * Do we have a pending number at the end, or when
1000 * we see a new one? Let's assume it's a month day,
1001 * as in "Dec 6, 1992"
1002 */
1003static void pending_number(struct tm *tm, int *num)
1004{
1005        int number = *num;
1006
1007        if (number) {
1008                *num = 0;
1009                if (tm->tm_mday < 0 && number < 32)
1010                        tm->tm_mday = number;
1011                else if (tm->tm_mon < 0 && number < 13)
1012                        tm->tm_mon = number-1;
1013                else if (tm->tm_year < 0) {
1014                        if (number > 1969 && number < 2100)
1015                                tm->tm_year = number - 1900;
1016                        else if (number > 69 && number < 100)
1017                                tm->tm_year = number;
1018                        else if (number < 38)
1019                                tm->tm_year = 100 + number;
1020                        /* We screw up for number = 00 ? */
1021                }
1022        }
1023}
1024
1025static unsigned long approxidate_str(const char *date,
1026                                     const struct timeval *tv,
1027                                     int *error_ret)
1028{
1029        int number = 0;
1030        int touched = 0;
1031        struct tm tm, now;
1032        time_t time_sec;
1033
1034        time_sec = tv->tv_sec;
1035        localtime_r(&time_sec, &tm);
1036        now = tm;
1037
1038        tm.tm_year = -1;
1039        tm.tm_mon = -1;
1040        tm.tm_mday = -1;
1041
1042        for (;;) {
1043                unsigned char c = *date;
1044                if (!c)
1045                        break;
1046                date++;
1047                if (isdigit(c)) {
1048                        pending_number(&tm, &number);
1049                        date = approxidate_digit(date-1, &tm, &number);
1050                        touched = 1;
1051                        continue;
1052                }
1053                if (isalpha(c))
1054                        date = approxidate_alpha(date-1, &tm, &now, &number, &touched);
1055        }
1056        pending_number(&tm, &number);
1057        if (!touched)
1058                *error_ret = 1;
1059        return update_tm(&tm, &now, 0);
1060}
1061
1062unsigned long approxidate_relative(const char *date, const struct timeval *tv)
1063{
1064        unsigned long timestamp;
1065        int offset;
1066        int errors = 0;
1067
1068        if (!parse_date_basic(date, &timestamp, &offset))
1069                return timestamp;
1070        return approxidate_str(date, tv, &errors);
1071}
1072
1073unsigned long approxidate_careful(const char *date, int *error_ret)
1074{
1075        struct timeval tv;
1076        unsigned long timestamp;
1077        int offset;
1078        int dummy = 0;
1079        if (!error_ret)
1080                error_ret = &dummy;
1081
1082        if (!parse_date_basic(date, &timestamp, &offset)) {
1083                *error_ret = 0;
1084                return timestamp;
1085        }
1086
1087        gettimeofday(&tv, NULL);
1088        return approxidate_str(date, &tv, error_ret);
1089}
1090
1091int date_overflows(unsigned long t)
1092{
1093        time_t sys;
1094
1095        /* If we overflowed our unsigned long, that's bad... */
1096        if (t == ULONG_MAX)
1097                return 1;
1098
1099        /*
1100         * ...but we also are going to feed the result to system
1101         * functions that expect time_t, which is often "signed long".
1102         * Make sure that we fit into time_t, as well.
1103         */
1104        sys = t;
1105        return t != sys || (t < 1) != (sys < 1);
1106}