/* @(#)rstat_proc.c	2.2 88/08/01 4.0 RPCSRC */
#ifndef lint
static  char sccsid[] = "@(#)rpc.rstatd.c 1.1 86/09/25 Copyr 1984 Sun Micro";
#endif

/*
 * Copyright (c) 1984 by Sun Microsystems, Inc.
 */

/*
 * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
 * unrestricted use provided that this legend is included on all tape
 * media and as a part of the software program in whole or part.  Users
 * may copy or modify Sun RPC without charge, but are not authorized
 * to license or distribute it to anyone else except as part of a product or
 * program developed by the user.
 *
 * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
 * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
 *
 * Sun RPC is provided with no support and without any obligation on the
 * part of Sun Microsystems, Inc. to assist in its use, correction,
 * modification or enhancement.
 *
 * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
 * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
 * OR ANY PART THEREOF.
 *
 * In no event will Sun Microsystems, Inc. be liable for any lost revenue
 * or profits or other special, indirect and consequential damages, even if
 * Sun has been advised of the possibility of such damages.
 *
 * Sun Microsystems, Inc.
 * 2550 Garcia Avenue
 * Mountain View, California  94043
 */

/*
 * rstat service:  built with rstat.x and derived from rpc.rstatd.c
 */

#include <signal.h>
#include <stdio.h>
#include <rpc/rpc.h>
#include <sys/socket.h>
#if defined(__linux__)
#include <sys/param.h>
#include <a.out.h>
#include <fcntl.h>
#include <string.h>
#elif defined(__MINT__)
#include <ioctl.h>
#include <sys/param.h>
#include <string.h>
#include <osbind.h>
#else
#include <nlist.h>
#include <sys/dk.h>
#endif
#include <sys/errno.h>
#if defined(__linux__) || defined (__MINT__)
struct vmmeter {
	u_long v_pgpgin;
	u_long v_pgpgout;
	u_long v_pswpin;
	u_long v_pswpout;
	u_long v_intr;
	u_long v_swtch;
};
#else
#include <sys/vmmeter.h>
#endif /* __linux__ */

#include <net/if.h>
#include "rstat.h"

#if !defined(__linux__) && !defined(__MINT__)
struct nlist nl[] = {
#define	X_CPTIME	0
	{ "_cp_time" },
#define	X_SUM		1
	{ "_sum" },
#define	X_IFNET		2
	{ "_ifnet" },
#define	X_DKXFER	3
	{ "_dk_xfer" },
#define	X_BOOTTIME	4
	{ "_boottime" },
#define	X_AVENRUN	5
	{ "_avenrun" },
#define X_HZ		6
	{ "_hz" },
	"",
};
#endif /* __linux__ */

#if defined(__linux__) || defined(__MINT__)
int numintfs;			/* number of NET interfaces */
#else
int kmem;
int firstifnet, numintfs;	/* chain of ethernet interfaces */
#endif
int stats_service();

#ifdef __MINT__
#ifndef Suptime
#define Suptime(a,b)	(trap_1_wll ((short)0x13f, (long)a, (long)b))
#endif
#endif

/*
 *  Define EXIT_WHEN_IDLE if you are able to have this program invoked
 *  automatically on demand (as from inetd).  When defined, the service
 *  will terminated after being idle for 20 seconds.
 */
int sincelastreq = 0;		/* number of alarms since last request */
#ifdef EXIT_WHEN_IDLE
#define CLOSEDOWN 20		/* how long to wait before exiting */
#endif /* def EXIT_WHEN_IDLE */
#define TIMEOUT 1

union {
    struct stats s1;
    struct statsswtch s2;
    struct statstime s3;
} stats_all;

void updatestat();
static int havedisk();
static int setup();
static stat_is_init = 0;
extern int errno;

#ifndef FSCALE
#define FSCALE (1 << 8)
#endif

rstat_run()
{
#ifndef DEBUG
#ifndef EXIT_WHEN_IDLE
   daemon(1, 1);
#endif
#endif
   svc_run();
}

stat_init()
{
	stat_is_init = 1;
	setup();
	updatestat();
	alarm(TIMEOUT);
#ifdef __linux__
	signal(SIGALRM, (void *)updatestat);
#else
	signal(SIGALRM, updatestat);
#endif
}

statstime *
rstatproc_stats_3()
{
    if (! stat_is_init)
        stat_init();
    sincelastreq = 0;
    return(&stats_all.s3);
}

statsswtch *
rstatproc_stats_2()
{
    if (! stat_is_init)
        stat_init();
    sincelastreq = 0;
    return(&stats_all.s2);
}

stats *
rstatproc_stats_1()
{
    if (! stat_is_init)
        stat_init();
    sincelastreq = 0;
    return(&stats_all.s1);
}

u_int *
rstatproc_havedisk_3()
{
    static u_int have;

    if (! stat_is_init)
        stat_init();
    sincelastreq = 0;
    have = havedisk();
	return(&have);
}

u_int *
rstatproc_havedisk_2()
{
    return(rstatproc_havedisk_3());
}

u_int *
rstatproc_havedisk_1()
{
    return(rstatproc_havedisk_3());
}

void updatestat()
{
	int off, i, hz;
	struct vmmeter sum;
	struct ifnet ifnet;
	double avrun[3];
	struct timeval tm, btm;
#ifdef __MINT__
	unsigned long uptime;
#endif
#ifdef __linux__
	FILE *fp;
	char buff[128];
	double d1, d2, d3;
	unsigned long uptime;
	char *bp, *sp;
	extern double atof(const char *);
#endif /* __linux__ */

#ifdef DEBUG
	fprintf(stderr, "entering updatestat\n");
#endif
#ifdef EXIT_WHEN_IDLE
	if (sincelastreq >= CLOSEDOWN) {
#ifdef DEBUG
	fprintf(stderr, "about to closedown\n");
#endif
		exit(0);
	}
	sincelastreq++;
#endif /* def EXIT_WHEN_IDLE */
#if defined(__linux__)
	memset((char *) &stats_all, 0, sizeof(stats_all));
	hz = HZ;
	if ((fp = fopen("/proc/uptime", "r")) != NULL) {
		(void) fgets(buff, 128, fp);
		sp = strchr(buff, ' '); *sp++ = '\0';
		d1 = atof(buff); d2 = atof(sp);
		uptime = (unsigned long) d1;
		btm.tv_sec = (unsigned long) d2;
		btm.tv_usec = 0;
		(void) fclose(fp);
	}
	if ((fp = fopen("/proc/loadavg", "r")) != NULL) {
		(void) fgets(buff, 128, fp);
		sp = strchr(buff, ' '); *sp++ = '\0';
		d1 = atof(buff); bp = strchr(sp, ' '); *bp++ = '\0';
		d2 = atof(sp); d3 = atof(bp);
		stats_all.s2.avenrun[0] = d1 * FSCALE;
		stats_all.s2.avenrun[1] = d2 * FSCALE;
		stats_all.s2.avenrun[2] = d3 * FSCALE;
		(void) fclose(fp);
	}
	if ((fp = fopen("/proc/kstat", "r")) != NULL) {
		fscanf(fp, "cpu %d,%d,%d,%d\n", &stats_all.s1.cp_time[0],
		      &stats_all.s1.cp_time[1], &stats_all.s1.cp_time[2],
		      &stats_all.s1.cp_time[3]);
	}
#elif defined(__MINT__)
	memset((char *)&stats_all, 0, sizeof(stats_all));
	memset((char *)&sum, 0, sizeof(sum));

	uptime = 0;
	Suptime (&uptime, stats_all.s2.avenrun);
	if (FSCALE >= 2048) {
		stats_all.s2.avenrun[0] *= FSCALE/2048;
		stats_all.s2.avenrun[1] *= FSCALE/2048;
		stats_all.s2.avenrun[2] *= FSCALE/2048;
	} else {
		stats_all.s2.avenrun[0] /= 2048/FSCALE;
		stats_all.s2.avenrun[1] /= 2048/FSCALE;
		stats_all.s2.avenrun[2] /= 2048/FSCALE;
	}
	hz = HZ;
#else
	if (lseek(kmem, (long)nl[X_HZ].n_value, 0) == -1) {
		fprintf(stderr, "rstat: can't seek in kmem\n");
		exit(1);
	}
	if (read(kmem, (char *)&hz, sizeof hz) != sizeof hz) {
		fprintf(stderr, "rstat: can't read hz from kmem\n");
		exit(1);
	}
	if (lseek(kmem, (long)nl[X_CPTIME].n_value, 0) == -1) {
		fprintf(stderr, "rstat: can't seek in kmem\n");
		exit(1);
	}
	if (read(kmem, (char *)stats_all.s1.cp_time, sizeof (stats_all.s1.cp_time))
	    != sizeof (stats_all.s1.cp_time)) {
		fprintf(stderr, "rstat: can't read cp_time from kmem\n");
		exit(1);
	}
	if (lseek(kmem, (long)nl[X_AVENRUN].n_value, 0) ==-1) {
		fprintf(stderr, "rstat: can't seek in kmem\n");
		exit(1);
	}
#ifdef vax
	if (read(kmem, (char *)avrun, sizeof (avrun)) != sizeof (avrun)) {
		fprintf(stderr, "rstat: can't read avenrun from kmem\n");
		exit(1);
	}
	stats_all.s2.avenrun[0] = avrun[0] * FSCALE;
	stats_all.s2.avenrun[1] = avrun[1] * FSCALE;
	stats_all.s2.avenrun[2] = avrun[2] * FSCALE;
#endif
	if (lseek(kmem, (long)nl[X_BOOTTIME].n_value, 0) == -1) {
		fprintf(stderr, "rstat: can't seek in kmem\n");
		exit(1);
	}
	if (read(kmem, (char *)&btm, sizeof (stats_all.s2.boottime))
	    != sizeof (stats_all.s2.boottime)) {
		fprintf(stderr, "rstat: can't read boottime from kmem\n");
		exit(1);
	}
	stats_all.s2.boottime.tv_sec = btm.tv_sec;
	stats_all.s2.boottime.tv_usec = btm.tv_usec;
#endif	/* __linux__ */

#ifdef DEBUG
	fprintf(stderr, "%d %d %d %d\n", stats_all.s1.cp_time[0],
	    stats_all.s1.cp_time[1], stats_all.s1.cp_time[2], stats_all.s1.cp_time[3]);
#endif

#if defined(__linux__)
	if (fp != (FILE *)NULL) {
		(void) fscanf(fp, "disk %d,%d,%d,%d\n",
			&stats_all.s1.dk_xfer[0], &stats_all.s1.dk_xfer[1],
			&stats_all.s1.dk_xfer[2], &stats_all.s1.dk_xfer[3]);
		bzero((char *) &sum, sizeof (sum));
		(void) fscanf(fp, "page %d,%d\nswap %d,%d\nintr %d\nctxt %d\n",
			&sum.v_pgpgin, &sum.v_pgpgout, &sum.v_pswpin,
			&sum.v_pswpout, &sum.v_intr, &sum.v_swtch);
		(void) fclose(fp);
	}
#elif defined(__MINT__)
/* XXX */
#else
	if (lseek(kmem, (long)nl[X_SUM].n_value, 0) ==-1) {
		fprintf(stderr, "rstat: can't seek in kmem\n");
		exit(1);
	}
 	if (read(kmem, (char *)&sum, sizeof sum) != sizeof sum) {
		fprintf(stderr, "rstat: can't read sum from kmem\n");
		exit(1);
	}
#endif	/* __linux__ */
	stats_all.s1.v_pgpgin = sum.v_pgpgin;
	stats_all.s1.v_pgpgout = sum.v_pgpgout;
	stats_all.s1.v_pswpin = sum.v_pswpin;
	stats_all.s1.v_pswpout = sum.v_pswpout;
	stats_all.s1.v_intr = sum.v_intr;
	gettimeofday(&tm, (struct timezone *) 0);
#ifndef __MINT__
	stats_all.s1.v_intr -= hz*(tm.tv_sec - btm.tv_sec) +
	    hz*(tm.tv_usec - btm.tv_usec)/1000000;
	stats_all.s2.v_swtch = sum.v_swtch;
#endif

#if defined(__linux__) || defined(__MINT__)
	stats_all.s2.boottime.tv_sec = tm.tv_sec - uptime;
	stats_all.s2.boottime.tv_usec = 0;
#else
	if (lseek(kmem, (long)nl[X_DKXFER].n_value, 0) == -1) {
		fprintf(stderr, "rstat: can't seek in kmem\n");
		exit(1);
	}
 	if (read(kmem, (char *)stats_all.s1.dk_xfer, sizeof (stats_all.s1.dk_xfer))
	    != sizeof (stats_all.s1.dk_xfer)) {
		fprintf(stderr, "rstat: can't read dk_xfer from kmem\n");
		exit(1);
	}
#endif	/* __linux__ */

	stats_all.s1.if_ipackets = 0;
	stats_all.s1.if_opackets = 0;
	stats_all.s1.if_ierrors = 0;
	stats_all.s1.if_oerrors = 0;
	stats_all.s1.if_collisions = 0;
#if defined(__linux__)
	{
		struct dev_stats if_stats;
		struct ifconf ifc;
		struct ifreq *ifr;
		int fd, i;

		/* Open a channel. */
		if ((fd = open("/dev/net/socket", O_RDWR)) >= 0) {
			/* Ask the kernel about the available interfaces. */
			ifc.ifc_len = sizeof(buff);
			ifc.ifc_buf = buff;
			if (ioctl(fd, SIOCGIFCONF, &ifc) < 0) {
				fprintf(stderr, "SIOCGIFCONF: %s\n",
							strerror(errno));
				return;
  			}

			/* Loop over iface list, fetching info as we go. */
			ifr = ifc.ifc_req;
			for (i = ifc.ifc_len / sizeof(struct ifreq);
			     --i >= 0; ifr++) {
				ifr->ifr_data = (caddr_t) &if_stats;
				if (ioctl(fd, SIOCGIFSTATS, ifr) < 0) {
					memset(&if_stats, 0,
					       sizeof(struct dev_stats));
				}
				stats_all.s1.if_ipackets += if_stats.rx_packets;
				stats_all.s1.if_opackets += if_stats.tx_packets;
				stats_all.s1.if_ierrors += if_stats.rx_errors;
				stats_all.s1.if_oerrors += if_stats.tx_errors;
				stats_all.s1.if_collisions += if_stats.tx_collision;
			}
			(void) close(fd);
		}
	}
#elif defined(__MINT__)
	{
		int sock, n;
		struct ifconf ifc;
		struct ifreq ifr[40];

		sock = socket (PF_INET, SOCK_DGRAM, 0);
		if (sock >= 0) {
			ifc.ifc_len = sizeof (ifr);
			ifc.ifc_buf = ifr;
			if (ioctl (sock, SIOCGIFCONF, &ifc))
				goto bad;
			n = ifc.ifc_len / sizeof (struct ifreq);
			for (i = 0; i < n; ++i) {
				if (ifr[i].ifr_addr.sa_family != AF_INET)
					continue;
				if (ioctl (sock, SIOCGIFSTATS, &ifr[i]))
					goto bad;
				stats_all.s1.if_ipackets +=
					ifr[i].ifr_stats.in_packets;
				stats_all.s1.if_opackets +=
					ifr[i].ifr_stats.out_packets;
				stats_all.s1.if_ierrors +=
					ifr[i].ifr_stats.in_errors;
				stats_all.s1.if_oerrors +=
					ifr[i].ifr_stats.out_errors;
				stats_all.s1.if_collisions +=
					ifr[i].ifr_stats.collisions;
			}
		bad:
			close (sock);
		}
	}
#else
	for (off = firstifnet, i = 0; off && i < numintfs; i++) {
		if (lseek(kmem, (long)off, 0) == -1) {
			fprintf(stderr, "rstat: can't seek in kmem\n");
			exit(1);
		}
		if (read(kmem, (char *)&ifnet, sizeof ifnet) != sizeof ifnet) {
			fprintf(stderr, "rstat: can't read ifnet from kmem\n");
			exit(1);
		}
		stats_all.s1.if_ipackets += ifnet.if_ipackets;
		stats_all.s1.if_opackets += ifnet.if_opackets;
		stats_all.s1.if_ierrors += ifnet.if_ierrors;
		stats_all.s1.if_oerrors += ifnet.if_oerrors;
		stats_all.s1.if_collisions += ifnet.if_collisions;
		off = (int) ifnet.if_next;
	}
#endif	/* __linux__ */
	gettimeofday((struct timeval *)&stats_all.s3.curtime,
		(struct timezone *) 0);

#ifdef __linux__
	/*
	 * Need to reinstall signal handler for linux
	 */
	signal(SIGALRM, (void *)updatestat);
#endif

	alarm(TIMEOUT);
}

static 
setup()
{
#if !defined(__linux__) && !defined(__MINT__)
	struct ifnet ifnet;
	int off;

	nlist("/vmunix", nl);
	if (nl[0].n_value == 0) {
		fprintf(stderr, "rstat: Variables missing from namelist\n");
		exit (1);
	}
	if ((kmem = open("/dev/kmem", 0)) < 0) {
		fprintf(stderr, "rstat: can't open kmem\n");
		exit(1);
	}

	off = nl[X_IFNET].n_value;
	if (lseek(kmem, (long)off, 0) == -1) {
		fprintf(stderr, "rstat: can't seek in kmem\n");
		exit(1);
	}
	if (read(kmem, (char *)&firstifnet, sizeof(int)) != sizeof (int)) {
		fprintf(stderr, "rstat: can't read firstifnet from kmem\n");
		exit(1);
	}
	numintfs = 0;
	for (off = firstifnet; off;) {
		if (lseek(kmem, (long)off, 0) == -1) {
			fprintf(stderr, "rstat: can't seek in kmem\n");
			exit(1);
		}
		if (read(kmem, (char *)&ifnet, sizeof ifnet) != sizeof ifnet) {
			fprintf(stderr, "rstat: can't read ifnet from kmem\n");
			exit(1);
		}
		numintfs++;
		off = (int) ifnet.if_next;
	}
#endif
}

/*
 * returns true if have a disk
 */
static
havedisk()
{
#if defined(__linux__)
	int i, cnt;
	
	cnt = 0;
	for (i=0; i < DK_NDRIVE; i++)
		cnt += stats_all.s1.dk_xfer[i];
	return (cnt != 0);
#elif defined(__MINT__)
#define DISKDRIVES	0x0000fffcl
	return ((Drvmap () & DISKDRIVES) ? 1 : 0);
#else
	int i, cnt;
	long  xfer[DK_NDRIVE];

	nlist("/vmunix", nl);
	if (nl[X_DKXFER].n_value == 0) {
		fprintf(stderr, "rstat: Variables missing from namelist\n");
		exit (1);
	}
	if ((kmem = open("/dev/kmem", 0)) < 0) {
		fprintf(stderr, "rstat: can't open kmem\n");
		exit(1);
	}
	if (lseek(kmem, (long)nl[X_DKXFER].n_value, 0) == -1) {
		fprintf(stderr, "rstat: can't seek in kmem\n");
		exit(1);
	}
	if (read(kmem, (char *)xfer, sizeof xfer)!= sizeof xfer) {
		fprintf(stderr, "rstat: can't read kmem\n");
		exit(1);
	}
	cnt = 0;
	for (i=0; i < DK_NDRIVE; i++)
		cnt += xfer[i];
	return (cnt != 0);
#endif
}
