#include <sys/types.h>
#include <signal.h>
#include <stdio.h>
#include <stdio_ext.h>
#include <unistd.h>
#include <utmpx.h>
#include <errno.h>
#include <termio.h>
#include <sys/termios.h>
#include <sys/tty.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <fcntl.h>
#include <time.h>
#include <sys/stropts.h>
#include <wait.h>
#include <syslog.h>
#include <stdlib.h>
#include <string.h>
#include <poll.h>
#include <deflt.h>
#include <procfs.h>
#include <sys/resource.h>
#include <limits.h>
#define dprintf(x) if (Debug) (void) printf x
#define MAX_FDS 4064
#define EXTRA_MARGIN 32
#define MAX_POLL_ERRS 1024
#define MAX_RESETS 1024
#define POLL_TIMEOUT 300
#define CLEANIT 1
#define DONT_CLEAN 0
#define UTMP_DEFAULT "/etc/default/utmpd"
#define WARN_TIME 3600
#define WTMPX_UFREQ 60
#define ADDPID 1
#define REMPID 2
struct pidrec {
int pd_type;
pid_t pd_pid;
};
struct pidentry {
pid_t pl_pid;
int pl_status;
};
static struct pidentry *pidtable = NULL;
static pollfd_t *fdtable = NULL;
static int pidcnt = 0;
static char *prog_name;
static char *UTMPPIPE_DIR = "/var/run";
static char *UTMPPIPE = "/var/run/utmppipe";
static int Pfd = -1;
static int Poll_timeout = POLL_TIMEOUT;
static int WTMPXfd = -1;
static int WTMPX_ufreq = WTMPX_UFREQ;
static int Debug = 0;
static int Max_fds = MAX_FDS;
static int wait_for_pids();
static void scan_utmps();
static void drain_pipe();
static void setup_pipe();
static void add_pid();
static void rem_pid();
static int find_pid();
static int proc_to_fd();
static void load_tables();
static int pidcmp();
static void clean_entry();
static void clean_utmpx_ent();
static void fatal() __NORETURN;
static void nonfatal();
static void print_tables();
static int proc_is_alive(pid_t pid);
static void warn_utmp(void);
static int validate_default(char *defp, int *flag);
int
main(int argc, char *argv[])
{
char *defp;
struct rlimit rlim;
int i;
time_t curtime, now;
char msg[256];
prog_name = argv[0];
if (getuid() != 0) {
(void) fprintf(stderr,
"You must be root to run this program\n");
fatal("You must be root to run this program");
}
if (argc > 1) {
if ((argc == 2 && (int)strlen(argv[1]) >= 2) &&
(argv[1][0] == '-' && argv[1][1] == 'd')) {
Debug = 1;
} else {
(void) fprintf(stderr,
"%s: Wrong number of arguments\n", prog_name);
(void) fprintf(stderr,
"Usage: %s [-debug]\n", prog_name);
exit(2);
}
}
if (defopen(UTMP_DEFAULT) == 0) {
if ((defp = defread("SCAN_PERIOD=")) != NULL)
if (validate_default(defp, &Poll_timeout) == -1) {
(void) snprintf(msg, sizeof (msg), "SCAN_PERIOD"
" should be a positive integer, found %s",
defp);
nonfatal(msg);
}
dprintf(("Poll timeout set to %d\n", Poll_timeout));
if ((defp = defread("WTMPX_UPDATE_FREQ=")) != NULL)
if (validate_default(defp, &WTMPX_ufreq) == -1) {
(void) snprintf(msg, sizeof (msg),
"WTMPX_UPDATE_FREQ should be a positive "
"integer, found %s", defp);
nonfatal(msg);
}
dprintf(("WTMPX update frequency set to %d\n", WTMPX_ufreq));
if ((defp = defread("MAX_FDS=")) != NULL)
if (validate_default(defp, &Max_fds) == -1) {
(void) snprintf(msg, sizeof (msg), "MAX_FDS "
"should be a positive integer, found %s",
defp);
nonfatal(msg);
}
dprintf(("Max fds set to %d\n", Max_fds));
(void) defopen((char *)NULL);
}
if (Debug == 0) {
if (fork()) {
exit(0);
}
(void) close(0);
(void) close(1);
(void) close(2);
(void) open("/dev/null", O_RDONLY);
(void) open("/dev/null", O_WRONLY);
(void) open("/dev/null", O_WRONLY);
(void) setsid();
}
openlog(prog_name, LOG_PID, LOG_DAEMON);
warn_utmp();
if ((pidtable = malloc(Max_fds * sizeof (struct pidentry))) == NULL)
fatal("Malloc failed");
if ((fdtable = malloc(Max_fds * sizeof (pollfd_t))) == NULL)
fatal("Malloc failed");
if (getrlimit(RLIMIT_NOFILE, &rlim) == 0) {
rlim.rlim_cur = Max_fds + EXTRA_MARGIN + 1;
rlim.rlim_max = Max_fds + EXTRA_MARGIN + 1;
if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
fatal("Out of File Descriptors");
}
} else
fatal("getrlimit returned failure");
(void) enable_extended_FILE_stdio(-1, -1);
if ((WTMPXfd = open(WTMPX_FILE, O_RDONLY)) < 0)
nonfatal("WARNING: unable to open " WTMPX_FILE " for update.");
curtime = time(NULL);
dprintf(("utmp warning timer set to %d seconds\n", WARN_TIME));
for (i = 0; i < MAX_RESETS; i++) {
load_tables();
while (wait_for_pids() == 1) {
now = time(NULL);
if ((now - curtime) >= WARN_TIME) {
dprintf(("utmp warning timer expired\n"));
warn_utmp();
curtime = now;
}
}
}
(void) close(WTMPXfd);
fatal("Too many resets, giving up");
return (1);
}
static void
load_tables()
{
int i;
dprintf(("Load tables\n"));
for (i = 0; i < pidcnt; i++)
(void) close(fdtable[i].fd);
pidcnt = 0;
Pfd = -1;
setup_pipe();
scan_utmps();
}
static int
wait_for_pids()
{
register struct pollfd *pfd;
register int i;
pid_t pid;
int ret_val = 0;
int timeout;
static time_t last_timeout = 0;
static int bad_error = 0;
if (last_timeout == 0)
last_timeout = time(NULL);
if ((timeout = Poll_timeout - (time(NULL) - last_timeout)) <= 0) {
timeout = Poll_timeout;
last_timeout = time(NULL);
scan_utmps();
}
fdtable[0].events = POLLRDNORM;
for (i = 0; i < (timeout / WTMPX_ufreq); i++) {
while ((ret_val = poll(fdtable, pidcnt, WTMPX_ufreq*1000)) < 0)
if (errno == EAGAIN)
(void) sleep(2);
else
fatal("poll");
(void) pread(WTMPXfd, (void *)&pid, sizeof (pid), 0);
if (ret_val)
break;
}
if (ret_val == 0) {
last_timeout = time(NULL);
scan_utmps();
return (1);
}
if (fdtable[0].revents & POLLRDNORM) {
drain_pipe();
fdtable[0].revents = 0;
ret_val--;
}
(void) sleep(5);
for (i = pidcnt - 1; i > 0; i--) {
if (ret_val == 0)
break;
pfd = &fdtable[i];
if (pfd->fd < 0) {
rem_pid((pid_t)0, i, DONT_CLEAN);
continue;
}
if (pfd->revents & POLLHUP) {
psinfo_t psinfo;
if (pread(pfd->fd, &psinfo, sizeof (psinfo), (off_t)0)
!= sizeof (psinfo)) {
dprintf(("! %d: terminated, status 0x%.4x\n", \
(int)pidtable[i].pl_pid, psinfo.pr_wstat));
pidtable[i].pl_status = psinfo.pr_wstat;
} else {
dprintf(("! %d: terminated\n", \
(int)pidtable[i].pl_pid));
pidtable[i].pl_status = 0;
}
rem_pid((pid_t)0, i, CLEANIT);
ret_val--;
continue;
}
if (pfd->revents & (POLLNVAL|POLLERR)) {
dprintf(("Poll Err = %d pid = %d i = %d\n", \
pfd->revents, (int)pidtable[i].pl_pid, i));
pid = pidtable[i].pl_pid;
if (pfd->revents & POLLNVAL) {
rem_pid((pid_t)0, i, DONT_CLEAN);
} else {
rem_pid((pid_t)0, i, DONT_CLEAN);
add_pid(pid);
}
if (bad_error++ > MAX_POLL_ERRS) {
bad_error = 0;
return (0);
}
ret_val--;
continue;
}
if (pfd->revents != 0) {
dprintf(("%d: unknown err %d\n", \
(int)pidtable[i].pl_pid, pfd->revents));
rem_pid((pid_t)0, i, DONT_CLEAN);
ret_val--;
if (bad_error++ > MAX_POLL_ERRS) {
bad_error = 0;
return (0);
}
return (1);
}
}
return (1);
}
static void
scan_utmps()
{
struct utmpx *utmpx;
int i;
dprintf(("Scan utmps\n"));
setutxent();
while ((utmpx = getutxent()) != NULL) {
if (utmpx->ut_type == USER_PROCESS) {
if (proc_is_alive(utmpx->ut_pid)) {
if (find_pid(utmpx->ut_pid, &i) == 0)
add_pid(utmpx->ut_pid);
} else {
if (find_pid(utmpx->ut_pid, &i) == 1)
rem_pid(utmpx->ut_pid, i, CLEANIT);
else
clean_utmpx_ent(utmpx);
}
}
}
endutxent();
}
static void
setup_pipe()
{
struct statvfs statvfs_buf;
if (Pfd < 0) {
if ((statvfs(UTMPPIPE_DIR, &statvfs_buf) == 0) &&
((statvfs_buf.f_flag & ST_RDONLY) == 0)) {
(void) unlink(UTMPPIPE);
(void) mknod(UTMPPIPE, S_IFIFO | 0600, 0);
}
Pfd = open(UTMPPIPE, O_RDWR | O_NDELAY);
}
if (Pfd < 0)
nonfatal(UTMPPIPE);
if (Pfd >= 0) {
(void) ioctl(Pfd, I_SRDOPT, RMSGD);
}
add_pid(0);
fdtable[0].fd = Pfd;
fdtable[0].events = POLLRDNORM;
}
static void
drain_pipe()
{
struct pidrec prec;
register struct pidrec *p = ≺
int bytes_read;
int i;
for (;;) {
if ((bytes_read = read(Pfd, p, sizeof (struct pidrec))) !=
sizeof (struct pidrec)) {
if (bytes_read > 0)
while (read(Pfd, p, sizeof (struct pidrec)) > 0)
;
return;
}
dprintf(("drain_pipe: Recd command %d, pid %d\n",
p->pd_type, (int)p->pd_pid));
switch (p->pd_type) {
case ADDPID:
if (find_pid(p->pd_pid, &i) == 0)
add_pid(p->pd_pid);
break;
case REMPID:
rem_pid(p->pd_pid, -1, DONT_CLEAN);
break;
default:
nonfatal("Bad message on utmppipe\n");
break;
}
}
}
static void
add_pid(pid_t pid)
{
int fd = 0;
int i = 0, move_amt;
int j;
static int first_time = 1;
if (pidcnt != 0 && (find_pid(pid, &j) == 1 || pid == 0))
return;
if (pidcnt >= Max_fds) {
if (first_time == 1) {
nonfatal("File Descriptor limit exceeded");
first_time = 0;
}
return;
}
if (pid != 0 && (fd = proc_to_fd(pid)) == -1) {
return;
}
if (pidcnt != 0) {
for (i = 0; i < pidcnt; i++) {
if (pid <= pidtable[i].pl_pid)
break;
}
if (i != pidcnt && pid != pidtable[i].pl_pid) {
move_amt = pidcnt - i;
if (move_amt != 0) {
(void) memmove(&pidtable[i+1], &pidtable[i],
move_amt * sizeof (struct pidentry));
(void) memmove(&fdtable[i+1], &fdtable[i],
move_amt * sizeof (pollfd_t));
}
}
}
fdtable[i].events = 0;
fdtable[i].revents = 0;
fdtable[i].fd = fd;
pidtable[i].pl_pid = pid;
pidcnt++;
dprintf((" add_pid: pid = %d fd = %d index = %d pidcnt = %d\n",
(int)pid, fd, i, pidcnt));
}
static void
rem_pid(pid_t pid, int i, int clean_it)
{
int move_amt;
dprintf((" rem_pid: pid = %d i = %d", (int)pid, i));
if ((i == -1 && pid == 0) || (i == 0)) {
dprintf((" - attempted to remove proc 0\n"));
return;
}
if (i != -1 || find_pid(pid, &i) == 1) {
(void) close(fdtable[i].fd);
dprintf((" fd = %d\n", fdtable[i].fd));
if (clean_it == CLEANIT)
clean_entry(i);
move_amt = (pidcnt - i) - 1;
(void) memmove(&pidtable[i], &pidtable[i+1],
move_amt * sizeof (struct pidentry));
(void) memmove(&fdtable[i], &fdtable[i+1],
move_amt * sizeof (pollfd_t));
pidcnt--;
}
if (i == -1)
dprintf((" - entry not found \n"));
}
static int
find_pid(pid_t pid, int *i)
{
struct pidentry pe;
struct pidentry *p;
pe.pl_pid = pid;
p = bsearch(&pe, pidtable, pidcnt, sizeof (struct pidentry), pidcmp);
if (p == NULL)
return (0);
else {
*i = p - (struct pidentry *)pidtable;
return (1);
}
}
static int
pidcmp(struct pidentry *a, struct pidentry *b)
{
if (b == NULL || a == NULL)
return (0);
return (a->pl_pid - b->pl_pid);
}
static int
proc_to_fd(pid_t pid)
{
char procname[64];
int fd, dfd;
(void) sprintf(procname, "/proc/%d/psinfo", (int)pid);
if ((fd = open(procname, O_RDONLY)) >= 0) {
if (fd < EXTRA_MARGIN) {
dfd = fcntl(fd, F_DUPFD, EXTRA_MARGIN);
if (dfd > 0) {
(void) close(fd);
fd = dfd;
}
}
(void) fcntl(fd, F_SETFD, 1);
return (fd);
}
if (errno == ENOENT)
return (-1);
if (errno == EMFILE) {
fatal("Out of file descriptors");
}
fatal(procname);
return (-1);
}
static void
clean_entry(int i)
{
struct utmpx *u;
if (pidcnt == 0)
return;
dprintf((" Cleaning %d\n", (int)pidtable[i].pl_pid));
if (proc_is_alive(pidtable[i].pl_pid)) {
dprintf((" Bad attempt to clean %d\n",
(int)pidtable[i].pl_pid));
return;
}
setutxent();
while ((u = getutxent()) != NULL) {
if (u->ut_pid == pidtable[i].pl_pid) {
if (u->ut_type == USER_PROCESS) {
clean_utmpx_ent(u);
}
}
}
endutxent();
}
static void
clean_utmpx_ent(struct utmpx *u)
{
dprintf((" clean_utmpx_ent: %d\n", (int)u->ut_pid));
u->ut_type = DEAD_PROCESS;
(void) time(&u->ut_xtime);
(void) pututxline(u);
updwtmpx(WTMPX_FILE, u);
}
static void
fatal(char *str)
{
int oerrno = errno;
syslog(LOG_ALERT, "%s", str);
if (Debug == 1) {
if ((errno = oerrno) != 0)
perror(prog_name);
dprintf(("%s\n", str));
}
exit(1);
}
static void
nonfatal(char *str)
{
syslog(LOG_WARNING, "%s", str);
if (Debug == 1) {
if (errno != 0)
perror(prog_name);
dprintf(("%c%s\n", 7, str));
print_tables();
(void) sleep(5);
}
}
static void
print_tables()
{
int i;
if (Debug == 0)
return;
dprintf(("pidtable: "));
for (i = 0; i < pidcnt; i++)
dprintf(("%d: %d ", i, (int)pidtable[i].pl_pid));
dprintf(("\n"));
dprintf(("fdtable: "));
for (i = 0; i < pidcnt; i++)
dprintf(("%d: %d ", i, fdtable[i].fd));
dprintf(("\n"));
}
static int
proc_is_alive(pid_t pid)
{
char psinfoname[64];
int fd;
psinfo_t psinfo;
if (kill(pid, 0) != 0)
return (0);
(void) sprintf(psinfoname, "/proc/%d/psinfo", (int)pid);
if ((fd = open(psinfoname, O_RDONLY)) < 0 ||
read(fd, &psinfo, sizeof (psinfo)) != sizeof (psinfo)) {
psinfo.pr_nlwp = 0;
}
if (fd >= 0)
(void) close(fd);
return (psinfo.pr_nlwp != 0);
}
static void
warn_utmp()
{
struct stat s;
if (lstat(UTMP_FILE, &s) == 0 &&
s.st_size % sizeof (struct utmp) == 0) {
nonfatal("WARNING: /var/adm/utmp exists!\nSee "
"utmp(5) for more information");
}
}
static int
validate_default(char *defp, int *flag)
{
long lval;
char *endptr;
errno = 0;
lval = strtol(defp, &endptr, 10);
if (errno != 0 || lval > INT_MAX || lval <= 0)
return (-1);
while (isspace(*endptr) != 0)
endptr++;
if (*endptr != '\0')
return (-1);
*flag = lval;
return (0);
}