xref: /openbsd/usr.bin/cal/cal.c (revision 4cfece93)
1 /*	$OpenBSD: cal.c,v 1.30 2015/10/09 01:37:06 deraadt Exp $	*/
2 /*	$NetBSD: cal.c,v 1.6 1995/03/26 03:10:24 glass Exp $	*/
3 
4 /*
5  * Copyright (c) 1989, 1993, 1994
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * Kim Letkeman.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include <sys/types.h>
37 
38 #include <ctype.h>
39 #include <err.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <time.h>
44 #include <unistd.h>
45 
46 #define	THURSDAY		4		/* for reformation */
47 #define	SATURDAY		6		/* 1 Jan 1 was a Saturday */
48 
49 #define	FIRST_MISSING_DAY	639799		/* 3 Sep 1752 */
50 #define	NUMBER_MISSING_DAYS	11		/* 11 day correction */
51 
52 #define	MAXDAYS			42		/* max slots in a month array */
53 #define	SPACE			-1		/* used in day array */
54 
55 static const int days_in_month[2][13] = {
56 	{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
57 	{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
58 };
59 
60 const int sep1752s[MAXDAYS] = {
61 	SPACE,	SPACE,	1,	2,	14,	15,	16,
62 	17,	18,	19,	20,	21,	22,	23,
63 	24,	25,	26,	27,	28,	29,	30,
64 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
65 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
66 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
67 }, sep1752m[MAXDAYS] = {
68 	SPACE,	1,	2,	14,	15,	16,	17,
69 	18,	19,	20,	21,	22,	23,	24,
70 	25,	26,	27,	28,	29,	30,	SPACE,
71 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
72 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
73 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
74 }, sep1752js[MAXDAYS] = {
75 	SPACE,	SPACE,	245,	246,	258,	259,	260,
76 	261,	262,	263,	264,	265,	266,	267,
77 	268,	269,	270,	271,	272,	273,	274,
78 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
79 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
80 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
81 }, sep1752jm[MAXDAYS] = {
82 	SPACE,	245,	246,	258,	259,	260,	261,
83 	262,	263,	264,	265,	266,	267,	268,
84 	269,	270,	271,	272,	273,	274,	SPACE,
85 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
86 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
87 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
88 }, empty[MAXDAYS] = {
89 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
90 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
91 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
92 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
93 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
94 	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,	SPACE,
95 };
96 
97 const char *month_names[12] = {
98 	"January", "February", "March", "April", "May", "June",
99 	"July", "August", "September", "October", "November", "December",
100 };
101 
102 #define	DAY_HEADINGS_S	"Su Mo Tu We Th Fr Sa"
103 #define	DAY_HEADINGS_M	"Mo Tu We Th Fr Sa Su"
104 #define	DAY_HEADINGS_JS	" Su  Mo  Tu  We  Th  Fr  Sa"
105 #define	DAY_HEADINGS_JM	" Mo  Tu  We  Th  Fr  Sa  Su"
106 
107 const int	*sep1752 = NULL;
108 const char	*day_headings = NULL;
109 
110 /* leap year -- account for gregorian reformation in 1752 */
111 #define	leap_year(yr) \
112 	((yr) <= 1752 ? !((yr) % 4) : \
113 	(!((yr) % 4) && ((yr) % 100)) || !((yr) % 400))
114 
115 /* number of centuries since 1700, not inclusive */
116 #define	centuries_since_1700(yr) \
117 	((yr) > 1700 ? (yr) / 100 - 17 : 0)
118 
119 /* number of centuries since 1700 whose modulo of 400 is 0 */
120 #define	quad_centuries_since_1700(yr) \
121 	((yr) > 1600 ? ((yr) - 1600) / 400 : 0)
122 
123 /* number of leap years between year 1 and this year, not inclusive */
124 #define	leap_years_since_year_1(yr) \
125 	((yr) / 4 - centuries_since_1700(yr) + quad_centuries_since_1700(yr))
126 
127 int julian;
128 int mflag = 0;
129 int wflag = 0;
130 
131 void	ascii_day(char *, int);
132 void	center(const char *, int, int);
133 void	day_array(int, int, int *);
134 int	day_in_week(int, int, int);
135 int	day_in_year(int, int, int);
136 int	week(int, int, int);
137 int	isoweek(int, int, int);
138 void	j_yearly(int);
139 void	monthly(int, int);
140 void	trim_trailing_spaces(char *);
141 void	usage(void);
142 void	yearly(int);
143 int	parsemonth(const char *);
144 
145 int
146 main(int argc, char *argv[])
147 {
148 	struct tm *local_time;
149 	time_t now;
150 	int ch, month, year, yflag;
151 	const char *errstr;
152 
153 	if (pledge("stdio", NULL) == -1)
154 		err(1, "pledge");
155 
156 	yflag = year = 0;
157 	while ((ch = getopt(argc, argv, "jmwy")) != -1)
158 		switch(ch) {
159 		case 'j':
160 			julian = 1;
161 			break;
162 		case 'm':
163 			mflag = 1;
164 			break;
165 		case 'w':
166 			wflag = 1;
167 			break;
168 		case 'y':
169 			yflag = 1;
170 			break;
171 		case '?':
172 		default:
173 			usage();
174 		}
175 	argc -= optind;
176 	argv += optind;
177 
178 	if (julian && wflag)
179 		usage();
180 
181 	day_headings = DAY_HEADINGS_S;
182 	sep1752 = sep1752s;
183 	if (mflag && julian) {
184 		sep1752 = sep1752jm;
185 		day_headings = DAY_HEADINGS_JM;
186 	} else if (mflag) {
187 		sep1752 = sep1752m;
188 		day_headings = DAY_HEADINGS_M;
189 	} else if (julian) {
190 		sep1752 = sep1752js;
191 		day_headings = DAY_HEADINGS_JS;
192 	}
193 
194 	month = 0;
195 	switch(argc) {
196 	case 2:
197 		month = parsemonth(*argv++);
198 		if (!month)
199 			errx(1, "Unable to parse month");
200 		/* FALLTHROUGH */
201 	case 1:
202 		if (argc == 1 && !isdigit((unsigned char)*argv[0])) {
203 			month = parsemonth(*argv);
204 			if (!month)
205 				errx(1, "illegal year value: use 1-9999");
206 			(void)time(&now);
207 			local_time = localtime(&now);
208 			year = local_time->tm_year + 1900;
209 		} else {
210 			year = strtonum(*argv, 1, 9999, &errstr);
211 			if (errstr)
212 				errx(1, "illegal year value: use 1-9999");
213 		}
214 		break;
215 	case 0:
216 		(void)time(&now);
217 		local_time = localtime(&now);
218 		year = local_time->tm_year + 1900;
219 		if (!yflag)
220 			month = local_time->tm_mon + 1;
221 		break;
222 	default:
223 		usage();
224 	}
225 
226 	if (month)
227 		monthly(month, year);
228 	else if (julian)
229 		j_yearly(year);
230 	else
231 		yearly(year);
232 	exit(0);
233 }
234 
235 #define	DAY_LEN		3		/* 3 spaces per day */
236 #define	J_DAY_LEN	4		/* 4 spaces per day */
237 #define	WEEK_LEN	20		/* 7 * 3 - one space at the end */
238 #define WEEKNUMBER_LEN	5		/* 5 spaces per week number */
239 #define	J_WEEK_LEN	27		/* 7 * 4 - one space at the end */
240 #define	HEAD_SEP	2		/* spaces between day headings */
241 #define	J_HEAD_SEP	2
242 
243 int
244 week(int day, int month, int year)
245 {
246 	int	yearday;
247 	int	firstweekday;
248 	int	weekday;
249 	int	firstday;
250 	int	firstsunday;
251 	int	shift;
252 
253 	if (mflag)
254 		return isoweek(day, month, year);
255 
256 	yearday = day_in_year(day, month, year);
257 	firstweekday = day_in_week(1, 1, year) + 1;
258 	weekday = day_in_week(day, month, year) + 1;
259 	firstday = day_in_year(1, 1, year);
260 	firstsunday = firstday + (8 - firstweekday);
261 
262 	shift = 1;
263 	if (yearday < firstsunday)
264 		return (1);
265 	if (firstweekday > THURSDAY - 1)
266 		shift = 2;
267 	return ((((yearday + 1) - (weekday - 1)) / 7) + shift);
268 }
269 
270 int
271 isoweek(int day, int month, int year)
272 {
273 	/* http://www.tondering.dk/claus/cal/node8.html */
274 	int a, b, c, s, e, f, g, d, n;
275 
276 	a = month <= 2 ? year - 1 : year;
277 	b = a/4 - a/100 + a/400;
278 	c = (a-1)/4 - (a-1)/100 + (a-1)/400;
279 	s = b - c;
280 	if (month <= 2) {
281 		e = 0;
282 		f = day - 1 + 31 * (month-1);
283 	} else {
284 		e = s + 1;
285 		f = day + ((153 * (month-3) + 2) / 5) + 58 + s;
286 	}
287 	g = (a + b) % 7;
288 	d = (f + g - e) % 7;
289 	n = f + 3 - d;
290 
291 	if (n < 0)
292 		return 53 - (g - s) / 5;
293 	else if (n > 364 + s)
294 		return 1;
295 	else
296 		return n/7 + 1;
297 }
298 
299 void
300 monthly(int month, int year)
301 {
302 	int col, row, len, days[MAXDAYS], firstday;
303 	char *p, lineout[30];
304 
305 	day_array(month, year, days);
306 	(void)snprintf(lineout, sizeof(lineout), "%s %d",
307 	    month_names[month - 1], year);
308 	len = strlen(lineout);
309 	(void)printf("%*s%s\n%s\n",
310 	    ((julian ? J_WEEK_LEN : WEEK_LEN) - len) / 2, "",
311 	    lineout, day_headings);
312 	for (row = 0; row < 6; row++) {
313 		firstday = SPACE;
314 		for (col = 0, p = lineout; col < 7; col++,
315 		    p += julian ? J_DAY_LEN : DAY_LEN) {
316 			if (firstday == SPACE && days[row * 7 + col] != SPACE)
317 				firstday = days[row * 7 + col];
318 			ascii_day(p, days[row * 7 + col]);
319 		}
320 		*p = '\0';
321 		trim_trailing_spaces(lineout);
322 		(void)printf("%-20s", lineout);
323 		if (wflag && firstday != SPACE)
324 			printf(" [%2d]", week(firstday, month, year));
325 		printf("\n");
326 	}
327 }
328 
329 void
330 j_yearly(int year)
331 {
332 	int col, *dp, i, month, row, which_cal;
333 	int days[12][MAXDAYS];
334 	char *p, lineout[80];
335 
336 	(void)snprintf(lineout, sizeof(lineout), "%d", year);
337 	center(lineout, J_WEEK_LEN * 2 + J_HEAD_SEP, 0);
338 	(void)printf("\n\n");
339 	for (i = 0; i < 12; i++)
340 		day_array(i + 1, year, days[i]);
341 	(void)memset(lineout, ' ', sizeof(lineout) - 1);
342 	lineout[sizeof(lineout) - 1] = '\0';
343 	for (month = 0; month < 12; month += 2) {
344 		center(month_names[month], J_WEEK_LEN, J_HEAD_SEP);
345 		center(month_names[month + 1], J_WEEK_LEN, 0);
346 		(void)printf("\n%s%*s%s\n", day_headings,
347 		    J_HEAD_SEP, "", day_headings);
348 
349 		for (row = 0; row < 6; row++) {
350 			for (which_cal = 0; which_cal < 2; which_cal++) {
351 				p = lineout + which_cal * (J_WEEK_LEN + 2);
352 				dp = &days[month + which_cal][row * 7];
353 				for (col = 0; col < 7; col++, p += J_DAY_LEN)
354 					ascii_day(p, *dp++);
355 			}
356 			*p = '\0';
357 			trim_trailing_spaces(lineout);
358 			(void)printf("%s\n", lineout);
359 		}
360 	}
361 	(void)printf("\n");
362 }
363 
364 void
365 yearly(int year)
366 {
367 	int col, *dp, i, month, row, which_cal, week_len, wn, firstday;
368 	int days[12][MAXDAYS];
369 	char *p, lineout[81];
370 
371 	week_len = WEEK_LEN;
372 	if (wflag)
373 		week_len += WEEKNUMBER_LEN;
374 	(void)snprintf(lineout, sizeof(lineout), "%d", year);
375 	center(lineout, week_len * 3 + HEAD_SEP * 2, 0);
376 	(void)printf("\n\n");
377 	for (i = 0; i < 12; i++)
378 		day_array(i + 1, year, days[i]);
379 	(void)memset(lineout, ' ', sizeof(lineout) - 1);
380 	lineout[sizeof(lineout) - 1] = '\0';
381 	for (month = 0; month < 12; month += 3) {
382 		center(month_names[month], week_len, HEAD_SEP);
383 		center(month_names[month + 1], week_len, HEAD_SEP);
384 		center(month_names[month + 2], week_len, 0);
385 		(void)printf("\n%s%*s%s%*s%s\n", day_headings,
386 		    HEAD_SEP + (wflag ? WEEKNUMBER_LEN : 0), "", day_headings,
387 		    HEAD_SEP + (wflag ? WEEKNUMBER_LEN : 0), "", day_headings);
388 
389 		for (row = 0; row < 6; row++) {
390 			for (which_cal = 0; which_cal < 3; which_cal++) {
391 				p = lineout + which_cal * (week_len + 2);
392 
393 				dp = &days[month + which_cal][row * 7];
394 				firstday = SPACE;
395 				for (col = 0; col < 7; col++, p += DAY_LEN) {
396 					if (firstday == SPACE && *dp != SPACE)
397 						firstday = *dp;
398 					ascii_day(p, *dp++);
399 				}
400 				if (wflag && firstday != SPACE) {
401 					wn = week(firstday,
402 					    month + which_cal + 1, year);
403 					(void)snprintf(p, 5, "[%2d]", wn);
404 					p += strlen(p);
405 					*p = ' ';
406 				} else
407 					memset(p, ' ', 4);
408 			}
409 			*p = '\0';
410 			trim_trailing_spaces(lineout);
411 			(void)printf("%s\n", lineout);
412 		}
413 	}
414 	(void)printf("\n");
415 }
416 
417 /*
418  * day_array --
419  *	Fill in an array of 42 integers with a calendar.  Assume for a moment
420  *	that you took the (maximum) 6 rows in a calendar and stretched them
421  *	out end to end.  You would have 42 numbers or spaces.  This routine
422  *	builds that array for any month from Jan. 1 through Dec. 9999.
423  */
424 void
425 day_array(int month, int year, int *days)
426 {
427 	int day, dw, dm;
428 
429 	if (month == 9 && year == 1752) {
430 		memmove(days, sep1752, MAXDAYS * sizeof(int));
431 		return;
432 	}
433 	memmove(days, empty, MAXDAYS * sizeof(int));
434 	dm = days_in_month[leap_year(year)][month];
435 	dw = day_in_week(mflag?0:1, month, year);
436 	day = julian ? day_in_year(1, month, year) : 1;
437 	while (dm--)
438 		days[dw++] = day++;
439 }
440 
441 /*
442  * day_in_year --
443  *	return the 1 based day number within the year
444  */
445 int
446 day_in_year(int day, int month, int year)
447 {
448 	int i, leap;
449 
450 	leap = leap_year(year);
451 	for (i = 1; i < month; i++)
452 		day += days_in_month[leap][i];
453 	return (day);
454 }
455 
456 /*
457  * day_in_week
458  *	return the 0 based day number for any date from 1 Jan. 1 to
459  *	31 Dec. 9999.  Assumes the Gregorian reformation eliminates
460  *	3 Sep. 1752 through 13 Sep. 1752.  Returns Thursday for all
461  *	missing days.
462  */
463 int
464 day_in_week(int day, int month, int year)
465 {
466 	long temp;
467 
468 	temp = (long)(year - 1) * 365 + leap_years_since_year_1(year - 1)
469 	    + day_in_year(day, month, year);
470 	if (temp < FIRST_MISSING_DAY)
471 		return ((temp - 1 + SATURDAY) % 7);
472 	if (temp >= (FIRST_MISSING_DAY + NUMBER_MISSING_DAYS))
473 		return (((temp - 1 + SATURDAY) - NUMBER_MISSING_DAYS) % 7);
474 	return (THURSDAY);
475 }
476 
477 void
478 ascii_day(char *p, int day)
479 {
480 	int display, val;
481 	static const char *aday[] = {
482 		"",
483 		" 1", " 2", " 3", " 4", " 5", " 6", " 7",
484 		" 8", " 9", "10", "11", "12", "13", "14",
485 		"15", "16", "17", "18", "19", "20", "21",
486 		"22", "23", "24", "25", "26", "27", "28",
487 		"29", "30", "31",
488 	};
489 
490 	if (day == SPACE) {
491 		memset(p, ' ', julian ? J_DAY_LEN : DAY_LEN);
492 		return;
493 	}
494 	if (julian) {
495 		val = day / 100;
496 		if (val) {
497 			day %= 100;
498 			*p++ = val + '0';
499 			display = 1;
500 		} else {
501 			*p++ = ' ';
502 			display = 0;
503 		}
504 		val = day / 10;
505 		if (val || display)
506 			*p++ = val + '0';
507 		else
508 			*p++ = ' ';
509 		*p++ = day % 10 + '0';
510 	} else {
511 		*p++ = aday[day][0];
512 		*p++ = aday[day][1];
513 	}
514 	*p = ' ';
515 }
516 
517 void
518 trim_trailing_spaces(char *s)
519 {
520 	char *p;
521 
522 	for (p = s; *p; ++p)
523 		continue;
524 	while (p > s && isspace((unsigned char)*--p))
525 		continue;
526 	if (p > s)
527 		++p;
528 	*p = '\0';
529 }
530 
531 void
532 center(const char *str, int len, int separate)
533 {
534 
535 	len -= strlen(str);
536 	(void)printf("%*s%s%*s", len / 2, "", str,
537 	    len / 2 + len % 2 + separate, "");
538 }
539 
540 void
541 usage(void)
542 {
543 
544 	(void)fprintf(stderr, "usage: cal [-jmwy] [month] [year]\n");
545 	exit(1);
546 }
547 
548 int
549 parsemonth(const char *s)
550 {
551 	struct tm tm;
552 	char *cp;
553 	int v;
554 
555 	v = (int)strtol(s, &cp, 10);
556 	if (*cp != '\0') {		/* s wasn't purely numeric */
557 		v = 0;
558 		if ((cp = strptime(s, "%b", &tm)) != NULL && *cp == '\0')
559 			v = tm.tm_mon + 1;
560 	}
561 	if (v <= 0 || v > 12)
562 		errx(1, "invalid month: use 1-12 or a name");
563 	return (v);
564 }
565