prtime.cc revision 58d02015f8788a79b322c58d4bdbc914e4c333dc
1/* Portions are Copyright (C) 2007 Google Inc */
2/* ***** BEGIN LICENSE BLOCK *****
3 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
4 *
5 * The contents of this file are subject to the Mozilla Public License Version
6 * 1.1 (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 * http://www.mozilla.org/MPL/
9 *
10 * Software distributed under the License is distributed on an "AS IS" basis,
11 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12 * for the specific language governing rights and limitations under the
13 * License.
14 *
15 * The Original Code is the Netscape Portable Runtime (NSPR).
16 *
17 * The Initial Developer of the Original Code is
18 * Netscape Communications Corporation.
19 * Portions created by the Initial Developer are Copyright (C) 1998-2000
20 * the Initial Developer. All Rights Reserved.
21 *
22 * Contributor(s):
23 *
24 * Alternatively, the contents of this file may be used under the terms of
25 * either the GNU General Public License Version 2 or later (the "GPL"), or
26 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
27 * in which case the provisions of the GPL or the LGPL are applicable instead
28 * of those above. If you wish to allow use of your version of this file only
29 * under the terms of either the GPL or the LGPL, and not to allow others to
30 * use your version of this file under the terms of the MPL, indicate your
31 * decision by deleting the provisions above and replace them with the notice
32 * and other provisions required by the GPL or the LGPL. If you do not delete
33 * the provisions above, a recipient may use your version of this file under
34 * the terms of any one of the MPL, the GPL or the LGPL.
35 *
36 * ***** END LICENSE BLOCK ***** */
37
38/*
39 * prtime.cc --
40 * NOTE: The original nspr file name is prtime.c
41 *
42 *     NSPR date and time functions
43 *
44 * CVS revision 3.37
45 */
46
47/*
48 * The following functions were copied from the NSPR prtime.c file.
49 * PR_ParseTimeString
50 *   We inlined the new PR_ParseTimeStringToExplodedTime function to avoid
51 *   copying PR_ExplodeTime and PR_LocalTimeParameters.  (The PR_ExplodeTime
52 *   and PR_ImplodeTime calls cancel each other out.)
53 * PR_NormalizeTime
54 * PR_GMTParameters
55 * PR_ImplodeTime
56 *   This was modified to use the Win32 SYSTEMTIME/FILETIME structures
57 *   and the timezone offsets are applied to the FILETIME structure.
58 * All types and macros are defined in the base/third_party/prtime.h file.
59 * These have been copied from the following nspr files. We have only copied
60 * over the types we need.
61 * 1. prtime.h
62 * 2. prtypes.h
63 * 3. prlong.h
64 */
65
66#include "prtime.h"
67#include "build/build_config.h"
68
69#if defined(OS_WIN)
70#include <windows.h>
71#elif defined(OS_MACOSX)
72#include <CoreFoundation/CoreFoundation.h>
73#endif
74#include <errno.h>  /* for EINVAL */
75#include <time.h>
76
77/* Implements the Unix localtime_r() function for windows */
78#if defined(OS_WIN)
79static void localtime_r(const time_t* secs, struct tm* time) {
80  (void) localtime_s(time, secs);
81}
82#endif
83
84/*
85 *------------------------------------------------------------------------
86 *
87 * PR_ImplodeTime --
88 *
89 *     Cf. time_t mktime(struct tm *tp)
90 *     Note that 1 year has < 2^25 seconds.  So an PRInt32 is large enough.
91 *
92 *------------------------------------------------------------------------
93 */
94PRTime
95PR_ImplodeTime(const PRExplodedTime *exploded)
96{
97    // This is important, we want to make sure multiplications are
98    // done with the correct precision.
99    static const PRTime kSecondsToMicroseconds = static_cast<PRTime>(1000000);
100#if defined(OS_WIN)
101   // Create the system struct representing our exploded time.
102    SYSTEMTIME st = {0};
103    FILETIME ft = {0};
104    ULARGE_INTEGER uli = {0};
105
106    st.wYear = exploded->tm_year;
107    st.wMonth = exploded->tm_month + 1;
108    st.wDayOfWeek = exploded->tm_wday;
109    st.wDay = exploded->tm_mday;
110    st.wHour = exploded->tm_hour;
111    st.wMinute = exploded->tm_min;
112    st.wSecond = exploded->tm_sec;
113    st.wMilliseconds = exploded->tm_usec/1000;
114     // Convert to FILETIME.
115    if (!SystemTimeToFileTime(&st, &ft)) {
116      NOTREACHED() << "Unable to convert time";
117      return 0;
118    }
119    // Apply offsets.
120    uli.LowPart = ft.dwLowDateTime;
121    uli.HighPart = ft.dwHighDateTime;
122    // Convert from Windows epoch to NSPR epoch, and 100-nanoseconds units
123    // to microsecond units.
124    PRTime result =
125        static_cast<PRTime>((uli.QuadPart / 10) - 11644473600000000i64);
126    // Adjust for time zone and dst.  Convert from seconds to microseconds.
127    result -= (exploded->tm_params.tp_gmt_offset +
128               exploded->tm_params.tp_dst_offset) * kSecondsToMicroseconds;
129    return result;
130#elif defined(OS_MACOSX)
131    // Create the system struct representing our exploded time.
132    CFGregorianDate gregorian_date;
133    gregorian_date.year = exploded->tm_year;
134    gregorian_date.month = exploded->tm_month + 1;
135    gregorian_date.day = exploded->tm_mday;
136    gregorian_date.hour = exploded->tm_hour;
137    gregorian_date.minute = exploded->tm_min;
138    gregorian_date.second = exploded->tm_sec;
139
140    // Compute |absolute_time| in seconds, correct for gmt and dst
141    // (note the combined offset will be negative when we need to add it), then
142    // convert to microseconds which is what PRTime expects.
143    CFAbsoluteTime absolute_time =
144        CFGregorianDateGetAbsoluteTime(gregorian_date, NULL);
145    PRTime result = static_cast<PRTime>(absolute_time);
146    result -= exploded->tm_params.tp_gmt_offset +
147              exploded->tm_params.tp_dst_offset;
148    result += kCFAbsoluteTimeIntervalSince1970;  // PRTime epoch is 1970
149    result *= kSecondsToMicroseconds;
150    result += exploded->tm_usec;
151    return result;
152#elif defined(OS_POSIX)
153    struct tm exp_tm = {0};
154    exp_tm.tm_sec  = exploded->tm_sec;
155    exp_tm.tm_min  = exploded->tm_min;
156    exp_tm.tm_hour = exploded->tm_hour;
157    exp_tm.tm_mday = exploded->tm_mday;
158    exp_tm.tm_mon  = exploded->tm_month;
159    exp_tm.tm_year = exploded->tm_year - 1900;
160
161#if defined(ANDROID)
162    // TODO: Fix in bionic
163    time_t absolute_time = mktime(&exp_tm);
164#else
165    time_t absolute_time = timegm(&exp_tm);
166#endif // broken android
167
168    // If timegm returned -1.  Since we don't pass it a time zone, the only
169    // valid case of returning -1 is 1 second before Epoch (Dec 31, 1969).
170    if (absolute_time == -1 &&
171        !(exploded->tm_year == 1969 && exploded->tm_month == 11 &&
172        exploded->tm_mday == 31 && exploded->tm_hour == 23 &&
173        exploded->tm_min == 59 && exploded->tm_sec == 59)) {
174      // If we get here, time_t must be 32 bits.
175      // Date was possibly too far in the future and would overflow.  Return
176      // the most future date possible (year 2038).
177      if (exploded->tm_year >= 1970)
178        return INT_MAX * kSecondsToMicroseconds;
179      // Date was possibly too far in the past and would underflow.  Return
180      // the most past date possible (year 1901).
181      return INT_MIN * kSecondsToMicroseconds;
182    }
183
184    PRTime result = static_cast<PRTime>(absolute_time);
185    result -= exploded->tm_params.tp_gmt_offset +
186              exploded->tm_params.tp_dst_offset;
187    result *= kSecondsToMicroseconds;
188    result += exploded->tm_usec;
189    return result;
190#else
191#error No PR_ImplodeTime implemented on your platform.
192#endif
193}
194
195/*
196 * The COUNT_LEAPS macro counts the number of leap years passed by
197 * till the start of the given year Y.  At the start of the year 4
198 * A.D. the number of leap years passed by is 0, while at the start of
199 * the year 5 A.D. this count is 1. The number of years divisible by
200 * 100 but not divisible by 400 (the non-leap years) is deducted from
201 * the count to get the correct number of leap years.
202 *
203 * The COUNT_DAYS macro counts the number of days since 01/01/01 till the
204 * start of the given year Y. The number of days at the start of the year
205 * 1 is 0 while the number of days at the start of the year 2 is 365
206 * (which is ((2)-1) * 365) and so on. The reference point is 01/01/01
207 * midnight 00:00:00.
208 */
209
210#define COUNT_LEAPS(Y)   ( ((Y)-1)/4 - ((Y)-1)/100 + ((Y)-1)/400 )
211#define COUNT_DAYS(Y)  ( ((Y)-1)*365 + COUNT_LEAPS(Y) )
212#define DAYS_BETWEEN_YEARS(A, B)  (COUNT_DAYS(B) - COUNT_DAYS(A))
213
214/*
215 * Static variables used by functions in this file
216 */
217
218/*
219 * The following array contains the day of year for the last day of
220 * each month, where index 1 is January, and day 0 is January 1.
221 */
222
223static const int lastDayOfMonth[2][13] = {
224    {-1, 30, 58, 89, 119, 150, 180, 211, 242, 272, 303, 333, 364},
225    {-1, 30, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}
226};
227
228/*
229 * The number of days in a month
230 */
231
232static const PRInt8 nDays[2][12] = {
233    {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
234    {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
235};
236
237/*
238 *-------------------------------------------------------------------------
239 *
240 * IsLeapYear --
241 *
242 *     Returns 1 if the year is a leap year, 0 otherwise.
243 *
244 *-------------------------------------------------------------------------
245 */
246
247static int IsLeapYear(PRInt16 year)
248{
249    if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
250        return 1;
251    else
252        return 0;
253}
254
255/*
256 * 'secOffset' should be less than 86400 (i.e., a day).
257 * 'time' should point to a normalized PRExplodedTime.
258 */
259
260static void
261ApplySecOffset(PRExplodedTime *time, PRInt32 secOffset)
262{
263    time->tm_sec += secOffset;
264
265    /* Note that in this implementation we do not count leap seconds */
266    if (time->tm_sec < 0 || time->tm_sec >= 60) {
267        time->tm_min += time->tm_sec / 60;
268        time->tm_sec %= 60;
269        if (time->tm_sec < 0) {
270            time->tm_sec += 60;
271            time->tm_min--;
272        }
273    }
274
275    if (time->tm_min < 0 || time->tm_min >= 60) {
276        time->tm_hour += time->tm_min / 60;
277        time->tm_min %= 60;
278        if (time->tm_min < 0) {
279            time->tm_min += 60;
280            time->tm_hour--;
281        }
282    }
283
284    if (time->tm_hour < 0) {
285        /* Decrement mday, yday, and wday */
286        time->tm_hour += 24;
287        time->tm_mday--;
288        time->tm_yday--;
289        if (time->tm_mday < 1) {
290            time->tm_month--;
291            if (time->tm_month < 0) {
292                time->tm_month = 11;
293                time->tm_year--;
294                if (IsLeapYear(time->tm_year))
295                    time->tm_yday = 365;
296                else
297                    time->tm_yday = 364;
298            }
299            time->tm_mday = nDays[IsLeapYear(time->tm_year)][time->tm_month];
300        }
301        time->tm_wday--;
302        if (time->tm_wday < 0)
303            time->tm_wday = 6;
304    } else if (time->tm_hour > 23) {
305        /* Increment mday, yday, and wday */
306        time->tm_hour -= 24;
307        time->tm_mday++;
308        time->tm_yday++;
309        if (time->tm_mday >
310                nDays[IsLeapYear(time->tm_year)][time->tm_month]) {
311            time->tm_mday = 1;
312            time->tm_month++;
313            if (time->tm_month > 11) {
314                time->tm_month = 0;
315                time->tm_year++;
316                time->tm_yday = 0;
317            }
318        }
319        time->tm_wday++;
320        if (time->tm_wday > 6)
321            time->tm_wday = 0;
322    }
323}
324
325void
326PR_NormalizeTime(PRExplodedTime *time, PRTimeParamFn params)
327{
328    int daysInMonth;
329    PRInt32 numDays;
330
331    /* Get back to GMT */
332    time->tm_sec -= time->tm_params.tp_gmt_offset
333            + time->tm_params.tp_dst_offset;
334    time->tm_params.tp_gmt_offset = 0;
335    time->tm_params.tp_dst_offset = 0;
336
337    /* Now normalize GMT */
338
339    if (time->tm_usec < 0 || time->tm_usec >= 1000000) {
340        time->tm_sec +=  time->tm_usec / 1000000;
341        time->tm_usec %= 1000000;
342        if (time->tm_usec < 0) {
343            time->tm_usec += 1000000;
344            time->tm_sec--;
345        }
346    }
347
348    /* Note that we do not count leap seconds in this implementation */
349    if (time->tm_sec < 0 || time->tm_sec >= 60) {
350        time->tm_min += time->tm_sec / 60;
351        time->tm_sec %= 60;
352        if (time->tm_sec < 0) {
353            time->tm_sec += 60;
354            time->tm_min--;
355        }
356    }
357
358    if (time->tm_min < 0 || time->tm_min >= 60) {
359        time->tm_hour += time->tm_min / 60;
360        time->tm_min %= 60;
361        if (time->tm_min < 0) {
362            time->tm_min += 60;
363            time->tm_hour--;
364        }
365    }
366
367    if (time->tm_hour < 0 || time->tm_hour >= 24) {
368        time->tm_mday += time->tm_hour / 24;
369        time->tm_hour %= 24;
370        if (time->tm_hour < 0) {
371            time->tm_hour += 24;
372            time->tm_mday--;
373        }
374    }
375
376    /* Normalize month and year before mday */
377    if (time->tm_month < 0 || time->tm_month >= 12) {
378        time->tm_year += time->tm_month / 12;
379        time->tm_month %= 12;
380        if (time->tm_month < 0) {
381            time->tm_month += 12;
382            time->tm_year--;
383        }
384    }
385
386    /* Now that month and year are in proper range, normalize mday */
387
388    if (time->tm_mday < 1) {
389        /* mday too small */
390        do {
391            /* the previous month */
392            time->tm_month--;
393            if (time->tm_month < 0) {
394                time->tm_month = 11;
395                time->tm_year--;
396            }
397            time->tm_mday += nDays[IsLeapYear(time->tm_year)][time->tm_month];
398        } while (time->tm_mday < 1);
399    } else {
400        daysInMonth = nDays[IsLeapYear(time->tm_year)][time->tm_month];
401        while (time->tm_mday > daysInMonth) {
402            /* mday too large */
403            time->tm_mday -= daysInMonth;
404            time->tm_month++;
405            if (time->tm_month > 11) {
406                time->tm_month = 0;
407                time->tm_year++;
408            }
409            daysInMonth = nDays[IsLeapYear(time->tm_year)][time->tm_month];
410        }
411    }
412
413    /* Recompute yday and wday */
414    time->tm_yday = time->tm_mday +
415            lastDayOfMonth[IsLeapYear(time->tm_year)][time->tm_month];
416
417    numDays = DAYS_BETWEEN_YEARS(1970, time->tm_year) + time->tm_yday;
418    time->tm_wday = (numDays + 4) % 7;
419    if (time->tm_wday < 0) {
420        time->tm_wday += 7;
421    }
422
423    /* Recompute time parameters */
424
425    time->tm_params = params(time);
426
427    ApplySecOffset(time, time->tm_params.tp_gmt_offset
428            + time->tm_params.tp_dst_offset);
429}
430
431/*
432 *------------------------------------------------------------------------
433 *
434 * PR_GMTParameters --
435 *
436 *     Returns the PRTimeParameters for Greenwich Mean Time.
437 *     Trivially, both the tp_gmt_offset and tp_dst_offset fields are 0.
438 *
439 *------------------------------------------------------------------------
440 */
441
442PRTimeParameters
443PR_GMTParameters(const PRExplodedTime *gmt)
444{
445#if defined(XP_MAC)
446#pragma unused (gmt)
447#endif
448
449    PRTimeParameters retVal = { 0, 0 };
450    return retVal;
451}
452
453/*
454 * The following code implements PR_ParseTimeString().  It is based on
455 * ns/lib/xp/xp_time.c, revision 1.25, by Jamie Zawinski <jwz@netscape.com>.
456 */
457
458/*
459 * We only recognize the abbreviations of a small subset of time zones
460 * in North America, Europe, and Japan.
461 *
462 * PST/PDT: Pacific Standard/Daylight Time
463 * MST/MDT: Mountain Standard/Daylight Time
464 * CST/CDT: Central Standard/Daylight Time
465 * EST/EDT: Eastern Standard/Daylight Time
466 * AST: Atlantic Standard Time
467 * NST: Newfoundland Standard Time
468 * GMT: Greenwich Mean Time
469 * BST: British Summer Time
470 * MET: Middle Europe Time
471 * EET: Eastern Europe Time
472 * JST: Japan Standard Time
473 */
474
475typedef enum
476{
477  TT_UNKNOWN,
478
479  TT_SUN, TT_MON, TT_TUE, TT_WED, TT_THU, TT_FRI, TT_SAT,
480
481  TT_JAN, TT_FEB, TT_MAR, TT_APR, TT_MAY, TT_JUN,
482  TT_JUL, TT_AUG, TT_SEP, TT_OCT, TT_NOV, TT_DEC,
483
484  TT_PST, TT_PDT, TT_MST, TT_MDT, TT_CST, TT_CDT, TT_EST, TT_EDT,
485  TT_AST, TT_NST, TT_GMT, TT_BST, TT_MET, TT_EET, TT_JST
486} TIME_TOKEN;
487
488/*
489 * This parses a time/date string into a PRTime
490 * (microseconds after "1-Jan-1970 00:00:00 GMT").
491 * It returns PR_SUCCESS on success, and PR_FAILURE
492 * if the time/date string can't be parsed.
493 *
494 * Many formats are handled, including:
495 *
496 *   14 Apr 89 03:20:12
497 *   14 Apr 89 03:20 GMT
498 *   Fri, 17 Mar 89 4:01:33
499 *   Fri, 17 Mar 89 4:01 GMT
500 *   Mon Jan 16 16:12 PDT 1989
501 *   Mon Jan 16 16:12 +0130 1989
502 *   6 May 1992 16:41-JST (Wednesday)
503 *   22-AUG-1993 10:59:12.82
504 *   22-AUG-1993 10:59pm
505 *   22-AUG-1993 12:59am
506 *   22-AUG-1993 12:59 PM
507 *   Friday, August 04, 1995 3:54 PM
508 *   06/21/95 04:24:34 PM
509 *   20/06/95 21:07
510 *   95-06-08 19:32:48 EDT
511 *
512 * If the input string doesn't contain a description of the timezone,
513 * we consult the `default_to_gmt' to decide whether the string should
514 * be interpreted relative to the local time zone (PR_FALSE) or GMT (PR_TRUE).
515 * The correct value for this argument depends on what standard specified
516 * the time string which you are parsing.
517 */
518
519PRStatus
520PR_ParseTimeString(
521        const char *string,
522        PRBool default_to_gmt,
523        PRTime *result_imploded)
524{
525  PRExplodedTime tm;
526  PRExplodedTime *result = &tm;
527  TIME_TOKEN dotw = TT_UNKNOWN;
528  TIME_TOKEN month = TT_UNKNOWN;
529  TIME_TOKEN zone = TT_UNKNOWN;
530  int zone_offset = -1;
531  int dst_offset = 0;
532  int date = -1;
533  PRInt32 year = -1;
534  int hour = -1;
535  int min = -1;
536  int sec = -1;
537
538  const char *rest = string;
539
540  int iterations = 0;
541
542  PR_ASSERT(string && result);
543  if (!string || !result) return PR_FAILURE;
544
545  while (*rest)
546        {
547
548          if (iterations++ > 1000)
549                {
550                  return PR_FAILURE;
551                }
552
553          switch (*rest)
554                {
555                case 'a': case 'A':
556                  if (month == TT_UNKNOWN &&
557                          (rest[1] == 'p' || rest[1] == 'P') &&
558                          (rest[2] == 'r' || rest[2] == 'R'))
559                        month = TT_APR;
560                  else if (zone == TT_UNKNOWN &&
561                                   (rest[1] == 's' || rest[1] == 'S') &&
562                                   (rest[2] == 't' || rest[2] == 'T'))
563                        zone = TT_AST;
564                  else if (month == TT_UNKNOWN &&
565                                   (rest[1] == 'u' || rest[1] == 'U') &&
566                                   (rest[2] == 'g' || rest[2] == 'G'))
567                        month = TT_AUG;
568                  break;
569                case 'b': case 'B':
570                  if (zone == TT_UNKNOWN &&
571                          (rest[1] == 's' || rest[1] == 'S') &&
572                          (rest[2] == 't' || rest[2] == 'T'))
573                        zone = TT_BST;
574                  break;
575                case 'c': case 'C':
576                  if (zone == TT_UNKNOWN &&
577                          (rest[1] == 'd' || rest[1] == 'D') &&
578                          (rest[2] == 't' || rest[2] == 'T'))
579                        zone = TT_CDT;
580                  else if (zone == TT_UNKNOWN &&
581                                   (rest[1] == 's' || rest[1] == 'S') &&
582                                   (rest[2] == 't' || rest[2] == 'T'))
583                        zone = TT_CST;
584                  break;
585                case 'd': case 'D':
586                  if (month == TT_UNKNOWN &&
587                          (rest[1] == 'e' || rest[1] == 'E') &&
588                          (rest[2] == 'c' || rest[2] == 'C'))
589                        month = TT_DEC;
590                  break;
591                case 'e': case 'E':
592                  if (zone == TT_UNKNOWN &&
593                          (rest[1] == 'd' || rest[1] == 'D') &&
594                          (rest[2] == 't' || rest[2] == 'T'))
595                        zone = TT_EDT;
596                  else if (zone == TT_UNKNOWN &&
597                                   (rest[1] == 'e' || rest[1] == 'E') &&
598                                   (rest[2] == 't' || rest[2] == 'T'))
599                        zone = TT_EET;
600                  else if (zone == TT_UNKNOWN &&
601                                   (rest[1] == 's' || rest[1] == 'S') &&
602                                   (rest[2] == 't' || rest[2] == 'T'))
603                        zone = TT_EST;
604                  break;
605                case 'f': case 'F':
606                  if (month == TT_UNKNOWN &&
607                          (rest[1] == 'e' || rest[1] == 'E') &&
608                          (rest[2] == 'b' || rest[2] == 'B'))
609                        month = TT_FEB;
610                  else if (dotw == TT_UNKNOWN &&
611                                   (rest[1] == 'r' || rest[1] == 'R') &&
612                                   (rest[2] == 'i' || rest[2] == 'I'))
613                        dotw = TT_FRI;
614                  break;
615                case 'g': case 'G':
616                  if (zone == TT_UNKNOWN &&
617                          (rest[1] == 'm' || rest[1] == 'M') &&
618                          (rest[2] == 't' || rest[2] == 'T'))
619                        zone = TT_GMT;
620                  break;
621                case 'j': case 'J':
622                  if (month == TT_UNKNOWN &&
623                          (rest[1] == 'a' || rest[1] == 'A') &&
624                          (rest[2] == 'n' || rest[2] == 'N'))
625                        month = TT_JAN;
626                  else if (zone == TT_UNKNOWN &&
627                                   (rest[1] == 's' || rest[1] == 'S') &&
628                                   (rest[2] == 't' || rest[2] == 'T'))
629                        zone = TT_JST;
630                  else if (month == TT_UNKNOWN &&
631                                   (rest[1] == 'u' || rest[1] == 'U') &&
632                                   (rest[2] == 'l' || rest[2] == 'L'))
633                        month = TT_JUL;
634                  else if (month == TT_UNKNOWN &&
635                                   (rest[1] == 'u' || rest[1] == 'U') &&
636                                   (rest[2] == 'n' || rest[2] == 'N'))
637                        month = TT_JUN;
638                  break;
639                case 'm': case 'M':
640                  if (month == TT_UNKNOWN &&
641                          (rest[1] == 'a' || rest[1] == 'A') &&
642                          (rest[2] == 'r' || rest[2] == 'R'))
643                        month = TT_MAR;
644                  else if (month == TT_UNKNOWN &&
645                                   (rest[1] == 'a' || rest[1] == 'A') &&
646                                   (rest[2] == 'y' || rest[2] == 'Y'))
647                        month = TT_MAY;
648                  else if (zone == TT_UNKNOWN &&
649                                   (rest[1] == 'd' || rest[1] == 'D') &&
650                                   (rest[2] == 't' || rest[2] == 'T'))
651                        zone = TT_MDT;
652                  else if (zone == TT_UNKNOWN &&
653                                   (rest[1] == 'e' || rest[1] == 'E') &&
654                                   (rest[2] == 't' || rest[2] == 'T'))
655                        zone = TT_MET;
656                  else if (dotw == TT_UNKNOWN &&
657                                   (rest[1] == 'o' || rest[1] == 'O') &&
658                                   (rest[2] == 'n' || rest[2] == 'N'))
659                        dotw = TT_MON;
660                  else if (zone == TT_UNKNOWN &&
661                                   (rest[1] == 's' || rest[1] == 'S') &&
662                                   (rest[2] == 't' || rest[2] == 'T'))
663                        zone = TT_MST;
664                  break;
665                case 'n': case 'N':
666                  if (month == TT_UNKNOWN &&
667                          (rest[1] == 'o' || rest[1] == 'O') &&
668                          (rest[2] == 'v' || rest[2] == 'V'))
669                        month = TT_NOV;
670                  else if (zone == TT_UNKNOWN &&
671                                   (rest[1] == 's' || rest[1] == 'S') &&
672                                   (rest[2] == 't' || rest[2] == 'T'))
673                        zone = TT_NST;
674                  break;
675                case 'o': case 'O':
676                  if (month == TT_UNKNOWN &&
677                          (rest[1] == 'c' || rest[1] == 'C') &&
678                          (rest[2] == 't' || rest[2] == 'T'))
679                        month = TT_OCT;
680                  break;
681                case 'p': case 'P':
682                  if (zone == TT_UNKNOWN &&
683                          (rest[1] == 'd' || rest[1] == 'D') &&
684                          (rest[2] == 't' || rest[2] == 'T'))
685                        zone = TT_PDT;
686                  else if (zone == TT_UNKNOWN &&
687                                   (rest[1] == 's' || rest[1] == 'S') &&
688                                   (rest[2] == 't' || rest[2] == 'T'))
689                        zone = TT_PST;
690                  break;
691                case 's': case 'S':
692                  if (dotw == TT_UNKNOWN &&
693                          (rest[1] == 'a' || rest[1] == 'A') &&
694                          (rest[2] == 't' || rest[2] == 'T'))
695                        dotw = TT_SAT;
696                  else if (month == TT_UNKNOWN &&
697                                   (rest[1] == 'e' || rest[1] == 'E') &&
698                                   (rest[2] == 'p' || rest[2] == 'P'))
699                        month = TT_SEP;
700                  else if (dotw == TT_UNKNOWN &&
701                                   (rest[1] == 'u' || rest[1] == 'U') &&
702                                   (rest[2] == 'n' || rest[2] == 'N'))
703                        dotw = TT_SUN;
704                  break;
705                case 't': case 'T':
706                  if (dotw == TT_UNKNOWN &&
707                          (rest[1] == 'h' || rest[1] == 'H') &&
708                          (rest[2] == 'u' || rest[2] == 'U'))
709                        dotw = TT_THU;
710                  else if (dotw == TT_UNKNOWN &&
711                                   (rest[1] == 'u' || rest[1] == 'U') &&
712                                   (rest[2] == 'e' || rest[2] == 'E'))
713                        dotw = TT_TUE;
714                  break;
715                case 'u': case 'U':
716                  if (zone == TT_UNKNOWN &&
717                          (rest[1] == 't' || rest[1] == 'T') &&
718                          !(rest[2] >= 'A' && rest[2] <= 'Z') &&
719                          !(rest[2] >= 'a' && rest[2] <= 'z'))
720                        /* UT is the same as GMT but UTx is not. */
721                        zone = TT_GMT;
722                  break;
723                case 'w': case 'W':
724                  if (dotw == TT_UNKNOWN &&
725                          (rest[1] == 'e' || rest[1] == 'E') &&
726                          (rest[2] == 'd' || rest[2] == 'D'))
727                        dotw = TT_WED;
728                  break;
729
730                case '+': case '-':
731                  {
732                        const char *end;
733                        int sign;
734                        if (zone_offset != -1)
735                          {
736                                /* already got one... */
737                                rest++;
738                                break;
739                          }
740                        if (zone != TT_UNKNOWN && zone != TT_GMT)
741                          {
742                                /* GMT+0300 is legal, but PST+0300 is not. */
743                                rest++;
744                                break;
745                          }
746
747                        sign = ((*rest == '+') ? 1 : -1);
748                        rest++; /* move over sign */
749                        end = rest;
750                        while (*end >= '0' && *end <= '9')
751                          end++;
752                        if (rest == end) /* no digits here */
753                          break;
754
755                        if ((end - rest) == 4)
756                          /* offset in HHMM */
757                          zone_offset = (((((rest[0]-'0')*10) + (rest[1]-'0')) * 60) +
758                                                         (((rest[2]-'0')*10) + (rest[3]-'0')));
759                        else if ((end - rest) == 2)
760                          /* offset in hours */
761                          zone_offset = (((rest[0]-'0')*10) + (rest[1]-'0')) * 60;
762                        else if ((end - rest) == 1)
763                          /* offset in hours */
764                          zone_offset = (rest[0]-'0') * 60;
765                        else
766                          /* 3 or >4 */
767                          break;
768
769                        zone_offset *= sign;
770                        zone = TT_GMT;
771                        break;
772                  }
773
774                case '0': case '1': case '2': case '3': case '4':
775                case '5': case '6': case '7': case '8': case '9':
776                  {
777                        int tmp_hour = -1;
778                        int tmp_min = -1;
779                        int tmp_sec = -1;
780                        const char *end = rest + 1;
781                        while (*end >= '0' && *end <= '9')
782                          end++;
783
784                        /* end is now the first character after a range of digits. */
785
786                        if (*end == ':')
787                          {
788                                if (hour >= 0 && min >= 0) /* already got it */
789                                  break;
790
791                                /* We have seen "[0-9]+:", so this is probably HH:MM[:SS] */
792                                if ((end - rest) > 2)
793                                  /* it is [0-9][0-9][0-9]+: */
794                                  break;
795                                else if ((end - rest) == 2)
796                                  tmp_hour = ((rest[0]-'0')*10 +
797                                                          (rest[1]-'0'));
798                                else
799                                  tmp_hour = (rest[0]-'0');
800
801                                /* move over the colon, and parse minutes */
802
803                                rest = ++end;
804                                while (*end >= '0' && *end <= '9')
805                                  end++;
806
807                                if (end == rest)
808                                  /* no digits after first colon? */
809                                  break;
810                                else if ((end - rest) > 2)
811                                  /* it is [0-9][0-9][0-9]+: */
812                                  break;
813                                else if ((end - rest) == 2)
814                                  tmp_min = ((rest[0]-'0')*10 +
815                                                         (rest[1]-'0'));
816                                else
817                                  tmp_min = (rest[0]-'0');
818
819                                /* now go for seconds */
820                                rest = end;
821                                if (*rest == ':')
822                                  rest++;
823                                end = rest;
824                                while (*end >= '0' && *end <= '9')
825                                  end++;
826
827                                if (end == rest)
828                                  /* no digits after second colon - that's ok. */
829                                  ;
830                                else if ((end - rest) > 2)
831                                  /* it is [0-9][0-9][0-9]+: */
832                                  break;
833                                else if ((end - rest) == 2)
834                                  tmp_sec = ((rest[0]-'0')*10 +
835                                                         (rest[1]-'0'));
836                                else
837                                  tmp_sec = (rest[0]-'0');
838
839                                /* If we made it here, we've parsed hour and min,
840                                   and possibly sec, so it worked as a unit. */
841
842                                /* skip over whitespace and see if there's an AM or PM
843                                   directly following the time.
844                                 */
845                                if (tmp_hour <= 12)
846                                  {
847                                        const char *s = end;
848                                        while (*s && (*s == ' ' || *s == '\t'))
849                                          s++;
850                                        if ((s[0] == 'p' || s[0] == 'P') &&
851                                                (s[1] == 'm' || s[1] == 'M'))
852                                          /* 10:05pm == 22:05, and 12:05pm == 12:05 */
853                                          tmp_hour = (tmp_hour == 12 ? 12 : tmp_hour + 12);
854                                        else if (tmp_hour == 12 &&
855                                                         (s[0] == 'a' || s[0] == 'A') &&
856                                                         (s[1] == 'm' || s[1] == 'M'))
857                                          /* 12:05am == 00:05 */
858                                          tmp_hour = 0;
859                                  }
860
861                                hour = tmp_hour;
862                                min = tmp_min;
863                                sec = tmp_sec;
864                                rest = end;
865                                break;
866                          }
867                        else if ((*end == '/' || *end == '-') &&
868                                         end[1] >= '0' && end[1] <= '9')
869                          {
870                                /* Perhaps this is 6/16/95, 16/6/95, 6-16-95, or 16-6-95
871                                   or even 95-06-05...
872                                   #### But it doesn't handle 1995-06-22.
873                                 */
874                                int n1, n2, n3;
875                                const char *s;
876
877                                if (month != TT_UNKNOWN)
878                                  /* if we saw a month name, this can't be. */
879                                  break;
880
881                                s = rest;
882
883                                n1 = (*s++ - '0');                                /* first 1 or 2 digits */
884                                if (*s >= '0' && *s <= '9')
885                                  n1 = n1*10 + (*s++ - '0');
886
887                                if (*s != '/' && *s != '-')                /* slash */
888                                  break;
889                                s++;
890
891                                if (*s < '0' || *s > '9')                /* second 1 or 2 digits */
892                                  break;
893                                n2 = (*s++ - '0');
894                                if (*s >= '0' && *s <= '9')
895                                  n2 = n2*10 + (*s++ - '0');
896
897                                if (*s != '/' && *s != '-')                /* slash */
898                                  break;
899                                s++;
900
901                                if (*s < '0' || *s > '9')                /* third 1, 2, 4, or 5 digits */
902                                  break;
903                                n3 = (*s++ - '0');
904                                if (*s >= '0' && *s <= '9')
905                                  n3 = n3*10 + (*s++ - '0');
906
907                                if (*s >= '0' && *s <= '9')            /* optional digits 3, 4, and 5 */
908                                  {
909                                        n3 = n3*10 + (*s++ - '0');
910                                        if (*s < '0' || *s > '9')
911                                          break;
912                                        n3 = n3*10 + (*s++ - '0');
913                                        if (*s >= '0' && *s <= '9')
914                                          n3 = n3*10 + (*s++ - '0');
915                                  }
916
917                                if ((*s >= '0' && *s <= '9') ||        /* followed by non-alphanum */
918                                        (*s >= 'A' && *s <= 'Z') ||
919                                        (*s >= 'a' && *s <= 'z'))
920                                  break;
921
922                                /* Ok, we parsed three 1-2 digit numbers, with / or -
923                                   between them.  Now decide what the hell they are
924                                   (DD/MM/YY or MM/DD/YY or YY/MM/DD.)
925                                 */
926
927                                if (n1 > 31 || n1 == 0)  /* must be YY/MM/DD */
928                                  {
929                                        if (n2 > 12) break;
930                                        if (n3 > 31) break;
931                                        year = n1;
932                                        if (year < 70)
933                                            year += 2000;
934                                        else if (year < 100)
935                                            year += 1900;
936                                        month = (TIME_TOKEN)(n2 + ((int)TT_JAN) - 1);
937                                        date = n3;
938                                        rest = s;
939                                        break;
940                                  }
941
942                                if (n1 > 12 && n2 > 12)  /* illegal */
943                                  {
944                                        rest = s;
945                                        break;
946                                  }
947
948                                if (n3 < 70)
949                                    n3 += 2000;
950                                else if (n3 < 100)
951                                    n3 += 1900;
952
953                                if (n1 > 12)  /* must be DD/MM/YY */
954                                  {
955                                        date = n1;
956                                        month = (TIME_TOKEN)(n2 + ((int)TT_JAN) - 1);
957                                        year = n3;
958                                  }
959                                else                  /* assume MM/DD/YY */
960                                  {
961                                        /* #### In the ambiguous case, should we consult the
962                                           locale to find out the local default? */
963                                        month = (TIME_TOKEN)(n1 + ((int)TT_JAN) - 1);
964                                        date = n2;
965                                        year = n3;
966                                  }
967                                rest = s;
968                          }
969                        else if ((*end >= 'A' && *end <= 'Z') ||
970                                         (*end >= 'a' && *end <= 'z'))
971                          /* Digits followed by non-punctuation - what's that? */
972                          ;
973                        else if ((end - rest) == 5)                /* five digits is a year */
974                          year = (year < 0
975                                          ? ((rest[0]-'0')*10000L +
976                                                 (rest[1]-'0')*1000L +
977                                                 (rest[2]-'0')*100L +
978                                                 (rest[3]-'0')*10L +
979                                                 (rest[4]-'0'))
980                                          : year);
981                        else if ((end - rest) == 4)                /* four digits is a year */
982                          year = (year < 0
983                                          ? ((rest[0]-'0')*1000L +
984                                                 (rest[1]-'0')*100L +
985                                                 (rest[2]-'0')*10L +
986                                                 (rest[3]-'0'))
987                                          : year);
988                        else if ((end - rest) == 2)                /* two digits - date or year */
989                          {
990                                int n = ((rest[0]-'0')*10 +
991                                                 (rest[1]-'0'));
992                                /* If we don't have a date (day of the month) and we see a number
993                                     less than 32, then assume that is the date.
994
995                                         Otherwise, if we have a date and not a year, assume this is the
996                                         year.  If it is less than 70, then assume it refers to the 21st
997                                         century.  If it is two digits (>= 70), assume it refers to this
998                                         century.  Otherwise, assume it refers to an unambiguous year.
999
1000                                         The world will surely end soon.
1001                                   */
1002                                if (date < 0 && n < 32)
1003                                  date = n;
1004                                else if (year < 0)
1005                                  {
1006                                        if (n < 70)
1007                                          year = 2000 + n;
1008                                        else if (n < 100)
1009                                          year = 1900 + n;
1010                                        else
1011                                          year = n;
1012                                  }
1013                                /* else what the hell is this. */
1014                          }
1015                        else if ((end - rest) == 1)                /* one digit - date */
1016                          date = (date < 0 ? (rest[0]-'0') : date);
1017                        /* else, three or more than five digits - what's that? */
1018
1019                        break;
1020                  }
1021                }
1022
1023          /* Skip to the end of this token, whether we parsed it or not.
1024                 Tokens are delimited by whitespace, or ,;-/
1025                 But explicitly not :+-.
1026           */
1027          while (*rest &&
1028                         *rest != ' ' && *rest != '\t' &&
1029                         *rest != ',' && *rest != ';' &&
1030                         *rest != '-' && *rest != '+' &&
1031                         *rest != '/' &&
1032                         *rest != '(' && *rest != ')' && *rest != '[' && *rest != ']')
1033                rest++;
1034          /* skip over uninteresting chars. */
1035        SKIP_MORE:
1036          while (*rest &&
1037                         (*rest == ' ' || *rest == '\t' ||
1038                          *rest == ',' || *rest == ';' || *rest == '/' ||
1039                          *rest == '(' || *rest == ')' || *rest == '[' || *rest == ']'))
1040                rest++;
1041
1042          /* "-" is ignored at the beginning of a token if we have not yet
1043                 parsed a year (e.g., the second "-" in "30-AUG-1966"), or if
1044                 the character after the dash is not a digit. */
1045          if (*rest == '-' && ((rest > string && isalpha(rest[-1]) && year < 0)
1046              || rest[1] < '0' || rest[1] > '9'))
1047                {
1048                  rest++;
1049                  goto SKIP_MORE;
1050                }
1051
1052        }
1053
1054  if (zone != TT_UNKNOWN && zone_offset == -1)
1055        {
1056          switch (zone)
1057                {
1058                case TT_PST: zone_offset = -8 * 60; break;
1059                case TT_PDT: zone_offset = -8 * 60; dst_offset = 1 * 60; break;
1060                case TT_MST: zone_offset = -7 * 60; break;
1061                case TT_MDT: zone_offset = -7 * 60; dst_offset = 1 * 60; break;
1062                case TT_CST: zone_offset = -6 * 60; break;
1063                case TT_CDT: zone_offset = -6 * 60; dst_offset = 1 * 60; break;
1064                case TT_EST: zone_offset = -5 * 60; break;
1065                case TT_EDT: zone_offset = -5 * 60; dst_offset = 1 * 60; break;
1066                case TT_AST: zone_offset = -4 * 60; break;
1067                case TT_NST: zone_offset = -3 * 60 - 30; break;
1068                case TT_GMT: zone_offset =  0 * 60; break;
1069                case TT_BST: zone_offset =  0 * 60; dst_offset = 1 * 60; break;
1070                case TT_MET: zone_offset =  1 * 60; break;
1071                case TT_EET: zone_offset =  2 * 60; break;
1072                case TT_JST: zone_offset =  9 * 60; break;
1073                default:
1074                  PR_ASSERT (0);
1075                  break;
1076                }
1077        }
1078
1079  /* If we didn't find a year, month, or day-of-the-month, we can't
1080         possibly parse this, and in fact, mktime() will do something random
1081         (I'm seeing it return "Tue Feb  5 06:28:16 2036", which is no doubt
1082         a numerologically significant date... */
1083  if (month == TT_UNKNOWN || date == -1 || year == -1 || year > PR_INT16_MAX)
1084      return PR_FAILURE;
1085
1086  memset(result, 0, sizeof(*result));
1087  if (sec != -1)
1088        result->tm_sec = sec;
1089  if (min != -1)
1090        result->tm_min = min;
1091  if (hour != -1)
1092        result->tm_hour = hour;
1093  if (date != -1)
1094        result->tm_mday = date;
1095  if (month != TT_UNKNOWN)
1096        result->tm_month = (((int)month) - ((int)TT_JAN));
1097  if (year != -1)
1098        result->tm_year = year;
1099  if (dotw != TT_UNKNOWN)
1100        result->tm_wday = (((int)dotw) - ((int)TT_SUN));
1101  /*
1102   * Mainly to compute wday and yday, but normalized time is also required
1103   * by the check below that works around a Visual C++ 2005 mktime problem.
1104   */
1105  PR_NormalizeTime(result, PR_GMTParameters);
1106  /* The remaining work is to set the gmt and dst offsets in tm_params. */
1107
1108  if (zone == TT_UNKNOWN && default_to_gmt)
1109        {
1110          /* No zone was specified, so pretend the zone was GMT. */
1111          zone = TT_GMT;
1112          zone_offset = 0;
1113        }
1114
1115  if (zone_offset == -1)
1116         {
1117           /* no zone was specified, and we're to assume that everything
1118             is local. */
1119          struct tm localTime;
1120          time_t secs;
1121
1122          PR_ASSERT(result->tm_month > -1 &&
1123                    result->tm_mday > 0 &&
1124                    result->tm_hour > -1 &&
1125                    result->tm_min > -1 &&
1126                    result->tm_sec > -1);
1127
1128            /*
1129             * To obtain time_t from a tm structure representing the local
1130             * time, we call mktime().  However, we need to see if we are
1131             * on 1-Jan-1970 or before.  If we are, we can't call mktime()
1132             * because mktime() will crash on win16. In that case, we
1133             * calculate zone_offset based on the zone offset at
1134             * 00:00:00, 2 Jan 1970 GMT, and subtract zone_offset from the
1135             * date we are parsing to transform the date to GMT.  We also
1136             * do so if mktime() returns (time_t) -1 (time out of range).
1137           */
1138
1139          /* month, day, hours, mins and secs are always non-negative
1140             so we dont need to worry about them. */
1141          if(result->tm_year >= 1970)
1142                {
1143                  PRInt64 usec_per_sec;
1144
1145                  localTime.tm_sec = result->tm_sec;
1146                  localTime.tm_min = result->tm_min;
1147                  localTime.tm_hour = result->tm_hour;
1148                  localTime.tm_mday = result->tm_mday;
1149                  localTime.tm_mon = result->tm_month;
1150                  localTime.tm_year = result->tm_year - 1900;
1151                  /* Set this to -1 to tell mktime "I don't care".  If you set
1152                     it to 0 or 1, you are making assertions about whether the
1153                     date you are handing it is in daylight savings mode or not;
1154                     and if you're wrong, it will "fix" it for you. */
1155                  localTime.tm_isdst = -1;
1156
1157#if _MSC_VER == 1400  /* 1400 = Visual C++ 2005 (8.0) */
1158                  /*
1159                   * mktime will return (time_t) -1 if the input is a date
1160                   * after 23:59:59, December 31, 3000, US Pacific Time (not
1161                   * UTC as documented):
1162                   * http://msdn.microsoft.com/en-us/library/d1y53h2a(VS.80).aspx
1163                   * But if the year is 3001, mktime also invokes the invalid
1164                   * parameter handler, causing the application to crash.  This
1165                   * problem has been reported in
1166                   * http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=266036.
1167                   * We avoid this crash by not calling mktime if the date is
1168                   * out of range.  To use a simple test that works in any time
1169                   * zone, we consider year 3000 out of range as well.  (See
1170                   * bug 480740.)
1171                   */
1172                  if (result->tm_year >= 3000) {
1173                      /* Emulate what mktime would have done. */
1174                      errno = EINVAL;
1175                      secs = (time_t) -1;
1176                  } else {
1177                      secs = mktime(&localTime);
1178                  }
1179#else
1180                  secs = mktime(&localTime);
1181#endif
1182                  if (secs != (time_t) -1)
1183                    {
1184                      PRTime usecs64;
1185                      LL_I2L(usecs64, secs);
1186                      LL_I2L(usec_per_sec, PR_USEC_PER_SEC);
1187                      LL_MUL(usecs64, usecs64, usec_per_sec);
1188                      *result_imploded = usecs64;
1189                      return PR_SUCCESS;
1190                    }
1191                }
1192
1193                /* So mktime() can't handle this case.  We assume the
1194                   zone_offset for the date we are parsing is the same as
1195                   the zone offset on 00:00:00 2 Jan 1970 GMT. */
1196                secs = 86400;
1197                localtime_r(&secs, &localTime);
1198                zone_offset = localTime.tm_min
1199                              + 60 * localTime.tm_hour
1200                              + 1440 * (localTime.tm_mday - 2);
1201        }
1202
1203  result->tm_params.tp_gmt_offset = zone_offset * 60;
1204  result->tm_params.tp_dst_offset = dst_offset * 60;
1205
1206  *result_imploded = PR_ImplodeTime(result);
1207  return PR_SUCCESS;
1208}
1209