#ifndef lint
static char rcsid[] = "$Header: linux-1.c,v 1.1 1994/11/12 20:21:04 forys Exp $";
#endif

/*
**  This program may be freely redistributed for noncommercial purposes.
**  This entire comment MUST remain intact.
**
**  Linux support by Chuck L. Blake (chuckb@Alice.Wonderland.Caltech.EDU)
**
**  Copyright 1994 by Jeff Forys (jeff@forys.cranbury.nj.us)
*/

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

#include <sys/time.h>
#include <sys/resource.h>	/* for [get|set]priority() */
#include <linux/fs.h>		/* for MINOR() macro */

#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

extern int MissedProcCnt;

/*
 * 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", "ABRT",		/*  1 -  6 */
	"BUS", "FPE", "KILL", "USR1", "SEGV", "USR2",		/*  7 - 12 */
	"PIPE", "ALRM", "TERM", "STKFLT", "CHLD", "CONT",	/* 13 - 18 */
	"STOP", "TSTP", "TTIN", "TTOU", "IO", "XCPU",		/* 19 - 24 */
	"XFSZ", "VTALRM", "PROF", "WINCH", "LOST", "PWR",	/* 25 - 30 */
	"UNUSED" 
};

int NSig = 31;

#define	SETCMD(dst,src,maxlen) {			\
	extern char *strrchr();				\
	if (maxlen > 0) src[maxlen] = '\0';		\
	dst = (dst = strrchr(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 skill_getpri(int *low, int *high);

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 = (strstr(ProgName, "snice") == NULL);

	/*
	 * 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;

	/*
	 * 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);
	}
}

/*
 * 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.
 */

#include <fcntl.h>
char *SysErr();

static char *ProcDir =	"/proc";		/* proc directory */
static char *ProcFil =	"/proc/%s/stat";	/* name of only needed file */

#define MXBUF 1024
	static char buf[MXBUF];	/* primary storage for file io */
/*
 * GetProc()
 *
 * Fill in and return a `struct ProcInfo' with information about the
 * next process.  If no processes are left, return NULL.
 */
struct ProcInfo *
GetProc()
{
	static struct ProcInfo procinfo;
	static DIR *dirfp = NULL;
	struct dirent *dp;
	char flnm[FILENAME_MAX];
	int fd;

	int n;		/* first for length of buf[], then as a loop counter */
	char* tmp;	/* pointer into buf[] */
	struct stat sb;	/* stat() buffer, used to get UID */

	/*
	 * If this is our first time here, open the proc directory,...
	 */
	if (dirfp == NULL && (dirfp=opendir(ProcDir)) == NULL) {
		fprintf(stderr, "%s: %s: %s\n", ProgName, ProcDir, SysErr());
		exit(EX_SERR);
	}

	while ((dp = readdir(dirfp)) != NULL) {
		if (dp->d_name[0] < '0' || dp->d_name[0] > '9')
			continue;
		(void) sprintf(flnm, ProcFil, dp->d_name);
		if ((fd = open(flnm, O_RDONLY)) < 0) {
			MissedProcCnt++;
			continue;	/* ignore procs we can't read */
		}

		fstat(fd, &sb);		/* uid = owner-id of /proc/PID/stat */
		procinfo.pi_uid = sb.st_uid;

		if ((n = read(fd, buf, MXBUF-1)) == -1)
			continue;
		buf[n] = '\0';		/* terminate the string */
		(void) close(fd);

/* Split buf into "PID (cmd)" and "state ppid pgrp sess tty ... 28 more"   */
/* This contortion is necessary because cmd could have any no. of embedded */
/* whitespace characters, while everything after (cmd) is well-defined.    */

		tmp = buf + n;		/* start tmp at end of buf */
		for(n = 33; n; n--)	/* move tmp to spc following (cmd) */
			while (*--tmp != ' ')
				;
		tmp[-1]='\0';			/* ')' --> '\0' */

		procinfo.pi_pid = atoi(buf); /* atoi("123 (cmd)") works. :-) */
		procinfo.pi_cmd = strchr(buf, '(') + 1;	/* 1st char past '(' */
		for(n = 4; n; n--)	/* move tmp to tty field */
			while (*++tmp != ' ')
				;
		procinfo.pi_tty = atoi(tmp);

		return(&procinfo);
	}

	(void) closedir(dirfp);
	dirfp = NULL;
	return((struct ProcInfo *)NULL);
}
