/*****************************************************************************
      loginhog - Utility to prevent multiple logins from the same user
       (C)opyright 1994-1995, B. Scott Burkett, All Rights Reserved
 ***************************************************************************** 
	MODULE: loginhog.c
 ***************************************************************************** 
       HISTORY:	initial coding		12/22/94		bsb

 *****************************************************************************
  
   Copyright (c), 1994-1995, by B. Scott Burkett
   All rights reserved.
  
   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:
  
   1. Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
   2. Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
   3. All modifications to the source code must be clearly marked as
      such.  Binary redistributions based on modified source code
      must be clearly marked as modified versions in the documentation
      and/or other materials provided with the distribution.
   4. All advertising materials mentioning features or use of this software
      must display the following acknowledgment:
        This product includes software developed by B. Scott Burkett and
        other unpaid contributors.
   5. The name of B. Scott Burkett may not be used to endorse or promote
      products derived from this software without specific prior
      written permission.
  
   THIS SOFTWARE IS PROVIDED BY B. SCOTT BURKETT AND CONTRIBUTORS "AS IS" AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   ARE DISCLAIMED.  IN NO EVENT SHALL B. SCOTT BURKETT OR CONTRIBUTORS BE LIABLE
   FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   SUCH DAMAGE.
 
 *****************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <utmp.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <utime.h>
#include <errno.h>
#include <ctype.h>
#include <regex.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/syslog.h>

#include "loginhog.h"

int main(int argc, char *argv[])
{
	Init( argc );
	Process();
	return(0);
}

/***************************************************************************
 *                                                                         *
 * void Init( int ac );                                                    *
 *                                                                         *
 * Responsible for initialization.                                         *
 *                                                                         *
 ***************************************************************************/

void Init( int ac )
{
	signal(SIGINT, suicide);
	signal(SIGTSTP, suicide);
	signal(SIGQUIT, suicide);
	signal(SIGHUP, suicide);

	ReadCFGFile();
}

void suicide(int signum)
{
	/* bwhahaa! */
	kill(getppid(), SIGTERM);
	kill(getpid(), SIGTERM);
}

void ReadCFGFile(void)
{
	FILE *cfgfile;
	int  ndx=0;

	if((cfgfile = fopen("/etc/loginhog.conf", "rt")) == NULL)
	{
		perror("fopen");
		exit(0);
	}

	while (1)
	{
		fgets(buf, 80, cfgfile);
		if(feof(cfgfile)) break;

		if(buf[0] == '#') continue;
		if(buf[0] == ';') continue;
		if(buf[0] == '%') continue;
		if(buf[0] == '\r') continue;
		if(buf[0] == '\n') continue;
		if(buf[0] == ' ') continue;
		if(buf[0] == '\t') continue;

		sscanf(buf, "%s %s", tmpcfg._username,
						 tmpcfg._ttydevice);

	
		if(ndx <= TABLE_SIZE)
		{
			memcpy( &cfg[ndx], &tmpcfg, sizeof(_CFG));
			ndx++;
		}

	}

	highentry=ndx-1;
	memset(&cfg[ndx], '\0', sizeof(_CFG));
	fclose(cfgfile);

}

/***************************************************************************
 *                                                                         *
 * void Process(void);                                                     *
 *                                                                         *
 * Main processing loop of the daemon       			           *
 *                                                                         *
 ***************************************************************************/

void Process(void)
{

	while( 1 )
	{
		userrec = getutent();
	
		if(userrec == NULL) 
			break;
	
		if(userrec->ut_type == USER_PROCESS)
		{
			if ( CheckLogins() )
			{
				if ( ValidateUser() )
				{
					SendFile("/etc/loginhog.warn");
					Guillotine();
				}
			}
		}
	
	}

	endutent();
}

int ValidateUser(void)
{
	int ndx;

	for(ndx=0; ndx<=highentry; ndx++)
	{
		/* Check user name */
		re_comp(cfg[ndx]._username);

		if(re_exec( userrec->ut_user ))
		{
			/* Check terminal device */
			re_comp(cfg[ndx]._ttydevice);

			if(re_exec( userrec->ut_line))
			{
				return(TRUE);
			}
		
			return(FALSE);
		}


	}

	return(FALSE);

}

int CheckLogins(void)
{
	int  retval=0, _firstflag=TRUE;
	FILE *utmp;

	if((utmp = fopen(UTMP_FILE, "r")) == NULL)
	{
		perror("fopen");
		exit(1);
	}

	while (1)
	{
		fread( &recbuf, 1, sizeof(struct utmp), utmp);
		if(feof(utmp)) break;

		/* Check for the original utmp entry */
		if( !strncmp(userrec->ut_user, recbuf.ut_user, 8))
		{
			if(_firstflag)
			{
				_firstflag = FALSE;
				continue;
			}
			else
			{
				retval = TRUE;	
			}
		}

	}

	fclose(utmp);
	return(retval);

}

/***************************************************************************
 *                                                                         *
 * void Guillotine( void );                                                *
 *                                                                         *
 * Function responsible for killing processes.                             *
 *                                                                         *
 ***************************************************************************/

void Guillotine( void ) 
{
	pid_t  shell = getppid();
	time_t currtime;

	/* Make sure the process is still there before sending any signals! */
	
	if(!ProcActive(shell))
		return;			
		
	currtime=time(NULL);	

	kill(shell, SIGHUP);
	sleep(2);

	if(ProcActive(shell)) {
		kill(shell, SIGTERM);
		sleep(2);
	}

	if(ProcActive(shell)) {
		kill(shell, SIGKILL);
		sleep(2);
	}
}

/***************************************************************************
 *                                                                         *
 * void SendFile(char *filename);                                          *
 *                                                                         *
 * Sends the contents of filename to the user's tty device.  This function *
 * is called by MessageWarn() and MessageKill().		           * 
 *                                            				   * 
 ***************************************************************************/

void SendFile(char *filename)
{
	FILE 	*tmp;
	int	pid, status, fd;
	char 	localhost[20], termdevice[30], *ptr;
	time_t  currtime = time(NULL);

	pid = fork();

	if(pid < 0) 
	{
		perror("fork");
		return;
	}

	if(pid)
	{
		wait(&status);
		return;
	}
	else
	{
		if( userrec->ut_pid != getpid())
			ptr = (char *)&recbuf.ut_line;
		else
			ptr = userrec->ut_line;

		sprintf(termdevice, "/dev/%s", ptr);

		if((tmp = fopen(filename, "rt")) == NULL)
		{
			perror("fopen");
			exit(0);
		}

		gethostname(localhost, sizeof(localhost));

		if((fd = open(termdevice, O_WRONLY)) == -1)
		{
			perror("open");	
			exit(1);
		}
		
		sprintf(buf, "\n\r\n\rMessage from loginhog.%s at %s\n\r\n\r",
			localhost, ctime(&currtime));
		write(fd, buf, strlen(buf));

		while (1)
		{
			fgets(buf, 80, tmp);
			if(feof(tmp)) break;
	
			write(fd, buf, strlen(buf));
	
		}
	
		fclose(tmp);
		fflush(tty);
		close(fd);

		exit(0);
	}

}

/***************************************************************************
 *                                                                         *
 * int ProcActive(int pid);                                                *
 *                                                                         *
 * Returns TRUE if passed PID is active.  This requires the proc psuedo    *
 * file system to be in place and mounted.                   		   * 
 *                                            				   * 
 ***************************************************************************/

int ProcActive(int pid)
{
	char filename[80];
	struct stat statbuf;

	/* Build proc_fs style filename */
	sprintf(filename, "/proc/%d", pid);

	if(stat(filename, &statbuf))
		return(FALSE);
	else
		return(TRUE);
}

