#ifndef lint
static char rcsid[] = "$Header: next-2.c,v 1.4 1994/06/26 04:18:20 forys Exp $";
#endif

/*
**  This program may be freely redistributed for noncommercial purposes.
**  This entire comment MUST remain intact.
**
**  NeXT OS 2.x support by Ric Anderson (ric@cs.arizona.edu)
**
**  Copyright 1994 by Jeff Forys (jeff@forys.cranbury.nj.us)
*/

#define NO_MEXTERN
#include "conf.h"
#undef  NO_MEXTERN

#include <sys/user.h>
#include <sys/proc.h>

#include <stdio.h>

/*
 * Define SigNames, NSig, and TtyDevDir here; they are used by other
 * routines and must be global.  Everyone seems to have their own
 * idea as to what NSIG should be.  Here, `NSig' is the number of
 * signals available, not counting zero.
 */
char *SigMap[] = { "0",
  "HUP", "INT", "QUIT", "ILL", "TRAP", "IOT",		/*  1 -  6 */
  "EMT", "FPE", "KILL", "BUS", "SEGV", "SYS",		/*  7 - 12 */
  "PIPE", "ALRM", "TERM", "URG", "STOP", "TSTP",	/* 13 - 18 */
  "CONT", "CHLD", "TTIN", "TTOU", "IO", "XCPU",		/* 19 - 24 */
  "XFSZ", "VTALRM", "PROF", "WINCH", "29", "USR1",	/* 25 - 30 */
  "USR2", "32"						/* 31 - 32 */
};
int NSig = NSIG;

#define	SETCMD(dst,src,maxlen) {			\
	extern char *rindex();				\
	if (maxlen > 0) src[maxlen] = '\0';		\
	dst = (dst = rindex(src, '/')) ? ++dst: src;	\
}

static char *TtyDevDir = "/dev";

int	Skill;			/* set 1 if running `skill', 0 if `snice' */
int	PrioMin, PrioMax;	/* min and max process priorities */
int	SigPri;			/* signal to send or priority to set */
pid_T	MyPid;			/* pid of this process */
uid_T	MyUid;			/* uid of this process */
char	*ProgName;		/* program name */

/*
 * This is the machine-dependent initialization routine.
 *
 *   - The following global variables must be initialized:
 *     MyPid, MyUid, ProgName, Skill, PrioMin, PrioMax, SigPri
 *   - The working directory will be changed to that which contains the
 *     tty devices (`TtyDevDir'); this makes argument parsing go faster.
 *   - If possible, this routine should raise the priority of this process.
 */
void
MdepInit(pname)
	char *pname;
{
	extern char *rindex(), *SysErr();

	MyPid = (pid_T) getpid();
	MyUid = (uid_T) getuid();
	SETCMD(ProgName, pname, 0)

	/*
	 * If we are running as root, raise our priority to better
	 * catch runaway processes.
	 */
	if (MyUid == ROOTUID)
		(void) setpriority(PRIO_PROCESS, MyPid, PRIO_MIN);

	/*
	 * Determine what we are doing to processes we find.  We will
	 * either send them a signal (skill), or renice them (snice).
	 */
	Skill = (strcmp(ProgName, "snice") != 0);

	/*
	 * chdir to `TtyDevDir' to speed up tty argument parsing.
	 */
	if (chdir(TtyDevDir) < 0) {
		fprintf(stderr, "%s: chdir(%s): %s\n", ProgName, TtyDevDir,
		        SysErr());
		exit(EX_SERR);
	}

	/*
	 * Set up minimum and maximum process priorities.
	 * Initialize SigPri to either default signal (`skill') or
	 * default priority (`snice').
	 */
	PrioMin = PRIO_MIN;
	PrioMax = PRIO_MAX;
	SigPri = Skill? SIGTERM: 4;
}

/*
 * Carry out an action on a particular process.  If this is `skill',
 * then send the process a signal, otherwise this is `snice' so change
 * it's priority.
 *
 * If 0 is returned, the operation was successful, otherwise -1 is
 * returned and `errno' set.
 */
int
MdepAction(pid)
	pid_T pid;
{
	if (Skill)
		return(kill((int)pid, SigPri));
	else
		return(setpriority(PRIO_PROCESS, (int)pid, SigPri));
}

/*
 * Now, set up everything we need to write a GetProc() routine.
 */

#undef  PI_ZOMBIE	/* #define'd in "conf.h" *and* <sys/table.h> */
#define PI_SKILL_ZOMBIE 3   /* value from "conf.h" (it *wont* change) */

#include <sys/table.h>

#define NPROCS	32767	/* max number of processes to check */
			/* Should be gotten from the kernel somehow */
extern  off_t lseek();

/*
 * GetProc()
 *
 * Fill in and return a `struct ProcInfo' with information about the
 * next process.  If no processes are left, return NULL.
 */
struct ProcInfo *
GetProc()
{   int rtn_status;
    static int procindx = 0;
    static struct ProcInfo procinfo;
    static struct tbl_procinfo proc;
    extern char *SysErr();
    extern int errno;

    /*
     * Read in one proc structure at-a-time.  Table() seems to
     * return -1 (errno = ESRCH) if you ask for a range of items
     * under NeXT OS 2.1 and some members of the range are empty.
     * I don't have any good clues on how to determine the number
     * of procs to try so I'm using NPROCS.
     * When we are finished (return NULL).
     */

    do {
	rtn_status = table(TBL_PROCINFO,procindx++,(char *) &proc,1,
          sizeof(proc));
    } while(procindx < NPROCS  &&  rtn_status < 0  &&  errno == ESRCH);
    if (procindx >= NPROCS  ||  rtn_status <= 0) {
	if (rtn_status != 0  &&  errno != ESRCH) {
	    fprintf(stderr, "%s: read proc: %s\n",
	      ProgName, SysErr());
	}
	return((struct ProcInfo *)NULL);
    }


    /*
     * Make sure this isn't a "zombie" or "exiting"
     * process.  If it is, we have all the information
     * we need; fill in procinfo and return.
     */
    procinfo.pi_flags = 0;
    procinfo.pi_pid = (pid_T) proc.pi_pid;
    procinfo.pi_uid = (uid_T) proc.pi_uid;

    if (proc.pi_status == PI_ZOMBIE) {    /* zombie */
	static char *zombie = "<defunct>";
	procinfo.pi_flags |= PI_SKILL_ZOMBIE;
	procinfo.pi_cmd = zombie;
    } else if (proc.pi_status == PI_EXITING) {
	static char *exiting = "<exiting>";
	procinfo.pi_flags |= PI_SWEXIT;
	procinfo.pi_cmd = exiting;
    }

    if (procinfo.pi_flags != 0)
      return(&procinfo);

    /*
     * We now have a non-zombie, non-exiting process.
     * Fill in the rest of `procinfo'.
     */
    if (proc.pi_ttyd != -1) { /* has a controlling tty */
	procinfo.pi_flags |= PI_CTLTTY;
	procinfo.pi_tty = (tty_T) proc.pi_ttyd;
    }

    /* set path-stripped command name */
    SETCMD(procinfo.pi_cmd, proc.pi_comm, PI_COMLEN)

    return(&procinfo);
}
