/* nasty linux-/solaris2-specific code */
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <dirent.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>

int timeout;

void sigusr1(int sig)
{
    signal(SIGUSR1, sigusr1);
    write(1, "\07", 1);
}

void sigalrm(int sig)
{
    if (++timeout >= 2)
	exit(0);
    signal(SIGALRM, sigalrm);
    alarm(60);
    write(1, "K", 1);
}

int main(int argc, char **argv)
{
    if (argc < 2) {
	FILE *f;
	char buf[80];
	if ((f = fopen(getenv("MAIL"), "r")) != 0) {
	    while (!feof(f))
		if (fgets(buf, sizeof(buf), f) != 0)
		    if (!strncmp(buf, "From: ", 6) &&
			strncmp(buf + 6, "Mail System Internal Data", 25)
			) {
			write(1, "\07", 1);
			break;
		    }
	    fclose(f);
	}
	signal(SIGUSR1, sigusr1);
	sigalrm(SIGALRM);
	for (;;) {
	    errno = 0;
	    if (read(0, buf, 1) > 0)
		timeout = 0;
	    else if (errno != EINTR)
		return 0;
	}
    } else {
	DIR *dir;
	struct dirent *de;
	struct stat st;
	int fd, ps;
	char name[50] = "/proc/";
	if ((dir = opendir("/proc")) != 0) {
	    while ((de = readdir(dir)) != 0) {
		strcpy(name + 6, de->d_name);
#ifdef __linux__
		strcat(name + 6, "/status");
#else /* solaris */
		strcat(name + 6, "/psinfo");
#endif
		if (!stat(name, &st) && st.st_uid == getuid()) {
		    if ((fd = open(name, O_RDONLY)) > 0) {
#ifdef __linux__
			char buf[0x100];
			read(fd, &buf, 0x100);
			close(fd);
			if (!strncmp(buf, "Name:\ttunnelk\n", 14)) {
#else /* solaris */
			char buf[0x68];
			read(fd, &buf, 0x68);
			close(fd);
			if (!strncmp(buf + 0x58, "tunnelk\00", 8)) {
#endif
			    if (sscanf(de->d_name, "%d", &ps) == 1
				&& ps != getpid()) {
				kill(ps, SIGUSR1);
				closedir(dir);
				return 0;
			    }
			}
		    }
		}
	    }
	    closedir(dir);
	}
	/* change this to "return 1;" if you NEED a meaningful return code */
	return 0;
    }
}

