]> diplodocus.org Git - nmh/blob - sbr/datetime.c
71a21f99f6d56eaec53df24c51e6def9c51af8b2
[nmh] / sbr / datetime.c
1 /* datetime.c -- functions for manipulating RFC 5545 date-time values
2 *
3 * This code is Copyright (c) 2014, by the authors of nmh.
4 * See the COPYRIGHT file in the root directory of the nmh
5 * distribution for complete copyright information.
6 */
7
8 #include "h/mh.h"
9 #include "dtime.h"
10 #include "error.h"
11 #include "h/icalendar.h"
12 #include "h/fmt_scan.h"
13 #include "h/tws.h"
14 #include "h/utils.h"
15 #include "unquote.h"
16
17 /*
18 * This doesn't try to support all of the myriad date-time formats
19 * allowed by RFC 5545. It is only used for viewing date-times,
20 * so that shouldn't be a problem: if a particular format can't
21 * be handled by this code, just present it to the user in its
22 * original form.
23 *
24 * And, this assumes a valid iCalendar input file. E.g, it
25 * doesn't check that each BEGIN has a matching END and vice
26 * versa. That should be done in the parser, though it currently
27 * isn't.
28 */
29
30 typedef struct tzparams {
31 /* Pointers to values in parse tree.
32 * TZOFFSETFROM is used to calculate the absolute time at which
33 * the transition to a given observance takes place.
34 * TZOFFSETTO is the timezone offset from UTC. Both are in HHmm
35 * format. */
36 char *offsetfrom, *offsetto;
37 const char *dtstart;
38 const char *rrule;
39
40 /* This is only used to make sure that timezone applies. And not
41 always, because if the timezone DTSTART is before the epoch, we
42 don't try to compare to it. */
43 time_t start_dt; /* in seconds since epoch */
44 } tzparams;
45
46 struct tzdesc {
47 char *tzid;
48
49 /* The following are translations of the pieces of RRULE and DTSTART
50 into seconds from beginning of year. */
51 tzparams standard_params;
52 tzparams daylight_params;
53
54 struct tzdesc *next;
55 };
56
57 /*
58 * Parse a datetime of the form YYYYMMDDThhmmss and a string
59 * representation of the timezone in units of [+-]hhmm and load the
60 * struct tws.
61 */
62 static int
63 parse_datetime (const char *datetime, const char *zone, bool dst,
64 struct tws *tws)
65 {
66 char utc_indicator;
67 bool form_1;
68 int items_matched;
69
70 ZERO(tws);
71 items_matched =
72 sscanf (datetime, "%4d%2d%2dT%2d%2d%2d%c",
73 &tws->tw_year, &tws->tw_mon, &tws->tw_mday,
74 &tws->tw_hour, &tws->tw_min, &tws->tw_sec,
75 &utc_indicator);
76 tws->tw_flags = TW_NULL;
77
78 form_1 = false;
79 if (items_matched == 7) {
80 /* The 'Z' must be capital according to RFC 5545 Sec. 3.3.5. */
81 if (utc_indicator != 'Z') {
82 inform("%s has invalid timezone-indicator byte: %#x",
83 datetime, utc_indicator);
84 return NOTOK;
85 }
86 } else if (zone == NULL) {
87 form_1 = true;
88 }
89
90 /* items_matched of 3 is for, e.g., 20151230. Assume that means
91 the entire day. The time fields of the tws struct were
92 initialized to 0 by the memset() above. */
93 if (items_matched >= 6 || items_matched == 3) {
94 /* struct tws defines tw_mon over [0, 11]. */
95 --tws->tw_mon;
96
97 /* Fill out rest of tws, i.e., its tw_wday and tw_flags. */
98 set_dotw (tws);
99 /* set_dotw() sets TW_SIMP. Replace that with TW_SEXP so that
100 dasctime() outputs the dotw before the date instead of after. */
101 tws->tw_flags &= ~TW_SDAY;
102 tws->tw_flags |= TW_SEXP;
103
104 /* For the call to dmktime():
105 - don't need tw_yday
106 - tw_clock must be 0 on entry, and is set by dmktime()
107 - the only flag in tw_flags used is TW_DST
108 */
109 tws->tw_yday = tws->tw_clock = 0;
110 if (zone) {
111 int offset = atoi(zone);
112 tws->tw_zone = 60 * (offset / 100) + offset % 100;
113 } else
114 tws->tw_zone = 0;
115 if (dst) {
116 tws->tw_zone -= 60; /* per dlocaltime() */
117 tws->tw_flags |= TW_DST;
118 }
119 /* dmktime() just sets tws->tw_clock. */
120 (void) dmktime (tws);
121
122 if (! form_1) {
123 /* Set TW_SZEXP so that dasctime outputs timezone, except
124 with local time (Form #1). */
125 tws->tw_flags |= TW_SZEXP;
126
127 /* Convert UTC time to time in local timezone. However,
128 don't try for years before 1970 because dlocatime()
129 doesn't handle them well. dlocaltime() will succeed if
130 tws->tw_clock is nonzero. */
131 if (tws->tw_year >= 1970 && tws->tw_clock > 0) {
132 const int was_dst = tws->tw_flags & TW_DST;
133
134 *tws = *dlocaltime (&tws->tw_clock);
135 if (was_dst && ! (tws->tw_flags & TW_DST)) {
136 /* dlocaltime() changed the DST flag from 1 to 0,
137 which means the time is in the hour (assumed to
138 be one hour) that is lost in the transition to
139 DST. So per RFC 5545 Sec. 3.3.5, "the
140 DATE-TIME value is interpreted using the UTC
141 offset before the gap in local times." In
142 other words, add an hour to it.
143 No adjustment is necessary for the transition
144 from DST to standard time, because dasctime()
145 shows the first occurrence of the time. */
146 tws->tw_clock += 3600;
147 *tws = *dlocaltime (&tws->tw_clock);
148 }
149 }
150 }
151
152 return OK;
153 }
154
155 return NOTOK;
156 }
157
158 tzdesc_t
159 load_timezones (const contentline *clines)
160 {
161 tzdesc_t timezones = NULL, timezone = NULL;
162 bool in_vtimezone, in_standard, in_daylight;
163 tzparams *params = NULL;
164 const contentline *node;
165
166 /* Interpret each VTIMEZONE section. */
167 in_vtimezone = in_standard = in_daylight = false;
168 for (node = clines; node; node = node->next) {
169 /* node->name will be NULL if the line was "deleted". */
170 if (! node->name) { continue; }
171
172 if (in_daylight || in_standard) {
173 if (! strcasecmp ("END", node->name) &&
174 ((in_standard && ! strcasecmp ("STANDARD", node->value)) ||
175 (in_daylight && ! strcasecmp ("DAYLIGHT", node->value)))) {
176 struct tws tws;
177
178 if (in_standard) { in_standard = false; }
179 else if (in_daylight) { in_daylight = false; }
180
181 if (parse_datetime(params->dtstart, params->offsetfrom,
182 in_daylight, &tws) != OK) {
183 inform("failed to parse start time %s for %s",
184 params->dtstart,
185 in_daylight ? "daylight" : "standard");
186 return NULL;
187 }
188
189 if (tws.tw_year >= 1970) {
190 /* dmktime() falls apart for, e.g., the year 1601. */
191 params->start_dt = tws.tw_clock;
192 }
193 params = NULL;
194 } else if (! strcasecmp ("DTSTART", node->name)) {
195 /* Save DTSTART for use after getting TZOFFSETFROM. */
196 params->dtstart = node->value;
197 } else if (! strcasecmp ("TZOFFSETFROM", node->name)) {
198 params->offsetfrom = node->value;
199 } else if (! strcasecmp ("TZOFFSETTO", node->name)) {
200 params->offsetto = node->value;
201 } else if (! strcasecmp ("RRULE", node->name)) {
202 params->rrule = node->value;
203 }
204 } else if (in_vtimezone) {
205 if (! strcasecmp ("END", node->name) &&
206 ! strcasecmp ("VTIMEZONE", node->value)) {
207 in_vtimezone = false;
208 } else if (! strcasecmp ("BEGIN", node->name) &&
209 ! strcasecmp ("STANDARD", node->value)) {
210 in_standard = true;
211 params = &timezone->standard_params;
212 } else if (! strcasecmp ("BEGIN", node->name) &&
213 ! strcasecmp ("DAYLIGHT", node->value)) {
214 in_daylight = true;
215 params = &timezone->daylight_params;
216 } else if (! strcasecmp ("TZID", node->name)) {
217 /* See comment below in format_datetime() about removing any enclosing quotes from a
218 timezone identifier. */
219 char *buf = mh_xmalloc(strlen(node->value) + 1);
220 unquote_string(node->value, buf);
221 timezone->tzid = buf;
222 }
223 } else {
224 if (! strcasecmp ("BEGIN", node->name) &&
225 ! strcasecmp ("VTIMEZONE", node->value)) {
226
227 in_vtimezone = true;
228 NEW0(timezone);
229 if (timezones) {
230 tzdesc_t t;
231
232 for (t = timezones; t && t->next; t = t->next) { continue; }
233 /* The loop terminated at, not after, the last
234 timezones node. */
235 t->next = timezone;
236 } else {
237 timezones = timezone;
238 }
239 }
240 }
241 }
242
243 return timezones;
244 }
245
246 void
247 free_timezones (tzdesc_t timezone)
248 {
249 tzdesc_t next;
250
251 for ( ; timezone; timezone = next) {
252 free (timezone->tzid);
253 next = timezone->next;
254 free (timezone);
255 }
256 }
257
258 /*
259 * Convert time to local timezone, accounting for daylight saving time:
260 * - Detect which type of datetime the node contains:
261 * Form #1: DATE WITH LOCAL TIME
262 * Form #2: DATE WITH UTC TIME
263 * Form #3: DATE WITH LOCAL TIME AND TIME ZONE REFERENCE
264 * - Convert value to local time in seconds since epoch.
265 * - If there's a DST in the timezone, convert its start and end
266 * date-times to local time in seconds, also. Then determine
267 * if the value is between them, and therefore DST. Otherwise, it's
268 * not.
269 * - Format the time value.
270 */
271
272 /*
273 * Given a recurrence rule and year, calculate its time in seconds
274 * from 01 January UTC of the year.
275 */
276 time_t
277 rrule_clock (const char *rrule, const char *starttime, const char *zone,
278 unsigned int year)
279 {
280 time_t clock = 0;
281
282 if (nmh_strcasestr (rrule, "FREQ=YEARLY;INTERVAL=1") ||
283 (nmh_strcasestr (rrule, "FREQ=YEARLY") && nmh_strcasestr(rrule, "INTERVAL") == NULL)) {
284 struct tws *tws;
285 const char *cp;
286 int wday = -1, month = -1;
287 int specific_day = 1; /* BYDAY integer (prefix) */
288 char buf[32];
289 int day;
290
291 if ((cp = nmh_strcasestr (rrule, "BYDAY="))) {
292 cp += 6;
293 /* BYDAY integers must be ASCII. */
294 if (*cp == '+') { ++cp; } /* +n specific day; don't support '-' */
295 else if (*cp == '-') { goto fail; }
296
297 if (isdigit ((unsigned char) *cp)) { specific_day = *cp++ - 0x30; }
298
299 if (! strncasecmp (cp, "SU", 2)) { wday = 0; }
300 else if (! strncasecmp (cp, "MO", 2)) { wday = 1; }
301 else if (! strncasecmp (cp, "TU", 2)) { wday = 2; }
302 else if (! strncasecmp (cp, "WE", 2)) { wday = 3; }
303 else if (! strncasecmp (cp, "TH", 2)) { wday = 4; }
304 else if (! strncasecmp (cp, "FR", 2)) { wday = 5; }
305 else if (! strncasecmp (cp, "SA", 2)) { wday = 6; }
306 }
307 if ((cp = nmh_strcasestr (rrule, "BYMONTH="))) {
308 month = atoi (cp + 8);
309 }
310
311 for (day = 1; day <= 7; ++day) {
312 /* E.g, 11-01-2014 02:00:00-0400 */
313 snprintf (buf, sizeof buf, "%02d-%02d-%04u %.2s:%.2s:%.2s%s",
314 month, day + 7 * (specific_day-1), year,
315 starttime, starttime + 2, starttime + 4,
316 zone ? zone : "0000");
317 if ((tws = dparsetime (buf))) {
318 if (! (tws->tw_flags & (TW_SEXP|TW_SIMP))) { set_dotw (tws); }
319
320 if (tws->tw_wday == wday) {
321 /* Found the day specified in the RRULE. */
322 break;
323 }
324 }
325 }
326
327 if (day <= 7) {
328 clock = tws->tw_clock;
329 }
330 }
331
332 fail:
333 if (clock == 0) {
334 inform("Unsupported RRULE format: %s, assume local timezone, continuing...",
335 rrule);
336 }
337
338 return clock;
339 }
340
341 char *
342 format_datetime (tzdesc_t timezones, const contentline *node)
343 {
344 param_list *p;
345 char *dt_timezone = NULL;
346 int dst = 0;
347 struct tws tws[2]; /* [standard, daylight] */
348 tzdesc_t tz;
349 char *tp_std, *tp_dst, *tp_dt;
350
351 /* Extract the timezone, if specified (RFC 5545 Sec. 3.3.5 Form #3). */
352 for (p = node->params; p && p->param_name; p = p->next) {
353 if (! strcasecmp (p->param_name, "TZID") && p->values) {
354 /* Remove any enclosing quotes from the timezone identifier. I don't believe that it's
355 legal for it to be quoted, according to RFC 5545 ยง 3.2.19:
356 tzidparam = "TZID" "=" [tzidprefix] paramtext
357 tzidprefix = "/"
358 where paramtext includes SAFE-CHAR, which specifically excludes DQUOTE. But we'll
359 be generous and strip quotes. */
360 char *buf = mh_xmalloc(strlen(p->values->value) + 1);
361 unquote_string(p->values->value, buf);
362 dt_timezone = buf;
363 break;
364 }
365 }
366
367 if (! dt_timezone) {
368 /* Form #1: DATE WITH LOCAL TIME, i.e., no time zone, or
369 Form #2: DATE WITH UTC TIME */
370 if (parse_datetime(node->value, NULL, false, &tws[0]) != OK) {
371 inform("unable to parse datetime %s", node->value);
372 return NULL;
373 }
374 return strdup (dasctime (&tws[0], 0));
375 }
376
377 /*
378 * must be
379 * Form #3: DATE WITH LOCAL TIME AND TIME ZONE REFERENCE
380 */
381
382 /* Find the corresponding tzdesc. */
383 for (tz = timezones; dt_timezone && tz; tz = tz->next) {
384 /* Property parameter values are case insensitive (RFC 5545
385 Sec. 2) and time zone identifiers are property parameters
386 (RFC 5545 Sec. 3.8.2.4), though it would seem odd to use
387 different case in the same file for identifiers that are
388 supposed to be the same. */
389 if (tz->tzid && ! strcasecmp (dt_timezone, tz->tzid)) { break; }
390 }
391
392 if (!tz) {
393 inform("did not find VTIMEZONE section for %s", dt_timezone);
394 free(dt_timezone);
395 return NULL;
396 }
397 free(dt_timezone);
398
399 /* Determine if it's Daylight Saving. */
400 tp_std = strchr (tz->standard_params.dtstart, 'T');
401 tp_dt = strchr (node->value, 'T');
402
403 if (tz->daylight_params.dtstart) {
404 tp_dst = strchr (tz->daylight_params.dtstart, 'T');
405 } else {
406 /* No DAYLIGHT section. */
407 tp_dst = NULL;
408 dst = 0;
409 }
410
411 if (tp_std && tp_dt) {
412 time_t transition[2] = { 0, 0 }; /* [standard, daylight] */
413 time_t dt[2]; /* [standard, daylight] */
414 unsigned int year;
415 char buf[5];
416
417 /* Datetime is form YYYYMMDDThhmmss. Extract year. */
418 memcpy (buf, node->value, sizeof buf - 1);
419 buf[sizeof buf - 1] = '\0';
420 year = atoi (buf);
421
422 if (tz->standard_params.rrule) {
423 /* +1 to skip the T before the time */
424 transition[0] =
425 rrule_clock (tz->standard_params.rrule, tp_std + 1,
426 tz->standard_params.offsetfrom, year);
427 }
428 if (tp_dst && tz->daylight_params.rrule) {
429 /* +1 to skip the T before the time */
430 transition[1] =
431 rrule_clock (tz->daylight_params.rrule, tp_dst + 1,
432 tz->daylight_params.offsetfrom, year);
433 }
434
435 if (transition[0] < transition[1]) {
436 inform("format_datetime() requires that daylight "
437 "saving time transition precede standard time "
438 "transition");
439 return NULL;
440 }
441
442 if (parse_datetime(node->value, tz->standard_params.offsetto,
443 false, &tws[0]) != OK) {
444 inform("unable to parse datetime %s", node->value);
445 return NULL;
446 }
447 dt[0] = tws[0].tw_clock;
448
449 if (tp_dst) {
450 if (dt[0] < transition[1]) {
451 dst = 0;
452 } else {
453 if (parse_datetime(node->value,
454 tz->daylight_params.offsetto, true, &tws[1]) != OK) {
455 inform("unable to parse datetime %s", node->value);
456 return NULL;
457 }
458 dt[1] = tws[1].tw_clock;
459 dst = dt[1] <= transition[0];
460 }
461 }
462
463 if (dst) {
464 if (tz->daylight_params.start_dt > 0 &&
465 dt[dst] < tz->daylight_params.start_dt) {
466 inform("date-time of %s is before VTIMEZONE start "
467 "of %s", node->value,
468 tz->daylight_params.dtstart);
469 return NULL;
470 }
471 } else {
472 if (tz->standard_params.start_dt > 0 &&
473 dt[dst] < tz->standard_params.start_dt) {
474 inform("date-time of %s is before VTIMEZONE start "
475 "of %s", node->value,
476 tz->standard_params.dtstart);
477 return NULL;
478 }
479 }
480 } else {
481 if (! tp_std) {
482 inform("unsupported date-time format: %s",
483 tz->standard_params.dtstart);
484 return NULL;
485 }
486 if (! tp_dt) {
487 inform("unsupported date-time format: %s", node->value);
488 return NULL;
489 }
490 }
491
492 return strdup (dasctime (&tws[dst], 0));
493 }