#include <sys/cdefs.h>
#ifndef lint
__RCSID("$NetBSD: term_chk.c,v 1.8 2009/04/14 07:59:17 lukem Exp $");
#endif
#include <sys/types.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <paths.h>
#include <fcntl.h>
#include <string.h>
#include <err.h>
#include "term_chk.h"
int
term_chk(uid_t uid, const char *tty, int *msgsokP, time_t *atimeP, int ismytty,
gid_t saved_egid)
{
char path[MAXPATHLEN];
struct stat s;
int i, fd, serrno;
if (strstr(tty, "../") != NULL) {
errno = EINVAL;
return -1;
}
i = snprintf(path, sizeof path, _PATH_DEV "%s", tty);
if (i < 0 || i >= (int)sizeof(path)) {
errno = ENOMEM;
return -1;
}
(void)setegid(saved_egid);
fd = open(path, O_WRONLY, 0);
serrno = errno;
(void)setegid(getgid());
errno = serrno;
if (fd == -1)
return(-1);
if (fstat(fd, &s) == -1)
goto error;
if (!isatty(fd))
goto error;
if (s.st_uid != uid && uid != 0) {
errno = EPERM;
goto error;
}
if (msgsokP)
*msgsokP = (s.st_mode & S_IWGRP) != 0;
if (atimeP)
*atimeP = s.st_atime;
if (ismytty)
(void)close(fd);
return ismytty ? 0 : fd;
error:
if (fd != -1) {
serrno = errno;
(void)close(fd);
errno = serrno;
}
return -1;
}
char *
check_sender(time_t *atime, uid_t myuid, gid_t saved_egid)
{
int myttyfd;
int msgsok;
char *mytty;
if (isatty(fileno(stdin)))
myttyfd = fileno(stdin);
else if (isatty(fileno(stdout)))
myttyfd = fileno(stdout);
else if (isatty(fileno(stderr)))
myttyfd = fileno(stderr);
else if (atime == NULL)
return NULL;
else
errx(1, "Cannot find your tty");
if ((mytty = ttyname(myttyfd)) == NULL)
err(1, "Cannot find the name of your tty");
if (strncmp(mytty, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
mytty += sizeof(_PATH_DEV) - 1;
if (term_chk(myuid, mytty, &msgsok, atime, 1, saved_egid) == -1)
err(1, "%s%s", _PATH_DEV, mytty);
if (!msgsok) {
warnx(
"You have write permission turned off; no reply possible");
}
return mytty;
}