1/*	$OpenBSD: strftime.c,v 1.33 2020/07/16 20:08:12 millert Exp $ */
2/*
3** Copyright (c) 1989, 1993
4**	The Regents of the University of California.  All rights reserved.
5**
6** Redistribution and use in source and binary forms, with or without
7** modification, are permitted provided that the following conditions
8** are met:
9** 1. Redistributions of source code must retain the above copyright
10**    notice, this list of conditions and the following disclaimer.
11** 2. Redistributions in binary form must reproduce the above copyright
12**    notice, this list of conditions and the following disclaimer in the
13**    documentation and/or other materials provided with the distribution.
14** 3. Neither the name of the University nor the names of its contributors
15**    may be used to endorse or promote products derived from this software
16**    without specific prior written permission.
17**
18** THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
19** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21** ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
22** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24** OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25** HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26** LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27** OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28** SUCH DAMAGE.
29*/
30
31#include <fcntl.h>
32#include <stdio.h>
33
34#include "private.h"
35#include "tzfile.h"
36
37struct lc_time_T {
38	const char *	mon[MONSPERYEAR];
39	const char *	month[MONSPERYEAR];
40	const char *	wday[DAYSPERWEEK];
41	const char *	weekday[DAYSPERWEEK];
42	const char *	X_fmt;
43	const char *	x_fmt;
44	const char *	c_fmt;
45	const char *	am;
46	const char *	pm;
47	const char *	date_fmt;
48};
49
50#define Locale	(&C_time_locale)
51static const struct lc_time_T	C_time_locale = {
52	{
53		"Jan", "Feb", "Mar", "Apr", "May", "Jun",
54		"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
55	}, {
56		"January", "February", "March", "April", "May", "June",
57		"July", "August", "September", "October", "November", "December"
58	}, {
59		"Sun", "Mon", "Tue", "Wed",
60		"Thu", "Fri", "Sat"
61	}, {
62		"Sunday", "Monday", "Tuesday", "Wednesday",
63		"Thursday", "Friday", "Saturday"
64	},
65
66	/* X_fmt */
67	"%H:%M:%S",
68
69	/*
70	** x_fmt
71	** C99 requires this format.
72	** Using just numbers (as here) makes Quakers happier;
73	** it's also compatible with SVR4.
74	*/
75	"%m/%d/%y",
76
77	/*
78	** c_fmt
79	** C99 requires this format.
80	** Previously this code used "%D %X", but we now conform to C99.
81	** Note that
82	**	"%a %b %d %H:%M:%S %Y"
83	** is used by Solaris 2.3.
84	*/
85	"%a %b %e %T %Y",
86
87	/* am */
88	"AM",
89
90	/* pm */
91	"PM",
92
93	/* date_fmt */
94	"%a %b %e %H:%M:%S %Z %Y"
95};
96
97static char *	_add(const char *, char *, const char *);
98static char *	_conv(int, const char *, char *, const char *);
99static char *	_fmt(const char *, const struct tm *, char *, const char *,
100			int *);
101static char *	_yconv(int, int, int, int, char *, const char *);
102
103extern char *	tzname[];
104
105#define IN_NONE	0
106#define IN_SOME	1
107#define IN_THIS	2
108#define IN_ALL	3
109
110size_t
111strftime(char *s, size_t maxsize, const char *format, const struct tm *t)
112{
113	char *	p;
114	int	warn;
115
116	tzset();
117	warn = IN_NONE;
118	p = _fmt(((format == NULL) ? "%c" : format), t, s, s + maxsize, &warn);
119	if (p == s + maxsize) {
120		if (maxsize > 0)
121			s[maxsize - 1] = '\0';
122		return 0;
123	}
124	*p = '\0';
125	return p - s;
126}
127DEF_STRONG(strftime);
128
129static char *
130_fmt(const char *format, const struct tm *t, char *pt, const char *ptlim, int *warnp)
131{
132	for ( ; *format; ++format) {
133		if (*format == '%') {
134label:
135			switch (*++format) {
136			case '\0':
137				--format;
138				break;
139			case 'A':
140				pt = _add((t->tm_wday < 0 ||
141					t->tm_wday >= DAYSPERWEEK) ?
142					"?" : Locale->weekday[t->tm_wday],
143					pt, ptlim);
144				continue;
145			case 'a':
146				pt = _add((t->tm_wday < 0 ||
147					t->tm_wday >= DAYSPERWEEK) ?
148					"?" : Locale->wday[t->tm_wday],
149					pt, ptlim);
150				continue;
151			case 'B':
152				pt = _add((t->tm_mon < 0 ||
153					t->tm_mon >= MONSPERYEAR) ?
154					"?" : Locale->month[t->tm_mon],
155					pt, ptlim);
156				continue;
157			case 'b':
158			case 'h':
159				pt = _add((t->tm_mon < 0 ||
160					t->tm_mon >= MONSPERYEAR) ?
161					"?" : Locale->mon[t->tm_mon],
162					pt, ptlim);
163				continue;
164			case 'C':
165				/*
166				** %C used to do a...
167				**	_fmt("%a %b %e %X %Y", t);
168				** ...whereas now POSIX 1003.2 calls for
169				** something completely different.
170				** (ado, 1993-05-24)
171				*/
172				pt = _yconv(t->tm_year, TM_YEAR_BASE, 1, 0,
173					pt, ptlim);
174				continue;
175			case 'c':
176				{
177				int warn2 = IN_SOME;
178
179				pt = _fmt(Locale->c_fmt, t, pt, ptlim, &warn2);
180				if (warn2 == IN_ALL)
181					warn2 = IN_THIS;
182				if (warn2 > *warnp)
183					*warnp = warn2;
184				}
185				continue;
186			case 'D':
187				pt = _fmt("%m/%d/%y", t, pt, ptlim, warnp);
188				continue;
189			case 'd':
190				pt = _conv(t->tm_mday, "%02d", pt, ptlim);
191				continue;
192			case 'E':
193			case 'O':
194				/*
195				** C99 locale modifiers.
196				** The sequences
197				**	%Ec %EC %Ex %EX %Ey %EY
198				**	%Od %oe %OH %OI %Om %OM
199				**	%OS %Ou %OU %OV %Ow %OW %Oy
200				** are supposed to provide alternate
201				** representations.
202				*/
203				goto label;
204			case 'e':
205				pt = _conv(t->tm_mday, "%2d", pt, ptlim);
206				continue;
207			case 'F':
208				pt = _fmt("%Y-%m-%d", t, pt, ptlim, warnp);
209				continue;
210			case 'H':
211				pt = _conv(t->tm_hour, "%02d", pt, ptlim);
212				continue;
213			case 'I':
214				pt = _conv((t->tm_hour % 12) ?
215					(t->tm_hour % 12) : 12,
216					"%02d", pt, ptlim);
217				continue;
218			case 'j':
219				pt = _conv(t->tm_yday + 1, "%03d", pt, ptlim);
220				continue;
221			case 'k':
222				/*
223				** This used to be...
224				**	_conv(t->tm_hour % 12 ?
225				**		t->tm_hour % 12 : 12, 2, ' ');
226				** ...and has been changed to the below to
227				** match SunOS 4.1.1 and Arnold Robbins'
228				** strftime version 3.0. That is, "%k" and
229				** "%l" have been swapped.
230				** (ado, 1993-05-24)
231				*/
232				pt = _conv(t->tm_hour, "%2d", pt, ptlim);
233				continue;
234#ifdef KITCHEN_SINK
235			case 'K':
236				/*
237				** After all this time, still unclaimed!
238				*/
239				pt = _add("kitchen sink", pt, ptlim);
240				continue;
241#endif /* defined KITCHEN_SINK */
242			case 'l':
243				/*
244				** This used to be...
245				**	_conv(t->tm_hour, 2, ' ');
246				** ...and has been changed to the below to
247				** match SunOS 4.1.1 and Arnold Robbin's
248				** strftime version 3.0. That is, "%k" and
249				** "%l" have been swapped.
250				** (ado, 1993-05-24)
251				*/
252				pt = _conv((t->tm_hour % 12) ?
253					(t->tm_hour % 12) : 12,
254					"%2d", pt, ptlim);
255				continue;
256			case 'M':
257				pt = _conv(t->tm_min, "%02d", pt, ptlim);
258				continue;
259			case 'm':
260				pt = _conv(t->tm_mon + 1, "%02d", pt, ptlim);
261				continue;
262			case 'n':
263				pt = _add("\n", pt, ptlim);
264				continue;
265			case 'p':
266				pt = _add((t->tm_hour >= (HOURSPERDAY / 2)) ?
267					Locale->pm :
268					Locale->am,
269					pt, ptlim);
270				continue;
271			case 'R':
272				pt = _fmt("%H:%M", t, pt, ptlim, warnp);
273				continue;
274			case 'r':
275				pt = _fmt("%I:%M:%S %p", t, pt, ptlim, warnp);
276				continue;
277			case 'S':
278				pt = _conv(t->tm_sec, "%02d", pt, ptlim);
279				continue;
280			case 's':
281				{
282					struct tm	tm;
283					char		buf[INT_STRLEN_MAXIMUM(
284								time_t) + 1];
285					time_t		mkt;
286
287					tm = *t;
288					mkt = mktime(&tm);
289					(void) snprintf(buf, sizeof buf,
290					    "%ld", (long) mkt);
291					pt = _add(buf, pt, ptlim);
292				}
293				continue;
294			case 'T':
295				pt = _fmt("%H:%M:%S", t, pt, ptlim, warnp);
296				continue;
297			case 't':
298				pt = _add("\t", pt, ptlim);
299				continue;
300			case 'U':
301				pt = _conv((t->tm_yday + DAYSPERWEEK -
302					t->tm_wday) / DAYSPERWEEK,
303					"%02d", pt, ptlim);
304				continue;
305			case 'u':
306				/*
307				** From Arnold Robbins' strftime version 3.0:
308				** "ISO 8601: Weekday as a decimal number
309				** [1 (Monday) - 7]"
310				** (ado, 1993-05-24)
311				*/
312				pt = _conv((t->tm_wday == 0) ?
313					DAYSPERWEEK : t->tm_wday,
314					"%d", pt, ptlim);
315				continue;
316			case 'V':	/* ISO 8601 week number */
317			case 'G':	/* ISO 8601 year (four digits) */
318			case 'g':	/* ISO 8601 year (two digits) */
319/*
320** From Arnold Robbins' strftime version 3.0: "the week number of the
321** year (the first Monday as the first day of week 1) as a decimal number
322** (01-53)."
323** (ado, 1993-05-24)
324**
325** From "http://www.ft.uni-erlangen.de/~mskuhn/iso-time.html" by Markus Kuhn:
326** "Week 01 of a year is per definition the first week which has the
327** Thursday in this year, which is equivalent to the week which contains
328** the fourth day of January. In other words, the first week of a new year
329** is the week which has the majority of its days in the new year. Week 01
330** might also contain days from the previous year and the week before week
331** 01 of a year is the last week (52 or 53) of the previous year even if
332** it contains days from the new year. A week starts with Monday (day 1)
333** and ends with Sunday (day 7). For example, the first week of the year
334** 1997 lasts from 1996-12-30 to 1997-01-05..."
335** (ado, 1996-01-02)
336*/
337				{
338					int	year;
339					int	base;
340					int	yday;
341					int	wday;
342					int	w;
343
344					year = t->tm_year;
345					base = TM_YEAR_BASE;
346					yday = t->tm_yday;
347					wday = t->tm_wday;
348					for ( ; ; ) {
349						int	len;
350						int	bot;
351						int	top;
352
353						len = isleap_sum(year, base) ?
354							DAYSPERLYEAR :
355							DAYSPERNYEAR;
356						/*
357						** What yday (-3 ... 3) does
358						** the ISO year begin on?
359						*/
360						bot = ((yday + 11 - wday) %
361							DAYSPERWEEK) - 3;
362						/*
363						** What yday does the NEXT
364						** ISO year begin on?
365						*/
366						top = bot -
367							(len % DAYSPERWEEK);
368						if (top < -3)
369							top += DAYSPERWEEK;
370						top += len;
371						if (yday >= top) {
372							++base;
373							w = 1;
374							break;
375						}
376						if (yday >= bot) {
377							w = 1 + ((yday - bot) /
378								DAYSPERWEEK);
379							break;
380						}
381						--base;
382						yday += isleap_sum(year, base) ?
383							DAYSPERLYEAR :
384							DAYSPERNYEAR;
385					}
386#ifdef XPG4_1994_04_09
387					if ((w == 52 &&
388						t->tm_mon == TM_JANUARY) ||
389						(w == 1 &&
390						t->tm_mon == TM_DECEMBER))
391							w = 53;
392#endif /* defined XPG4_1994_04_09 */
393					if (*format == 'V')
394						pt = _conv(w, "%02d",
395							pt, ptlim);
396					else if (*format == 'g') {
397						*warnp = IN_ALL;
398						pt = _yconv(year, base, 0, 1,
399							pt, ptlim);
400					} else	pt = _yconv(year, base, 1, 1,
401							pt, ptlim);
402				}
403				continue;
404			case 'v':
405				/*
406				** From Arnold Robbins' strftime version 3.0:
407				** "date as dd-bbb-YYYY"
408				** (ado, 1993-05-24)
409				*/
410				pt = _fmt("%e-%b-%Y", t, pt, ptlim, warnp);
411				continue;
412			case 'W':
413				pt = _conv((t->tm_yday + DAYSPERWEEK -
414					(t->tm_wday ?
415					(t->tm_wday - 1) :
416					(DAYSPERWEEK - 1))) / DAYSPERWEEK,
417					"%02d", pt, ptlim);
418				continue;
419			case 'w':
420				pt = _conv(t->tm_wday, "%d", pt, ptlim);
421				continue;
422			case 'X':
423				pt = _fmt(Locale->X_fmt, t, pt, ptlim, warnp);
424				continue;
425			case 'x':
426				{
427				int	warn2 = IN_SOME;
428
429				pt = _fmt(Locale->x_fmt, t, pt, ptlim, &warn2);
430				if (warn2 == IN_ALL)
431					warn2 = IN_THIS;
432				if (warn2 > *warnp)
433					*warnp = warn2;
434				}
435				continue;
436			case 'y':
437				*warnp = IN_ALL;
438				pt = _yconv(t->tm_year, TM_YEAR_BASE, 0, 1,
439					pt, ptlim);
440				continue;
441			case 'Y':
442				pt = _yconv(t->tm_year, TM_YEAR_BASE, 1, 1,
443					pt, ptlim);
444				continue;
445			case 'Z':
446				if (t->tm_zone != NULL)
447					pt = _add(t->tm_zone, pt, ptlim);
448				else if (t->tm_isdst >= 0)
449					pt = _add(tzname[t->tm_isdst != 0],
450						pt, ptlim);
451				/*
452				** C99 says that %Z must be replaced by the
453				** empty string if the time zone is not
454				** determinable.
455				*/
456				continue;
457			case 'z':
458				{
459				int		diff;
460				char const *	sign;
461
462				if (t->tm_isdst < 0)
463					continue;
464				diff = t->tm_gmtoff;
465				if (diff < 0) {
466					sign = "-";
467					diff = -diff;
468				} else	sign = "+";
469				pt = _add(sign, pt, ptlim);
470				diff /= SECSPERMIN;
471				diff = (diff / MINSPERHOUR) * 100 +
472					(diff % MINSPERHOUR);
473				pt = _conv(diff, "%04d", pt, ptlim);
474				}
475				continue;
476			case '+':
477				pt = _fmt(Locale->date_fmt, t, pt, ptlim,
478					warnp);
479				continue;
480			case '%':
481			/*
482			** X311J/88-090 (4.12.3.5): if conversion char is
483			** undefined, behavior is undefined. Print out the
484			** character itself as printf(3) also does.
485			*/
486			default:
487				break;
488			}
489		}
490		if (pt == ptlim)
491			break;
492		*pt++ = *format;
493	}
494	return pt;
495}
496
497static char *
498_conv(int n, const char *format, char *pt, const char *ptlim)
499{
500	char	buf[INT_STRLEN_MAXIMUM(int) + 1];
501
502	(void) snprintf(buf, sizeof buf, format, n);
503	return _add(buf, pt, ptlim);
504}
505
506static char *
507_add(const char *str, char *pt, const char *ptlim)
508{
509	while (pt < ptlim && (*pt = *str++) != '\0')
510		++pt;
511	return pt;
512}
513
514/*
515** POSIX and the C Standard are unclear or inconsistent about
516** what %C and %y do if the year is negative or exceeds 9999.
517** Use the convention that %C concatenated with %y yields the
518** same output as %Y, and that %Y contains at least 4 bytes,
519** with more only if necessary.
520*/
521
522static char *
523_yconv(int a, int b, int convert_top, int convert_yy, char *pt, const char *ptlim)
524{
525	int	lead;
526	int	trail;
527
528#define DIVISOR	100
529	trail = a % DIVISOR + b % DIVISOR;
530	lead = a / DIVISOR + b / DIVISOR + trail / DIVISOR;
531	trail %= DIVISOR;
532	if (trail < 0 && lead > 0) {
533		trail += DIVISOR;
534		--lead;
535	} else if (lead < 0 && trail > 0) {
536		trail -= DIVISOR;
537		++lead;
538	}
539	if (convert_top) {
540		if (lead == 0 && trail < 0)
541			pt = _add("-0", pt, ptlim);
542		else	pt = _conv(lead, "%02d", pt, ptlim);
543	}
544	if (convert_yy)
545		pt = _conv(((trail < 0) ? -trail : trail), "%02d", pt, ptlim);
546	return pt;
547}
548