diff --git a/usr.bin/calendar/calendar.1 b/usr.bin/calendar/calendar.1 index af368475e4d5..edb3aca48c92 100644 --- a/usr.bin/calendar/calendar.1 +++ b/usr.bin/calendar/calendar.1 @@ -25,7 +25,7 @@ .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" -.Dd July 31, 2022 +.Dd December 17, 2023 .Dt CALENDAR 1 .Os .Sh NAME @@ -213,9 +213,8 @@ succeeding lines. .Pp If the shared file is not referenced by a full pathname, .Nm -searches in the current (or home) directory first, and then in the -directory -.Pa /usr/share/calendar . +searches in the same order of precedence described in +.Sx FILES . .Pp Blank lines and text protected by the C comment syntax .Ql /* ... */ diff --git a/usr.bin/calendar/io.c b/usr.bin/calendar/io.c index 978027895dfe..17cd5b852c09 100644 --- a/usr.bin/calendar/io.c +++ b/usr.bin/calendar/io.c @@ -35,6 +35,7 @@ #include #include #include +#include #include #include #include @@ -102,9 +103,11 @@ trimlr(char **buf) static FILE * cal_fopen(const char *file) { + static int cwdfd = -1; FILE *fp; char *home = getenv("HOME"); unsigned int i; + int fd; struct stat sb; static bool warned = false; static char calendarhome[MAXPATHLEN]; @@ -114,6 +117,34 @@ cal_fopen(const char *file) return (NULL); } + /* + * On -a runs, we would have done a chdir() earlier on, but we also + * shouldn't have used the initial cwd anyways lest we bring + * unpredictable behavior upon us. + */ + if (!doall && cwdfd == -1) { + cwdfd = open(".", O_DIRECTORY | O_PATH); + if (cwdfd == -1) + err(1, "open(cwd)"); + } + + /* + * Check $PWD first as documented. + */ + if (cwdfd != -1) { + if ((fd = openat(cwdfd, file, O_RDONLY)) != -1) { + if ((fp = fdopen(fd, "r")) == NULL) + err(1, "fdopen(%s)", file); + + cal_home = NULL; + cal_dir = NULL; + cal_file = file; + return (fp); + } else if (errno != ENOENT && errno != ENAMETOOLONG) { + err(1, "open(%s)", file); + } + } + if (chdir(home) != 0) { warnx("Cannot enter home directory \"%s\"", home); return (NULL);