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