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