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