#include <sys/cdefs.h>
#include <poll.h>
#ifndef lint
#if 0
static char sccsid[] = "@(#)tipout.c 8.1 (Berkeley) 6/6/93";
#endif
__RCSID("$NetBSD: tipout.c,v 1.15 2011/09/06 18:33:01 joerg Exp $");
#endif
#include "tip.h"
void intEMT(void);
void intIOT(void);
void intSYS(void);
__dead static void intTERM(int);
void
intIOT(void)
{
(void)write(repdes[1],&ccc,1);
(void)read(fildes[0], &ccc,1);
}
void
intEMT(void)
{
char c, line[256];
char *pline = line;
char reply;
(void)read(fildes[0], &c, 1);
while (c != '\n' && line + sizeof line - pline > 0) {
*pline++ = c;
(void)read(fildes[0], &c, 1);
}
*pline = '\0';
if (boolean(value(SCRIPT)) && fscript != NULL)
(void)fclose(fscript);
if (pline == line) {
setboolean(value(SCRIPT), FALSE);
reply = 'y';
} else {
if ((fscript = fopen(line, "a")) == NULL)
reply = 'n';
else {
reply = 'y';
setboolean(value(SCRIPT), TRUE);
}
}
(void)write(repdes[1], &reply, 1);
}
static void
intTERM(int dummy __unused)
{
if (boolean(value(SCRIPT)) && fscript != NULL)
(void)fclose(fscript);
exit(0);
}
void
intSYS(void)
{
setboolean(value(BEAUTIFY), !boolean(value(BEAUTIFY)));
}
void
tipout(void)
{
char buf[BUFSIZ];
char *cp;
int cnt;
int omask;
struct pollfd pfd[2];
(void)signal(SIGINT, SIG_IGN);
(void)signal(SIGQUIT, SIG_IGN);
(void)signal(SIGHUP, intTERM);
(void)signal(SIGTERM, intTERM);
pfd[0].fd = attndes[0];
pfd[0].events = POLLIN;
pfd[1].fd = FD;
pfd[1].events = POLLIN|POLLHUP;
for (omask = 0;; (void)sigsetmask(omask)) {
if (poll(pfd, 2, -1) > 0) {
if (pfd[0].revents & POLLIN)
if (read(attndes[0], &ccc, 1) > 0) {
switch(ccc) {
case 'W':
intIOT();
break;
case 'S':
intEMT();
break;
case 'B':
intSYS();
break;
default:
break;
}
}
}
if (pfd[1].revents & (POLLIN|POLLHUP)) {
cnt = read(FD, buf, BUFSIZ);
if (cnt <= 0) {
if ((cnt < 0 && errno == EIO) || (cnt == 0)) {
(void)sigblock(sigmask(SIGTERM));
intTERM(0);
}
continue;
}
omask = sigblock(SIGTERM);
for (cp = buf; cp < buf + cnt; cp++)
*cp &= STRIP_PAR;
(void)write(1, buf, (size_t)cnt);
if (boolean(value(SCRIPT)) && fscript != NULL) {
if (!boolean(value(BEAUTIFY))) {
(void)fwrite(buf, 1, (size_t)cnt, fscript);
continue;
}
for (cp = buf; cp < buf + cnt; cp++)
if ((*cp >= ' ' && *cp <= '~') ||
any(*cp, value(EXCEPTIONS)))
(void)putc(*cp, fscript);
}
}
}
}