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