#include <sys/stat.h>
#include <sys/syslog.h>
#include <dirent.h>
#include <errno.h>
#include <event.h>
#include <paths.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "log.h"
#include "syslogd.h"
struct tty_delay {
struct event td_event;
size_t td_length;
char td_line[LOG_MAXLINE];
};
int tty_delayed = 0;
void ttycb(int, short, void *);
void
ttymsg(char *utline, struct iovec *iov)
{
static char device[MAXNAMLEN] = _PATH_DEV;
struct iovec localiov[IOVCNT];
int iovcnt = IOVCNT;
int cnt, fd;
size_t left;
ssize_t wret;
if ((strncmp(utline, "ftp", 3) == 0) ||
(strncmp(utline, "uucp", 4) == 0))
return;
(void) strlcpy(device + sizeof(_PATH_DEV) - 1, utline,
sizeof(device) - (sizeof(_PATH_DEV) - 1));
if (strchr(device + sizeof(_PATH_DEV) - 1, '/')) {
log_warnx("'/' in tty device \"%s\"", device);
return;
}
if ((fd = priv_open_tty(device)) == -1) {
if (errno != EBUSY && errno != EACCES)
log_warn("priv_open_tty device \"%s\"", device);
return;
}
left = 0;
for (cnt = 0; cnt < iovcnt; ++cnt)
left += iov[cnt].iov_len;
for (;;) {
wret = writev(fd, iov, iovcnt);
if (wret >= 0) {
if ((size_t)wret >= left)
break;
left -= wret;
if (iov != localiov) {
memmove(localiov, iov,
iovcnt * sizeof(struct iovec));
iov = localiov;
}
while ((size_t)wret >= iov->iov_len) {
wret -= iov->iov_len;
++iov;
--iovcnt;
}
if (wret) {
iov->iov_base = (char *)iov->iov_base + wret;
iov->iov_len -= wret;
}
continue;
}
if (errno == EWOULDBLOCK) {
struct tty_delay *td;
struct timeval to;
if (tty_delayed >= TTYMAXDELAY) {
log_warnx("tty device \"%s\": %s",
device, "too many delayed writes");
break;
}
log_debug("ttymsg delayed write");
if (iov != localiov) {
memmove(localiov, iov,
iovcnt * sizeof(struct iovec));
iov = localiov;
}
if ((td = malloc(sizeof(*td))) == NULL) {
log_warn("allocate delay tty device \"%s\"",
device);
break;
}
td->td_length = 0;
if (left > LOG_MAXLINE)
left = LOG_MAXLINE;
while (iovcnt && left) {
if (iov->iov_len > left)
iov->iov_len = left;
memcpy(td->td_line + td->td_length,
iov->iov_base, iov->iov_len);
td->td_length += iov->iov_len;
left -= iov->iov_len;
++iov;
--iovcnt;
}
tty_delayed++;
event_set(&td->td_event, fd, EV_WRITE, ttycb, td);
to.tv_sec = TTYMSGTIME;
to.tv_usec = 0;
event_add(&td->td_event, &to);
return;
}
if (errno != ENODEV && errno != EIO)
log_warn("writev tty device \"%s\"", device);
break;
}
(void) close(fd);
return;
}
void
ttycb(int fd, short event, void *arg)
{
struct tty_delay *td = arg;
struct timeval to;
ssize_t wret;
if (event != EV_WRITE)
goto done;
wret = write(fd, td->td_line, td->td_length);
if (wret == -1 && errno != EINTR && errno != EWOULDBLOCK)
goto done;
if (wret > 0) {
td->td_length -= wret;
if (td->td_length == 0)
goto done;
memmove(td->td_line, td->td_line + wret, td->td_length);
}
to.tv_sec = TTYMSGTIME;
to.tv_usec = 0;
event_add(&td->td_event, &to);
return;
done:
tty_delayed--;
close(fd);
free(td);
}