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