/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2014, 2015 Shruti V Sampat <shrutisampat@gmail.com>
*/
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
/* Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T */
/* All Rights Reserved */
/*
* Portions of such source code were derived from Berkeley 4.3 BSD
* under license from the Regents of the University of California.
*/
/*
* utmpd - utmp daemon
*
* This program receives requests from pututxline(3)
* via a named pipe to watch the process to make sure it cleans up
* its utmpx entry on termination.
* The program keeps a list of procs
* and uses poll() on their /proc files to detect termination.
* processes that aren't in the table so they can be watched.
*
* If utmpd doesn't hear back over the pipe from pututline(3) that
* the process has removed its entry it cleans the entry when the
* the process terminates.
* The AT&T Copyright above is there since we borrowed the pipe
* mechanism from init(1m).
*/
#include <signal.h>
#include <stdio.h>
#include <stdio_ext.h>
#include <unistd.h>
#include <utmpx.h>
#include <errno.h>
#include <termio.h>
#include <ctype.h>
#include <fcntl.h>
#include <time.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>
/*
* Memory allocation keyed off MAX_FDS
*/
/*
* MAX_POLLNV & RESETS - paranoia to cover an error case that might not exist
*/
/*
* The pidrec structure describes the data shipped down the pipe to
* us from the pututxline() library in
*/
/*
* pd_type's
*/
struct pidrec {
};
/*
* Since this program uses poll(2) and poll takes an array of file descriptors
* as an argument we maintain our data in tables.
* One table is the file descriptor array for poll, another parallel
* array is a table which contains the process ID of the corresponding
* open fd. These tables are kept sorted by process ID for quick lookups.
*/
struct pidentry {
};
/*
* This program has three main components plus utilities and debug routines
* Receiver - receives the process ID or process for us to watch.
* (Uses a named pipe to get messages)
* Watcher - Use poll(2) to watch for processes to die so they
* can be cleaned up (get marked as DEAD_PROCESS)
* Scanner - periodically scans the utmpx file for stale entries
* or live entries that we don't know about.
*/
static int wait_for_pids(); /* Watcher - uses poll */
static void scan_utmps(); /* Scanner, reads utmpx file */
static void drain_pipe(); /* Receiver - reads mesgs over UTMPPIPE */
static void setup_pipe(); /* For setting up receiver */
static void add_pid(); /* Adds a process to the table */
static void rem_pid(); /* Removes a process from the table */
static int find_pid(); /* Finds a process in the table */
static int proc_to_fd(); /* Takes a pid and returns an fd for its proc */
static void load_tables(); /* Loads up the tables the first time around */
static int pidcmp(); /* For sorting pids */
static void clean_entry(); /* Removes entry from our table and calls ... */
static void clean_utmpx_ent(); /* Cleans a utmpx entry */
static void nonfatal(); /* Prints error message */
static void print_tables(); /* Prints out internal tables for Debug */
static void warn_utmp(void);
/* Validate defaults from file and assign */
/*
* main() - Main does basic setup and calls wait_for_pids() to do the work
*/
int
{
char *defp;
int i;
if (getuid() != 0) {
"You must be root to run this program\n");
fatal("You must be root to run this program");
}
if (argc > 1) {
Debug = 1;
} else {
"%s: Wrong number of arguments\n", prog_name);
"Usage: %s [-debug]\n", prog_name);
exit(2);
}
}
/*
* Read defaults file for poll timeout, WTMPX update frequency
* and maximum number of processes to monitor.
*/
if (defopen(UTMP_DEFAULT) == 0) {
" should be a positive integer, found %s",
defp);
}
"WTMPX_UPDATE_FREQ should be a positive "
"integer, found %s", defp);
}
/*
* Paranoia - if polling on large number of FDs is expensive /
* buggy the number can be set lower in the field.
*/
"should be a positive integer, found %s",
defp);
}
}
if (Debug == 0) {
/*
* Daemonize ourselves
*/
if (fork()) {
exit(0);
}
(void) close(0);
(void) close(1);
(void) close(2);
/*
* We open these to avoid accidentally writing to a proc file
*/
(void) setsid(); /* release process from tty */
}
warn_utmp(); /* check to see if utmp came back by accident */
/*
* Allocate the pidtable and fdtable. An earlier version did
* this as we go, but this is simpler.
*/
fatal("Malloc failed");
fatal("Malloc failed");
/*
* Up the limit on FDs
*/
fatal("Out of File Descriptors");
}
} else
fatal("getrlimit returned failure");
/*
* Loop here scanning the utmpx file and waiting for processes
* to terminate. Most of the activity is directed out of wait_for_pids.
* If wait_for_pids fails we reload the table and try again.
*/
for (i = 0; i < MAX_RESETS; i++) {
load_tables();
while (wait_for_pids() == 1) {
dprintf(("utmp warning timer expired\n"));
warn_utmp();
}
}
}
/*
* We only get here if we had a bunch of resets - so give up
*/
fatal("Too many resets, giving up");
return (1);
}
/*
* load_tables() - Designed to be called repeatedly if we need to
* restart things. Zeros the pidcount, and loads
* the tables by scanning utmpx
*/
static void
{
int i;
dprintf(("Load tables\n"));
/*
* Close any open files.
*/
for (i = 0; i < pidcnt; i++)
pidcnt = 0;
Pfd = -1;
setup_pipe(); /* Setup the pipe to receive messages */
scan_utmps(); /* Read in USER procs entries to watch */
}
/*
* *** The Watcher ***
*
* Wait_for_pids - wait for the termination of a process in the table.
* Returns 1 on normal exist, 0 on failure.
*/
static int
{
register int i;
int ret_val = 0;
int timeout;
/*
* First time through we initialize last_timeout to now.
*/
if (last_timeout == 0)
/*
* Recalculate timeout - checking to see if time expired.
*/
scan_utmps();
}
for (i = 0; i < (timeout / WTMPX_ufreq); i++) {
/*
* Loop here while getting EAGAIN
*/
(void) sleep(2);
else
fatal("poll");
/*
* The results of pread(2) are discarded; we only want
* to update the access time of WTMPX_FILE.
* Periodically touching WTMPX helps determine when the
* OS became unavailable when the OS boots again .
* See PSARC 2004/462 for more information.
*/
if (ret_val) /* file descriptor(s) need attention */
break;
}
/*
* If ret_val == 0 the poll timed out - reset last_time and
* call scan_utmps
*/
if (ret_val == 0) {
scan_utmps();
return (1);
}
/*
* Check the pipe file descriptor
*/
drain_pipe();
ret_val--;
}
/*
* We got here because the status of one of the pids that
* we are polling on has changed, so search the table looking
* for the entry.
*
* The table is scanned backwards so that entries can be removed
* while we go since the table is compacted from high down to low
*/
for (i = pidcnt - 1; i > 0; i--) {
/*
* Break out of the loop if we've processed all the entries.
*/
if (ret_val == 0)
break;
continue;
}
/*
* POLLHUP - Process terminated
*/
!= sizeof (psinfo)) {
dprintf(("! %d: terminated, status 0x%.4x\n", \
} else {
dprintf(("! %d: terminated\n", \
}
/*
* PID gets removed when terminated only
*/
ret_val--;
continue;
}
/*
* POLLNVAL and POLLERR
* These error's shouldn't occurr but until their fixed
* we perform some simple error recovery.
*/
dprintf(("Poll Err = %d pid = %d i = %d\n", \
/*
* If its POLLNVAL we just remove the process for
* now, it will get picked up in the next scan.
* POLLERR pids get re-added after being deleted.
*/
} else { /* Else... POLLERR */
}
if (bad_error++ > MAX_POLL_ERRS) {
bad_error = 0;
return (0); /* 0 Indicates severe error */
}
ret_val--;
continue;
}
/*
* No more bits should be set in revents but check anyway
*/
dprintf(("%d: unknown err %d\n", \
ret_val--;
if (bad_error++ > MAX_POLL_ERRS) {
bad_error = 0;
return (0); /* 0 Indicates severe error */
}
return (1);
}
}
return (1); /* 1 Indicates Everything okay */
}
/*
* *** The Scanner ***
*
* scan_utmps() - Scan the utmpx file.
* For each USER_PROCESS check
* if its alive or dead. If alive and its not in
* our table to be watched, put it there. If its
* dead, remove it from our table and clean it up.
*/
static void
{
int i;
dprintf(("Scan utmps\n"));
/*
* Scan utmpx.
*/
setutxent();
/*
* Is the process alive?
*/
/*
* Yes, the process is alive, so add it if we
* don't have it in our table.
*/
} else {
/*
* No, the process is dead, so remove it if its
* in our table, otherwise just clean it.
*/
else
}
}
}
/*
* Close it to flush the buffer.
*/
endutxent();
}
/*
* *** Receiver Routines ***
*/
/*
* setup_pipe - Set up the pipe to read pids over
*/
static void
{
/*
* This code & comments swiped from init and left stock since it works
*/
if (Pfd < 0) {
}
}
if (Pfd < 0)
/*
* This code from init modified to be poll based instead of SIGPOLL,
* signal based.
*/
if (Pfd >= 0) {
/*
* Read pipe in message discard mode. When read reads a
* pidrec size record, the remainder of the message will
* be discarded. Though there shouldn't be any it will
* help resynch if someone else wrote some garbage.
*/
}
/*
* My code. We use slot 0 in the table to hold the fd of the pipe
*/
add_pid(0); /* Proc 0 guaranteed to get slot 0 */
}
/*
* drain_pipe() - The receiver routine that reads the pipe
*/
static void
{
int bytes_read;
int i;
for (;;) {
/*
* Important Note: Either read will really fail (in which case
* return is all we can do) or will get EAGAIN (Pfd was opened
* O_NDELAY), in which case we also want to return.
*/
sizeof (struct pidrec)) {
/*
* Something went wrong reading, so read until pipe
* is empty
*/
if (bytes_read > 0)
;
return;
}
dprintf(("drain_pipe: Recd command %d, pid %d\n",
switch (p->pd_type) {
case ADDPID:
/*
* Check if we already have the process, adding it
* if we don't.
*/
break;
case REMPID:
break;
default:
nonfatal("Bad message on utmppipe\n");
break;
}
}
}
/*
* *** Utilities for add and removing entries in the tables ***
*/
/*
* add_pid - add a pid to the fd table and the pidtable.
* these tables are sorted tables for quick lookups.
*
*/
static void
{
int fd = 0;
int i = 0, move_amt;
int j;
/*
* Check to see if the pid is already in our table, or being passed
* pid zero.
*/
return;
if (first_time == 1) {
/*
* Print this error only once
*/
nonfatal("File Descriptor limit exceeded");
first_time = 0;
}
return;
}
/*
* Open the /proc file checking if there's still a valid proc file.
*/
/*
* No so the process died before we got to watch for him
*/
return;
}
/*
* We only do this code if we're not putting in the first element
* Which we know will be for proc zero which is used by setup_pipe
* for its pipe fd.
*/
if (pidcnt != 0) {
for (i = 0; i < pidcnt; i++) {
break;
}
/*
* Handle the case where we're not sticking our entry on the
* the end, or overwriting an existing entry.
*/
/*
* Move table down
*/
if (move_amt != 0) {
}
}
}
/*
* Fill in the events field for poll and copy the entry into the array
*/
/*
* Likewise, setup pid field and pointer (index) to the fdtable entry
*/
pidcnt++; /* Bump the pid count */
dprintf((" add_pid: pid = %d fd = %d index = %d pidcnt = %d\n",
}
/*
* rem_pid - Remove an entry from the table and check to see if its
* not in the utmpx file.
* If i != -1 don't look up the pid, use i as index
*
* pid - Pid of process to clean or 0 if we don't know it
*
* i - Index into table or -1 if we need to look it up
*
* clean_it - Clean the entry, or just remove from table?
*/
static void
{
int move_amt;
/*
* Don't allow slot 0 in the table to be removed - utmppipe fd
*/
if ((i == -1 && pid == 0) || (i == 0)) {
dprintf((" - attempted to remove proc 0\n"));
return;
}
clean_entry(i);
/*
* Remove entries from the tables.
*/
/*
* decrement the pid count - one less pid to worry about
*/
pidcnt--;
}
if (i == -1)
dprintf((" - entry not found \n"));
}
/*
* find_pid - Returns an index into the pidtable of the specifed pid,
* else -1 if not found
*/
static int
{
struct pidentry *p;
if (p == NULL)
return (0);
else {
return (1);
}
}
/*
* Pidcmp - Used by besearch for sorting and finding process IDs.
*/
static int
{
return (0);
}
/*
* proc_to_fd - Take a process ID and return an open file descriptor to the
* /proc file for the specified process.
*/
static int
{
/*
* dup the fd above the low order values to assure
* stdio works for other fds - paranoia.
*/
if (fd < EXTRA_MARGIN) {
if (dfd > 0) {
}
}
/*
* More paranoia - set the close on exec flag
*/
return (fd);
}
return (-1);
/*
* This is fatal, since libc won't be able to allocate
* any fds for the pututxline() routines
*/
fatal("Out of file descriptors");
}
return (-1);
}
/*
* *** Utmpx Cleaning Utilities ***
*/
/*
* Clean_entry - Cleans the specified entry - where i is an index
* into the pid_table.
*/
static void
clean_entry(int i)
{
struct utmpx *u;
if (pidcnt == 0)
return;
/*
* Double check if the process is dead.
*/
dprintf((" Bad attempt to clean %d\n",
return;
}
/*
* Find the entry that corresponds to this pid.
* Do nothing if entry not found in utmpx file.
*/
setutxent();
if (u->ut_type == USER_PROCESS) {
clean_utmpx_ent(u);
}
}
}
endutxent();
}
/*
* clean_utmpx_ent - Clean a utmpx entry
*/
static void
{
u->ut_type = DEAD_PROCESS;
(void) pututxline(u);
updwtmpx(WTMPX_FILE, u);
/*
* XXX update wtmp for ! nonuserx entries?
*/
}
/*
* *** Error Handling and Debugging Routines ***
*/
/*
* fatal - Catastrophic failure
*/
static void
{
if (Debug == 1) {
}
exit(1);
}
/*
* nonfatal - Non-Catastrophic failure - print message and errno
*/
static void
{
if (Debug == 1) {
if (errno != 0)
print_tables();
}
}
/*
* print_tables - Print internal tables - for debugging
*/
static void
{
int i;
if (Debug == 0)
return;
dprintf(("pidtable: "));
for (i = 0; i < pidcnt; i++)
dprintf(("\n"));
dprintf(("fdtable: "));
for (i = 0; i < pidcnt; i++)
dprintf(("\n"));
}
/*
* proc_is_alive - Check to see if a process is alive AND its
* not a zombie. Returns 1 if process is alive
* and zero if it is dead or a zombie.
*/
static int
{
int fd;
return (0); /* Kill failed - no process */
/*
* The process exists, so check if it's a zombie.
*/
/*
* We either couldn't open the proc, or we did but the
* read of the psinfo file failed, so pid is nonexistent.
*/
}
if (fd >= 0)
/* if pr_nlwp == 0, process is a zombie */
}
/*
* be used. Applications that try to directly manipulate
* it may cause problems. Since the file is no longer
* shipped, if it appears on a system it's because an
* old application created it. We'll have utmpd
* complain about it periodically.
*/
static void
{
struct stat s;
"utmp(4) for more information");
}
}
/*
* validate_default - validate and assign defaults.
*/
static int
{
long lval;
char *endptr;
errno = 0;
return (-1);
endptr++;
if (*endptr != '\0')
return (-1);
return (0);
}