remove the CVSish $Id$ lines
[platform/upstream/curl.git] / lib / parsedate.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2009, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at http://curl.haxx.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  ***************************************************************************/
22 /*
23   A brief summary of the date string formats this parser groks:
24
25   RFC 2616 3.3.1
26
27   Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
28   Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
29   Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format
30
31   we support dates without week day name:
32
33   06 Nov 1994 08:49:37 GMT
34   06-Nov-94 08:49:37 GMT
35   Nov  6 08:49:37 1994
36
37   without the time zone:
38
39   06 Nov 1994 08:49:37
40   06-Nov-94 08:49:37
41
42   weird order:
43
44   1994 Nov 6 08:49:37  (GNU date fails)
45   GMT 08:49:37 06-Nov-94 Sunday
46   94 6 Nov 08:49:37    (GNU date fails)
47
48   time left out:
49
50   1994 Nov 6
51   06-Nov-94
52   Sun Nov 6 94
53
54   unusual separators:
55
56   1994.Nov.6
57   Sun/Nov/6/94/GMT
58
59   commonly used time zone names:
60
61   Sun, 06 Nov 1994 08:49:37 CET
62   06 Nov 1994 08:49:37 EST
63
64   time zones specified using RFC822 style:
65
66   Sun, 12 Sep 2004 15:05:58 -0700
67   Sat, 11 Sep 2004 21:32:11 +0200
68
69   compact numerical date strings:
70
71   20040912 15:05:58 -0700
72   20040911 +0200
73
74 */
75 #include "setup.h"
76 #include <stdio.h>
77 #include <ctype.h>
78 #include <string.h>
79
80 #ifdef HAVE_STDLIB_H
81 #include <stdlib.h> /* for strtol() */
82 #endif
83
84 #include <curl/curl.h>
85 #include "rawstr.h"
86 #include "parsedate.h"
87
88 const char * const Curl_wkday[] =
89 {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
90 static const char * const weekday[] =
91 { "Monday", "Tuesday", "Wednesday", "Thursday",
92   "Friday", "Saturday", "Sunday" };
93 const char * const Curl_month[]=
94 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
95   "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
96
97 struct tzinfo {
98   char name[5];
99   int offset; /* +/- in minutes */
100 };
101
102 /* Here's a bunch of frequently used time zone names. These were supported
103    by the old getdate parser. */
104 #define tDAYZONE -60       /* offset for daylight savings time */
105 static const struct tzinfo tz[]= {
106   {"GMT", 0},              /* Greenwich Mean */
107   {"UTC", 0},              /* Universal (Coordinated) */
108   {"WET", 0},              /* Western European */
109   {"BST", 0 tDAYZONE},     /* British Summer */
110   {"WAT", 60},             /* West Africa */
111   {"AST", 240},            /* Atlantic Standard */
112   {"ADT", 240 tDAYZONE},   /* Atlantic Daylight */
113   {"EST", 300},            /* Eastern Standard */
114   {"EDT", 300 tDAYZONE},   /* Eastern Daylight */
115   {"CST", 360},            /* Central Standard */
116   {"CDT", 360 tDAYZONE},   /* Central Daylight */
117   {"MST", 420},            /* Mountain Standard */
118   {"MDT", 420 tDAYZONE},   /* Mountain Daylight */
119   {"PST", 480},            /* Pacific Standard */
120   {"PDT", 480 tDAYZONE},   /* Pacific Daylight */
121   {"YST", 540},            /* Yukon Standard */
122   {"YDT", 540 tDAYZONE},   /* Yukon Daylight */
123   {"HST", 600},            /* Hawaii Standard */
124   {"HDT", 600 tDAYZONE},   /* Hawaii Daylight */
125   {"CAT", 600},            /* Central Alaska */
126   {"AHST", 600},           /* Alaska-Hawaii Standard */
127   {"NT",  660},            /* Nome */
128   {"IDLW", 720},           /* International Date Line West */
129   {"CET", -60},            /* Central European */
130   {"MET", -60},            /* Middle European */
131   {"MEWT", -60},           /* Middle European Winter */
132   {"MEST", -60 tDAYZONE},  /* Middle European Summer */
133   {"CEST", -60 tDAYZONE},  /* Central European Summer */
134   {"MESZ", -60 tDAYZONE},  /* Middle European Summer */
135   {"FWT", -60},            /* French Winter */
136   {"FST", -60 tDAYZONE},   /* French Summer */
137   {"EET", -120},           /* Eastern Europe, USSR Zone 1 */
138   {"WAST", -420},          /* West Australian Standard */
139   {"WADT", -420 tDAYZONE}, /* West Australian Daylight */
140   {"CCT", -480},           /* China Coast, USSR Zone 7 */
141   {"JST", -540},           /* Japan Standard, USSR Zone 8 */
142   {"EAST", -600},          /* Eastern Australian Standard */
143   {"EADT", -600 tDAYZONE}, /* Eastern Australian Daylight */
144   {"GST", -600},           /* Guam Standard, USSR Zone 9 */
145   {"NZT", -720},           /* New Zealand */
146   {"NZST", -720},          /* New Zealand Standard */
147   {"NZDT", -720 tDAYZONE}, /* New Zealand Daylight */
148   {"IDLE", -720},          /* International Date Line East */
149   /* Next up: Military timezone names. RFC822 allowed these, but (as noted in
150      RFC 1123) had their signs wrong. Here we use the correct signs to match
151      actual military usage.
152    */
153   {"A",  +1 * 60},         /* Alpha */
154   {"B",  +2 * 60},         /* Bravo */
155   {"C",  +3 * 60},         /* Charlie */
156   {"D",  +4 * 60},         /* Delta */
157   {"E",  +5 * 60},         /* Echo */
158   {"F",  +6 * 60},         /* Foxtrot */
159   {"G",  +7 * 60},         /* Golf */
160   {"H",  +8 * 60},         /* Hotel */
161   {"I",  +9 * 60},         /* India */
162   /* "J", Juliet is not used as a timezone, to indicate the observer's local time */
163   {"K", +10 * 60},         /* Kilo */
164   {"L", +11 * 60},         /* Lima */
165   {"M", +12 * 60},         /* Mike */
166   {"N",  -1 * 60},         /* November */
167   {"O",  -2 * 60},         /* Oscar */
168   {"P",  -3 * 60},         /* Papa */
169   {"Q",  -4 * 60},         /* Quebec */
170   {"R",  -5 * 60},         /* Romeo */
171   {"S",  -6 * 60},         /* Sierra */
172   {"T",  -7 * 60},         /* Tango */
173   {"U",  -8 * 60},         /* Uniform */
174   {"V",  -9 * 60},         /* Victor */
175   {"W", -10 * 60},         /* Whiskey */
176   {"X", -11 * 60},         /* X-ray */
177   {"Y", -12 * 60},         /* Yankee */
178   {"Z", 0},                /* Zulu, zero meridian, a.k.a. UTC */
179 };
180
181 /* returns:
182    -1 no day
183    0 monday - 6 sunday
184 */
185
186 static int checkday(const char *check, size_t len)
187 {
188   int i;
189   const char * const *what;
190   bool found= FALSE;
191   if(len > 3)
192     what = &weekday[0];
193   else
194     what = &Curl_wkday[0];
195   for(i=0; i<7; i++) {
196     if(Curl_raw_equal(check, what[0])) {
197       found=TRUE;
198       break;
199     }
200     what++;
201   }
202   return found?i:-1;
203 }
204
205 static int checkmonth(const char *check)
206 {
207   int i;
208   const char * const *what;
209   bool found= FALSE;
210
211   what = &Curl_month[0];
212   for(i=0; i<12; i++) {
213     if(Curl_raw_equal(check, what[0])) {
214       found=TRUE;
215       break;
216     }
217     what++;
218   }
219   return found?i:-1; /* return the offset or -1, no real offset is -1 */
220 }
221
222 /* return the time zone offset between GMT and the input one, in number
223    of seconds or -1 if the timezone wasn't found/legal */
224
225 static int checktz(const char *check)
226 {
227   unsigned int i;
228   const struct tzinfo *what;
229   bool found= FALSE;
230
231   what = tz;
232   for(i=0; i< sizeof(tz)/sizeof(tz[0]); i++) {
233     if(Curl_raw_equal(check, what->name)) {
234       found=TRUE;
235       break;
236     }
237     what++;
238   }
239   return found?what->offset*60:-1;
240 }
241
242 static void skip(const char **date)
243 {
244   /* skip everything that aren't letters or digits */
245   while(**date && !ISALNUM(**date))
246     (*date)++;
247 }
248
249 enum assume {
250   DATE_MDAY,
251   DATE_YEAR,
252   DATE_TIME
253 };
254
255 /* this is a clone of 'struct tm' but with all fields we don't need or use
256    cut out */
257 struct my_tm {
258   int tm_sec;
259   int tm_min;
260   int tm_hour;
261   int tm_mday;
262   int tm_mon;
263   int tm_year;
264 };
265
266 /* struct tm to time since epoch in GMT time zone.
267  * This is similar to the standard mktime function but for GMT only, and
268  * doesn't suffer from the various bugs and portability problems that
269  * some systems' implementations have.
270  */
271 static time_t my_timegm(struct my_tm *tm)
272 {
273   static const int month_days_cumulative [12] =
274     { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
275   int month, year, leap_days;
276
277   if(tm->tm_year < 70)
278     /* we don't support years before 1970 as they will cause this function
279        to return a negative value */
280     return -1;
281
282   year = tm->tm_year + 1900;
283   month = tm->tm_mon;
284   if (month < 0) {
285     year += (11 - month) / 12;
286     month = 11 - (11 - month) % 12;
287   }
288   else if (month >= 12) {
289     year -= month / 12;
290     month = month % 12;
291   }
292
293   leap_days = year - (tm->tm_mon <= 1);
294   leap_days = ((leap_days / 4) - (leap_days / 100) + (leap_days / 400)
295                - (1969 / 4) + (1969 / 100) - (1969 / 400));
296
297   return ((((time_t) (year - 1970) * 365
298             + leap_days + month_days_cumulative [month] + tm->tm_mday - 1) * 24
299            + tm->tm_hour) * 60 + tm->tm_min) * 60 + tm->tm_sec;
300 }
301
302 /*
303  * Curl_parsedate()
304  *
305  * Returns:
306  *
307  * PARSEDATE_OK     - a fine conversion
308  * PARSEDATE_FAIL   - failed to convert
309  * PARSEDATE_LATER  - time overflow at the far end of time_t
310  * PARSEDATE_SOONER - time underflow at the low end of time_t
311  */
312
313 int Curl_parsedate(const char *date, time_t *output)
314 {
315   time_t t = 0;
316   int wdaynum=-1;  /* day of the week number, 0-6 (mon-sun) */
317   int monnum=-1;   /* month of the year number, 0-11 */
318   int mdaynum=-1; /* day of month, 1 - 31 */
319   int hournum=-1;
320   int minnum=-1;
321   int secnum=-1;
322   int yearnum=-1;
323   int tzoff=-1;
324   struct my_tm tm;
325   enum assume dignext = DATE_MDAY;
326   const char *indate = date; /* save the original pointer */
327   int part = 0; /* max 6 parts */
328
329   while(*date && (part < 6)) {
330     bool found=FALSE;
331
332     skip(&date);
333
334     if(ISALPHA(*date)) {
335       /* a name coming up */
336       char buf[32]="";
337       size_t len;
338       sscanf(date, "%31[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]",
339              buf);
340       len = strlen(buf);
341
342       if(wdaynum == -1) {
343         wdaynum = checkday(buf, len);
344         if(wdaynum != -1)
345           found = TRUE;
346       }
347       if(!found && (monnum == -1)) {
348         monnum = checkmonth(buf);
349         if(monnum != -1)
350           found = TRUE;
351       }
352
353       if(!found && (tzoff == -1)) {
354         /* this just must be a time zone string */
355         tzoff = checktz(buf);
356         if(tzoff != -1)
357           found = TRUE;
358       }
359
360       if(!found)
361         return PARSEDATE_FAIL; /* bad string */
362
363       date += len;
364     }
365     else if(ISDIGIT(*date)) {
366       /* a digit */
367       int val;
368       char *end;
369       if((secnum == -1) &&
370          (3 == sscanf(date, "%02d:%02d:%02d", &hournum, &minnum, &secnum))) {
371         /* time stamp! */
372         date += 8;
373         found = TRUE;
374       }
375       else {
376         val = (int)strtol(date, &end, 10);
377
378         if((tzoff == -1) &&
379            ((end - date) == 4) &&
380            (val <= 1400) &&
381            (indate< date) &&
382            ((date[-1] == '+' || date[-1] == '-'))) {
383           /* four digits and a value less than or equal to 1400 (to take into
384              account all sorts of funny time zone diffs) and it is preceeded
385              with a plus or minus. This is a time zone indication.  1400 is
386              picked since +1300 is frequently used and +1400 is mentioned as
387              an edge number in the document "ISO C 200X Proposal: Timezone
388              Functions" at http://david.tribble.com/text/c0xtimezone.html If
389              anyone has a more authoritative source for the exact maximum time
390              zone offsets, please speak up! */
391           found = TRUE;
392           tzoff = (val/100 * 60 + val%100)*60;
393
394           /* the + and - prefix indicates the local time compared to GMT,
395              this we need ther reversed math to get what we want */
396           tzoff = date[-1]=='+'?-tzoff:tzoff;
397         }
398
399         if(((end - date) == 8) &&
400            (yearnum == -1) &&
401            (monnum == -1) &&
402            (mdaynum == -1)) {
403           /* 8 digits, no year, month or day yet. This is YYYYMMDD */
404           found = TRUE;
405           yearnum = val/10000;
406           monnum = (val%10000)/100-1; /* month is 0 - 11 */
407           mdaynum = val%100;
408         }
409
410         if(!found && (dignext == DATE_MDAY) && (mdaynum == -1)) {
411           if((val > 0) && (val<32)) {
412             mdaynum = val;
413             found = TRUE;
414           }
415           dignext = DATE_YEAR;
416         }
417
418         if(!found && (dignext == DATE_YEAR) && (yearnum == -1)) {
419           yearnum = val;
420           found = TRUE;
421           if(yearnum < 1900) {
422             if(yearnum > 70)
423               yearnum += 1900;
424             else
425               yearnum += 2000;
426           }
427           if(mdaynum == -1)
428             dignext = DATE_MDAY;
429         }
430
431         if(!found)
432           return PARSEDATE_FAIL;
433
434         date = end;
435       }
436     }
437
438     part++;
439   }
440
441   if(-1 == secnum)
442     secnum = minnum = hournum = 0; /* no time, make it zero */
443
444   if((-1 == mdaynum) ||
445      (-1 == monnum) ||
446      (-1 == yearnum))
447     /* lacks vital info, fail */
448     return PARSEDATE_FAIL;
449
450 #if SIZEOF_TIME_T < 5
451   /* 32 bit time_t can only hold dates to the beginning of 2038 */
452   if(yearnum > 2037) {
453     *output = 0x7fffffff;
454     return PARSEDATE_LATER;
455   }
456 #endif
457
458   if(yearnum < 1970) {
459     *output = 0;
460     return PARSEDATE_SOONER;
461   }
462
463   tm.tm_sec = secnum;
464   tm.tm_min = minnum;
465   tm.tm_hour = hournum;
466   tm.tm_mday = mdaynum;
467   tm.tm_mon = monnum;
468   tm.tm_year = yearnum - 1900;
469
470   /* my_timegm() returns a time_t. time_t is often 32 bits, even on many
471      architectures that feature 64 bit 'long'.
472
473      Some systems have 64 bit time_t and deal with years beyond 2038. However,
474      even on some of the systems with 64 bit time_t mktime() returns -1 for
475      dates beyond 03:14:07 UTC, January 19, 2038. (Such as AIX 5100-06)
476   */
477   t = my_timegm(&tm);
478
479   /* time zone adjust (cast t to int to compare to negative one) */
480   if(-1 != (int)t) {
481
482     /* Add the time zone diff between local time zone and GMT. */
483     long delta = (long)(tzoff!=-1?tzoff:0);
484
485     if((delta>0) && (t + delta < t))
486       return -1; /* time_t overflow */
487
488     t += delta;
489   }
490
491   *output = t;
492
493   return PARSEDATE_OK;
494 }
495
496 time_t curl_getdate(const char *p, const time_t *now)
497 {
498   time_t parsed;
499   int rc = Curl_parsedate(p, &parsed);
500   (void)now; /* legacy argument from the past that we ignore */
501
502   switch(rc) {
503   case PARSEDATE_OK:
504   case PARSEDATE_LATER:
505   case PARSEDATE_SOONER:
506     return parsed;
507   }
508   /* everything else is fail */
509   return -1;
510 }