1 /* $NetBSD: calendar.c,v 1.53 2016/06/03 02:06:40 agc Exp $ */ 2 3 /* 4 * Copyright (c) 1989, 1993, 1994 5 * The Regents of the University of California. All rights reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 10 * 1. Redistributions of source code must retain the above copyright 11 * notice, this list of conditions and the following disclaimer. 12 * 2. Redistributions in binary form must reproduce the above copyright 13 * notice, this list of conditions and the following disclaimer in the 14 * documentation and/or other materials provided with the distribution. 15 * 3. Neither the name of the University nor the names of its contributors 16 * may be used to endorse or promote products derived from this software 17 * without specific prior written permission. 18 * 19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 29 * SUCH DAMAGE. 30 */ 31 32 #include <sys/cdefs.h> 33 #ifndef lint 34 __COPYRIGHT("@(#) Copyright (c) 1989, 1993\ 35 The Regents of the University of California. All rights reserved."); 36 #endif /* not lint */ 37 38 #ifndef lint 39 #if 0 40 static char sccsid[] = "@(#)calendar.c 8.4 (Berkeley) 1/7/95"; 41 #endif 42 __RCSID("$NetBSD: calendar.c,v 1.53 2016/06/03 02:06:40 agc Exp $"); 43 #endif /* not lint */ 44 45 #include <sys/param.h> 46 #include <sys/ioctl.h> 47 #include <sys/time.h> 48 #include <sys/stat.h> 49 #include <sys/uio.h> 50 #include <sys/wait.h> 51 52 #include <assert.h> 53 #include <ctype.h> 54 #include <err.h> 55 #include <errno.h> 56 #include <fcntl.h> 57 #include <pwd.h> 58 #include <stdbool.h> 59 #include <stdio.h> 60 #include <stdlib.h> 61 #include <string.h> 62 #include <time.h> 63 #include <tzfile.h> 64 #include <unistd.h> 65 66 #include "pathnames.h" 67 68 #define CALENDAR_VERSION "calendar-20160601" 69 70 /* flags used by calendar file parser */ 71 #define F_ISMONTH 0x01 72 #define F_ISDAY 0x02 73 #define F_ISDOW 0x04 74 #define F_WILDMONTH 0x10 75 #define F_WILDDAY 0x20 76 77 static unsigned short lookahead = 1; 78 static unsigned short weekend = 2; 79 static char *fname = NULL; 80 static char *datestr = NULL; 81 static const char *defaultnames[] = {"calendar", ".calendar", _PATH_SYSTEM_CALENDAR, NULL}; 82 static struct passwd *pw; 83 static char path[MAXPATHLEN + 1]; 84 static bool doall = false; 85 static bool cpp_restricted = false; 86 87 /* 1-based month, 0-based days, cumulative */ 88 static const int daytab[][14] = { 89 { 0, -1, 30, 58, 89, 119, 150, 180, 211, 242, 272, 303, 333, 364 }, 90 { 0, -1, 30, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }, 91 }; 92 static struct tm *tp; 93 static const int *cumdays; 94 static int offset, yrdays; 95 static char dayname[10]; 96 97 static struct iovec header[] = { 98 { __UNCONST("From: "), 6 }, 99 { NULL, 0 }, 100 { __UNCONST(" (Reminder Service)\nTo: "), 24 }, 101 { NULL, 0 }, 102 { __UNCONST("\nSubject: "), 10 }, 103 { NULL, 0 }, 104 { __UNCONST("'s Calendar\nPrecedence: bulk\n\n"), 30 }, 105 }; 106 107 static const char *days[] = { 108 "sun", "mon", "tue", "wed", "thu", "fri", "sat", NULL, 109 }; 110 111 static const char *months[] = { 112 "jan", "feb", "mar", "apr", "may", "jun", 113 "jul", "aug", "sep", "oct", "nov", "dec", NULL, 114 }; 115 116 static void atodays(int, char *, unsigned short *); 117 static void cal(void); 118 static void closecal(FILE *); 119 static void changeuser(void); 120 static int getday(char *); 121 static int getfield(char *, char **, int *); 122 static void getmmdd(struct tm *, char *); 123 static int getmonth(char *); 124 static bool isnow(char *); 125 static FILE *opencal(FILE **); 126 static int tryopen(const char *, int); 127 static void settime(void); 128 static void usage(void) __dead; 129 130 int 131 main(int argc, char **argv) 132 { 133 int ch; 134 const char *caldir; 135 136 (void)setprogname(argv[0]); /* for portability */ 137 138 while ((ch = getopt(argc, argv, "-ad:f:l:vw:x")) != -1) { 139 switch (ch) { 140 case '-': /* backward contemptible */ 141 case 'a': 142 if (getuid()) { 143 errno = EPERM; 144 err(EXIT_FAILURE, NULL); 145 } 146 doall = true; 147 break; 148 case 'd': 149 datestr = optarg; 150 break; 151 case 'f': 152 fname = optarg; 153 break; 154 case 'l': 155 atodays(ch, optarg, &lookahead); 156 break; 157 case 'v': 158 printf("%s\n", CALENDAR_VERSION); 159 return 0; 160 case 'w': 161 atodays(ch, optarg, &weekend); 162 break; 163 case 'x': 164 cpp_restricted = true; 165 break; 166 case '?': 167 default: 168 usage(); 169 } 170 } 171 argc -= optind; 172 argv += optind; 173 174 if (argc) 175 usage(); 176 177 settime(); 178 if (doall) { 179 /* 180 * XXX - This ignores the user's CALENDAR_DIR variable. 181 * Run under user's login shell? 182 */ 183 if (setgroups(0, NULL) == -1) { 184 err(EXIT_FAILURE, "setgroups"); 185 } 186 while ((pw = getpwent()) != NULL) { 187 if (setegid(pw->pw_gid) == -1) { 188 warn("%s: setegid", pw->pw_name); 189 continue; 190 } 191 if (seteuid(pw->pw_uid) == -1) { 192 warn("%s: seteuid", pw->pw_name); 193 continue; 194 } 195 if (chdir(pw->pw_dir) != -1) { 196 cal(); 197 } 198 if (seteuid(0) == -1) { 199 warn("%s: seteuid back to 0", pw->pw_name); 200 } 201 } 202 } else if ((caldir = getenv("CALENDAR_DIR")) != NULL) { 203 if (chdir(caldir) != -1) 204 cal(); 205 } else if ((pw = getpwuid(geteuid())) != NULL) { 206 if (chdir(pw->pw_dir) != -1) 207 cal(); 208 } 209 return 0; 210 } 211 212 static void 213 cal(void) 214 { 215 bool printing; 216 FILE *fp, *in = NULL; 217 char *line; 218 219 if ((fp = opencal(&in)) == NULL || in == NULL) 220 return; 221 printing = false; 222 while ((line = fparseln(in, 223 NULL, NULL, NULL, FPARSELN_UNESCCOMM)) != NULL) { 224 if (line[0] == '\0') 225 continue; 226 if (line[0] != '\t') 227 printing = isnow(line); 228 if (printing) 229 (void)fprintf(fp, "%s\n", line); 230 free(line); 231 232 } 233 closecal(fp); 234 } 235 236 static void 237 settime(void) 238 { 239 time_t now; 240 241 (void)time(&now); 242 tp = localtime(&now); 243 if (datestr) 244 getmmdd(tp, datestr); 245 246 if (isleap(tp->tm_year + TM_YEAR_BASE)) { 247 yrdays = DAYSPERLYEAR; 248 cumdays = daytab[1]; 249 } else { 250 yrdays = DAYSPERNYEAR; 251 cumdays = daytab[0]; 252 } 253 /* Friday displays Monday's events */ 254 offset = tp->tm_wday == 5 ? lookahead + weekend : lookahead; 255 header[5].iov_base = dayname; 256 header[5].iov_len = strftime(dayname, sizeof(dayname), "%A", tp); 257 } 258 259 /* 260 * Possible date formats include any combination of: 261 * 3-charmonth (January, Jan, Jan) 262 * 3-charweekday (Friday, Monday, mon.) 263 * numeric month or day (1, 2, 04) 264 * 265 * Any character may separate them, or they may not be separated. Any line, 266 * following a line that is matched, that starts with "whitespace", is shown 267 * along with the matched line. 268 */ 269 static bool 270 isnow(char *endp) 271 { 272 int day; 273 int flags; 274 int month; 275 int v1; 276 int v2; 277 278 flags = 0; 279 280 /* didn't recognize anything, skip it */ 281 if (!(v1 = getfield(endp, &endp, &flags))) 282 return false; 283 284 if ((flags & (F_ISDAY|F_ISDOW)) || v1 > 12) { 285 /* found a day */ 286 day = v1; 287 /* if no recognizable month, assume wildcard ('*') month */ 288 if ((month = getfield(endp, &endp, &flags)) == 0) { 289 flags |= F_ISMONTH | F_WILDMONTH; 290 month = tp->tm_mon + 1; 291 } 292 } else if (flags & F_ISMONTH) { 293 month = v1; 294 /* if no recognizable day, assume the first */ 295 if ((day = getfield(endp, &endp, &flags)) == 0) 296 day = 1; 297 } else { 298 v2 = getfield(endp, &endp, &flags); 299 if (flags & F_ISMONTH) { 300 day = v1; 301 month = v2; 302 } else { 303 /* F_ISDAY set, v2 > 12, or no way to tell */ 304 month = v1; 305 /* if no recognizable day, assume the first */ 306 day = v2 ? v2 : 1; 307 } 308 } 309 /* if month is out of range, treat it as '*' */ 310 if (month < 1 || month > 12) { 311 flags |= F_ISMONTH | F_WILDMONTH; 312 month = tp->tm_mon + 1; 313 } 314 315 if (flags & F_WILDMONTH && flags & F_WILDDAY) 316 return true; 317 318 if (flags & F_WILDMONTH && flags & F_ISDAY && day == tp->tm_mday) 319 return true; 320 321 if (flags & F_WILDMONTH && flags & F_ISDOW && day == tp->tm_wday + 1) 322 return true; 323 324 if (flags & F_ISMONTH && flags & F_WILDDAY && month == tp->tm_mon + 1) 325 return true; 326 327 if (flags & F_ISMONTH && flags & F_ISDOW && month == tp->tm_mon + 1 && 328 day == tp->tm_wday + 1) 329 return true; 330 331 if (flags & F_ISDOW) 332 day = tp->tm_mday + (((day - 1) - tp->tm_wday + 7) % 7); 333 day = cumdays[month] + day; 334 335 /* if today or today + offset days */ 336 if (day >= tp->tm_yday && day <= tp->tm_yday + offset) 337 return true; 338 339 /* if number of days left in this year + days to event in next year */ 340 if (yrdays - tp->tm_yday + day <= offset) 341 return true; 342 343 return false; 344 } 345 346 static int 347 getfield(char *p, char **endp, int *flags) 348 { 349 int val; 350 char *start; 351 char savech; 352 353 /* 354 * note this macro has an arg that isn't used ... it is retained 355 * (it is believed) to make the macro call look more "natural" 356 * and suggest at the call site what is happening. 357 */ 358 #define FLDCHAR(a) (*p != '\0' && !isdigit((unsigned char)*p) && \ 359 !isalpha((unsigned char)*p) && *p != '*') 360 361 val = 0; 362 for (/*EMPTY*/; FLDCHAR(*p); ++p) 363 continue; 364 if (*p == '*') { /* `*' is current month */ 365 if (!(*flags & F_ISMONTH)) { 366 *flags |= F_ISMONTH | F_WILDMONTH; 367 *endp = p + 1; 368 return tp->tm_mon + 1; 369 } else { 370 *flags |= F_ISDAY | F_WILDDAY; 371 *endp = p + 1; 372 return 1; 373 } 374 } 375 if (isdigit((unsigned char)*p)) { 376 val = (int)strtol(p, &p, 10); /* if 0, it's failure */ 377 for (/*EMPTY*/; FLDCHAR(*p); ++p) 378 continue; 379 *endp = p; 380 return val; 381 } 382 for (start = p; *p != '\0' && isalpha((unsigned char)*p); p++) 383 continue; 384 385 savech = *p; 386 if (p != start) { 387 *p = '\0'; 388 if ((val = getmonth(start)) != 0) 389 *flags |= F_ISMONTH; 390 else if ((val = getday(start)) != 0) 391 *flags |= F_ISDOW; 392 else { 393 *p = savech; 394 *endp = start; 395 return 0; 396 } 397 } 398 for (*p = savech; FLDCHAR(*p); ++p) 399 continue; 400 *endp = p; 401 return val; 402 } 403 404 static FILE * 405 opencal(FILE **in) 406 { 407 int fd = -1; 408 int pdes[2]; 409 410 /* open up calendar file as stdin */ 411 if (fname == NULL) { 412 for (const char **name = defaultnames; *name != NULL; name++) { 413 if ((fd = tryopen(*name, O_RDONLY)) == -1) 414 continue; 415 else 416 break; 417 } 418 if (fd == -1) { 419 if (doall) 420 return NULL; 421 err(EXIT_FAILURE, "Cannot open calendar file"); 422 } 423 } else if ((fd = tryopen(fname, O_RDONLY)) == -1) { 424 if (doall) 425 return NULL; 426 err(EXIT_FAILURE, "Cannot open `%s'", fname); 427 } 428 429 if (pipe(pdes) == -1) { 430 warn("Cannot open pipe"); 431 return NULL; 432 } 433 434 switch (fork()) { 435 case -1: 436 /* error */ 437 (void)close(pdes[0]); 438 (void)close(pdes[1]); 439 return NULL; 440 case 0: 441 /* child */ 442 /* set stdin to calendar file */ 443 if (fd != STDIN_FILENO) { 444 (void)dup2(fd, STDIN_FILENO); 445 (void)close(fd); 446 } 447 /* set stdout to pipe input */ 448 if (pdes[1] != STDOUT_FILENO) { 449 (void)dup2(pdes[1], STDOUT_FILENO); 450 (void)close(pdes[1]); 451 } 452 (void)close(pdes[0]); 453 if (doall) { 454 /* become the user properly */ 455 changeuser(); 456 } 457 /* tell CPP to only open regular files */ 458 if(!cpp_restricted && setenv("CPP_RESTRICTED", "", 1) == -1) 459 err(EXIT_FAILURE, "Cannot restrict cpp"); 460 cpp_restricted = true; 461 462 (void)execl(_PATH_CPP, "cpp", "-traditional", "-P", "-I.", 463 "-I" _PATH_CALENDARS, NULL); 464 err(EXIT_FAILURE, "Cannot exec `%s'", _PATH_CPP); 465 /*NOTREACHED*/ 466 default: 467 /* parent -- fdopen *in to pipe output */ 468 *in = fdopen(pdes[0], "r"); 469 (void)close(pdes[1]); 470 471 /* close calendar file */ 472 close(fd); 473 474 /* not reading all calendar files, just set output to stdout */ 475 if (!doall) 476 return stdout; 477 478 /* 479 * Set output to a temporary file, so if no output 480 * don't send mail. 481 */ 482 (void)snprintf(path, sizeof(path), "%s/_calXXXXXX", _PATH_TMP); 483 if ((fd = mkstemp(path)) == -1) { 484 warn("Cannot create temporary file"); 485 return NULL; 486 } 487 return fdopen(fd, "w+"); 488 } 489 /*NOTREACHED*/ 490 } 491 492 static int 493 tryopen(const char *pathname, int flags) 494 { 495 int fd, serrno, zero; 496 struct stat st; 497 498 /* 499 * XXX: cpp_restricted has inverted sense; it is false by default, 500 * and -x sets it to true. CPP_RESTRICTED is set in the environment 501 * if cpp_restricted is false... go figure. This should be fixed 502 * later. 503 */ 504 if (doall && cpp_restricted == false) { 505 /* 506 * We are running with the user's euid, so they can't 507 * cause any mayhem (e.g. opening rewinding tape 508 * devices) that they couldn't do easily enough on 509 * their own. All we really need to worry about is opens 510 * that hang, because that would DoS the calendar run. 511 */ 512 fd = open(pathname, flags | O_NONBLOCK); 513 if (fd == -1) { 514 return -1; 515 } 516 if (fstat(fd, &st) == -1) { 517 serrno = errno; 518 close(fd); 519 errno = serrno; 520 return -1; 521 } 522 if (S_ISCHR(st.st_mode) || 523 S_ISBLK(st.st_mode) || 524 S_ISFIFO(st.st_mode)) { 525 close(fd); 526 527 /* Call shenanigans in the daily output */ 528 errno = EPERM; 529 warn("%s: %s", pw->pw_name, pathname); 530 531 errno = EPERM; 532 return -1; 533 } 534 if (S_ISDIR(st.st_mode)) { 535 /* Don't warn about this */ 536 close(fd); 537 errno = EISDIR; 538 return -1; 539 } 540 if (!S_ISREG(st.st_mode)) { 541 /* There shouldn't be other cases to go here */ 542 close(fd); 543 errno = EINVAL; 544 return -1; 545 } 546 zero = 0; 547 if (ioctl(fd, FIONBIO, &zero) == -1) { 548 serrno = errno; 549 warn("%s: %s: FIONBIO", pw->pw_name, pathname); 550 close(fd); 551 errno = serrno; 552 return -1; 553 } 554 return fd; 555 } else { 556 return open(pathname, flags); 557 } 558 } 559 560 static void 561 closecal(FILE *fp) 562 { 563 struct stat sbuf; 564 ssize_t nread; 565 int pdes[2]; 566 int status; 567 char buf[1024]; 568 569 if (!doall) 570 return; 571 572 (void)rewind(fp); 573 if (fstat(fileno(fp), &sbuf) == -1 || sbuf.st_size == 0) 574 goto done; 575 if (pipe(pdes) == -1) 576 goto done; 577 578 switch (fork()) { 579 case -1: 580 /* error */ 581 (void)close(pdes[0]); 582 (void)close(pdes[1]); 583 break; 584 case 0: 585 /* child -- set stdin to pipe output */ 586 if (pdes[0] != STDIN_FILENO) { 587 (void)dup2(pdes[0], STDIN_FILENO); 588 (void)close(pdes[0]); 589 } 590 (void)close(pdes[1]); 591 if (doall) { 592 /* become the user properly */ 593 changeuser(); 594 } 595 (void)execl(_PATH_SENDMAIL, "sendmail", "-i", "-t", "-F", 596 "\"Reminder Service\"", "-f", "root", NULL); 597 err(EXIT_FAILURE, "Cannot exec `%s'", _PATH_SENDMAIL); 598 /*NOTREACHED*/ 599 default: 600 /* parent -- write to pipe input */ 601 (void)close(pdes[0]); 602 603 header[1].iov_base = header[3].iov_base = (void *)pw->pw_name; 604 header[1].iov_len = header[3].iov_len = strlen(pw->pw_name); 605 (void)writev(pdes[1], header, 7); 606 while ((nread = read(fileno(fp), buf, sizeof(buf))) > 0) 607 (void)write(pdes[1], buf, (size_t)nread); 608 (void)close(pdes[1]); 609 break; 610 } 611 612 done: (void)fclose(fp); 613 (void)unlink(path); 614 while (wait(&status) != -1) 615 continue; 616 } 617 618 static void 619 changeuser(void) 620 { 621 uid_t uid; 622 gid_t gid; 623 624 uid = geteuid(); 625 gid = getegid(); 626 assert(uid == pw->pw_uid); 627 assert(gid == pw->pw_gid); 628 629 if (seteuid(0) == -1) { 630 err(EXIT_FAILURE, "%s: changing user: cannot reassert uid 0", 631 pw->pw_name); 632 } 633 if (setgid(gid) == -1) { 634 err(EXIT_FAILURE, "%s: cannot assume gid %d", 635 pw->pw_name, (int)gid); 636 } 637 if (initgroups(pw->pw_name, gid) == -1) { 638 err(EXIT_FAILURE, "%s: cannot initgroups", pw->pw_name); 639 } 640 if (setuid(uid) == -1) { 641 err(EXIT_FAILURE, "%s: cannot assume uid %d", 642 pw->pw_name, (int)uid); 643 } 644 } 645 646 static int 647 getmonth(char *s) 648 { 649 const char **p; 650 651 for (p = months; *p; ++p) 652 if (strncasecmp(s, *p, 3) == 0) 653 return (int)(p - months) + 1; 654 return 0; 655 } 656 657 static int 658 getday(char *s) 659 { 660 const char **p; 661 662 for (p = days; *p; ++p) 663 if (strncasecmp(s, *p, 3) == 0) 664 return (int)(p - days) + 1; 665 return 0; 666 } 667 668 static void 669 atodays(int ch, char *arg, unsigned short *rvp) 670 { 671 int u; 672 673 u = atoi(arg); 674 if (u < 0 || u > 366) 675 warnx("-%c %d out of range 0-366, ignored.", ch, u); 676 else 677 *rvp = u; 678 } 679 680 #define todigit(x) ((x) - '0') 681 #define ATOI2(x) (todigit((x)[0]) * 10 + todigit((x)[1])) 682 #define ISDIG2(x) (isdigit((unsigned char)(x)[0]) && isdigit((unsigned char)(x)[1])) 683 684 static void 685 getmmdd(struct tm *ptm, char *ds) 686 { 687 bool ok = false; 688 struct tm ttm; 689 690 ttm = *ptm; 691 ttm.tm_isdst = -1; 692 693 if (ISDIG2(ds)) { 694 ttm.tm_mon = ATOI2(ds) - 1; 695 ds += 2; 696 } 697 if (ISDIG2(ds)) { 698 ttm.tm_mday = ATOI2(ds); 699 ds += 2; 700 ok = true; 701 } 702 if (ok) { 703 if (ISDIG2(ds) && ISDIG2(ds + 2)) { 704 ttm.tm_year = ATOI2(ds) * 100 - TM_YEAR_BASE; 705 ds += 2; 706 ttm.tm_year += ATOI2(ds); 707 } else if (ISDIG2(ds)) { 708 ttm.tm_year = ATOI2(ds); 709 if (ttm.tm_year < 69) 710 ttm.tm_year += 2000 - TM_YEAR_BASE; 711 else 712 ttm.tm_year += 1900 - TM_YEAR_BASE; 713 } 714 } 715 if (ok && mktime(&ttm) == -1) 716 ok = false; 717 718 if (ok) 719 *ptm = ttm; 720 else { 721 warnx("Can't convert `%s' to date, ignored.", ds); 722 usage(); 723 } 724 } 725 726 __dead 727 static void 728 usage(void) 729 { 730 (void)fprintf(stderr, "usage: %s [-ax] [-d MMDD[[YY]YY]" 731 " [-f fname] [-l days] [-w days]\n", getprogname()); 732 exit(1); 733 } 734