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