/*****************************************************************************
 *
 * File ..................: common/clcomm.c
 * Purpose ...............: Client/Server communications
 * Last modification date : 13-Nov-1999
 *
 *****************************************************************************
 * Copyright (C) 1997-1999
 *   
 * Michiel Broek		FIDO:		2:2801/16
 * Beekmansbos 10		Internet:	mbroek@ux123.pttnwb.nl
 * 1971 BV IJmuiden
 * the Netherlands
 *
 * This file is part of MBSE BBS.
 *
 * This BBS is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2, or (at your option) any
 * later version.
 *
 * MBSE BBS is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with MBSE BBS; see the file COPYING.  If not, write to the Free
 * Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
 *****************************************************************************/

#include "../include/libs.h"
#include "../include/structs.h"
#include "../include/records.h"
#include "common.h"


int		do_quiet = FALSE;	/* Quiet flag			    */
int		show_log = FALSE;	/* Show loglines on screen	    */
char		progname[21];		/* Program name			    */
char		logfile[81];		/* Normal logfile		    */
long		loggrade;		/* Logging grade		    */
pid_t		mypid;			/* Original parent pid if child	    */
unsigned long	lcrc = 0, tcrc = 1;	/* CRC value of logstring	    */
int		lcnt = 0;		/* Same message counter		    */
char		*authcode = (char *)"";
char		*servername = (char *)"";
char		*k, *v;



/*
 * Prototypes
 */
static int	getstr(char**);
int		rdconfig(void);



/*
 * Keyword table
 */
static struct _keytab {char *key; int(*prc)(char **); char** dest;}
keytab[] = {
	{(char *)"server",	getstr,		&servername},
	{(char *)"authcode",	getstr,		&authcode},
	{NULL,			NULL,		NULL}
};



int readconfig(void)
{
	int	err = 0, linecnt = 0, i;
	FILE	*fp;
	char	buf[512], *p;

	sprintf(buf, "%s/etc/client.conf", getenv("MBSE_ROOT"));

	if ((fp=fopen(buf, "r")) == NULL) {
		printf("rdconfig: cannot open file \"%s\" ", S(buf));
		exit(1);
	}

	while (fgets(buf, sizeof(buf)-1, fp)) {
		linecnt++;
		if (*(p = buf+strlen(buf)-1) != '\n') {
			printf("client.conf(%d): %s - line too long", linecnt, buf);
			while (fgets(buf, sizeof(buf)-1, fp) &&
				(*(p=buf+strlen(buf)-1) != '\n'));
			continue;
		}

		*p--='\0';
		while ((p >= buf) && isspace(*p)) 
			*p--='\0';
		k = buf;
		while (*k && isspace(*k)) 
			k++;
		p = k;
		while (*p && !isspace(*p)) 
			p++;
		*p++='\0';
		v = p;
		while (*v && isspace(*v)) 
			v++;

		/*
		 *  Skip empty and comment lines 
		 */
		if ((*k == '\0') || (*k == '#')) 
			continue;

		for (i = 0; keytab[i].key; i++)
			if (strcasecmp(k, keytab[i].key) == 0) 
				break;

		if (keytab[i].key == NULL) {
			printf("client.conf(%d): %s %s - unknown keyword", 
				linecnt, S(k), S(v));
			err++;
		} else {
			keytab[i].prc(keytab[i].dest);
		}
	}
	fclose(fp);
	if (err != 0) {
		printf("Configuration error(s)\n");
		exit(1);
	}
	return 0;
}



/*
 * Read a string from the config file until eol.
 */
static int getstr(char **dest)
{
	*dest = xstrcpy(v);
	return 0;
}



void InitClient(char *user, char *myname, char *where, char *log, long loggr)
{
	if ((getenv("MBSE_ROOT")) == NULL) {
		printf("Could not get the MBSE_ROOT environment variable\n");
		printf("Please set the environment variable ie:\n");
		printf("\"MBSE_ROOT=/opt/mbse; export MBSE_ROOT\"\n\n");
		exit(1);
	}
	readconfig();

	sprintf(progname, "%s", myname);
	sprintf(logfile, "%s", log);
	loggrade = loggr;

	/*
	 * Store my pid in case a child process is forked and wants to do
	 * some communications with the mbsed server.
	 */
	mypid = getpid();
	if (socket_connect(servername, user, myname, where, authcode) == -1) {
		printf("PANIC: cannot access socket\n");
		exit(1);
	}
}



void ExitClient(int errcode)
{
	if (socket_shutdown(mypid) == -1)
		printf("PANIC: unable to shutdown socket\n");
	fflush(stdout);
	fflush(stdin);
	exit(errcode);
}



void SockS(const char *format, ...)
{
	char	*out;
	va_list	va_ptr;

	out = calloc(2048, sizeof(char));

	va_start(va_ptr, format);
	vsprintf(out, format, va_ptr);
	va_end(va_ptr);

	if (socket_send(out) == 0)
		socket_receive();

	free(out);
}



char *SockR(const char *format, ...)
{
	static char	buf[SS_BUFSIZE];
	char		*out;
	va_list		va_ptr;

	memset(&buf, 0, SS_BUFSIZE);
	out = calloc(2048, sizeof(char));

	va_start(va_ptr, format);
	vsprintf(out, format, va_ptr);
	va_end(va_ptr);

	if (socket_send(out) == 0)
		sprintf(buf, "%s", socket_receive());

	Syslog('+', "%s", buf);
	free(out);
	return buf;
}



void WriteError(const char *format, ...)
{
	char		*outputstr;
	va_list		va_ptr;

	outputstr = calloc(2048, sizeof(char));

	va_start(va_ptr, format);
	vsprintf(outputstr, format, va_ptr);
	va_end(va_ptr);

	tcrc = StringCRC32(outputstr);
	if (tcrc == lcrc) {
		lcnt++;
		free(outputstr);
		return;
	} else {
		lcrc = tcrc;
		if (lcnt) {
			lcnt++;
			SockS("ALOG:5,%s,%s,%d,?,Last message repeated %d times;", 
					logfile, progname, mypid, lcnt);
			SockS("ALOG:5,%s,%s,%d,?,Last message repeated %d times;", 
					CFG.error_log, progname, mypid, lcnt);
		}
		lcnt = 0;
	}

	SockS("ALOG:5,%s,%s,%d,?,%s;", logfile, progname, mypid, outputstr);
	SockS("ALOG:5,%s,%s,%d,?,%s;", CFG.error_log, progname, mypid, outputstr);
	free(outputstr);
}



void Syslog(int level, const char *format, ...)
{
	char		*outstr;
	va_list		va_ptr;
	long		mask = 0;

	outstr = calloc(2048, sizeof(char));

	va_start(va_ptr, format);
	vsprintf(outstr, format, va_ptr);
	va_end(va_ptr);

	switch(tolower(level)) {
		case ' ' : mask = DLOG_ALLWAYS;	break;
		case '?' : mask = DLOG_ERROR;	break;	
		case '!' : mask = DLOG_ATTENT;	break;
		case '+' : mask = DLOG_NORMAL;	break;
		case '-' : mask = DLOG_VERBOSE;	break;
		case 'a' : mask = DLOG_TCP;	break;
		case 'b' : mask = DLOG_BBS;	break;
		case 'c' : mask = DLOG_CHAT;	break;
		case 'd' : mask = DLOG_DEVIO;	break;
		case 'e' : mask = DLOG_EXEC;	break;
		case 'f' : mask = DLOG_FILEFWD;	break;
		case 'h' : mask = DLOG_HYDRA;	break;
		case 'i' : mask = DLOG_IEMSI;	break;
		case 'l' : mask = DLOG_LOCK;	break;
		case 'm' : mask = DLOG_MAIL;	break;
		case 'n' : mask = DLOG_NEWS;	break;
		case 'o' : mask = DLOG_OUTSCAN;	break;
		case 'p' : mask = DLOG_PACK;	break;
		case 'r' : mask = DLOG_ROUTE;	break;
		case 's' : mask = DLOG_SESSION;	break;
		case 't' : mask = DLOG_TTY;	break;
		case 'x' : mask = DLOG_XMODEM;	break;
		case 'z' : mask = DLOG_ZMODEM;	break;
	}

	if (((loggrade | DLOG_ALLWAYS | DLOG_ERROR) & mask) == 0) {
		free(outstr);
		return;
	}

	tcrc = StringCRC32(outstr);
	if (tcrc == lcrc) {
		lcnt++;
		free(outstr);
		return;
	} else {
		lcrc = tcrc;
		if (lcnt) {
			lcnt++;
			SockS("ALOG:5,%s,%s,%d,%c,Last message repeated %d times;", 
					logfile, progname, mypid, toupper(level), lcnt);
		}
		lcnt = 0;
	}

	if (show_log)
		printf("%c %s\n", level, outstr);

	SockS("ALOG:5,%s,%s,%d,%c,%s;", logfile, progname, mypid, toupper(level), outstr);
	free(outstr);
}



void IsDoing(const char *format, ...)
{
	char	*outputstr;
	va_list	va_ptr;

	outputstr = calloc(64, sizeof(char));

	va_start(va_ptr, format);
	vsprintf(outputstr, format, va_ptr);
	va_end(va_ptr);

	SockS("ADOI:2,%d,%s;", mypid, outputstr);
	free(outputstr);
}



void SetTTY(char *tty)
{
	SockS("ATTY:2,%d,%s;", mypid, tty);
}



void DoNop()
{
	SockS("GNOP:0;");
}



static time_t	nop = 0;

/*
 * This function can be called very often but will only send once a minute
 * a NOP to the server. This is a simple solution to keep server trafic low.
 */
void Nopper(void)
{
	time_t	now;

	now = time(NULL);
	if (((time_t)now - (time_t)nop) > 60) {
		nop = now;
		SockS("GNOP:0;");
	}
}



/*
 * Set new alarmtime for Client/Server connection,
 * if zero set the default time.
 */
void Altime(int altime)
{
	if (altime)
		SockS("ATIM:1,%d;", altime);
	else
		SockS("ADEF:0;");
}



unsigned long sequencer()
{
	char		*buf, *res;
	unsigned long	seq = 0;

	buf = calloc(81, sizeof(char));
	res = calloc(81, sizeof(char));

	sprintf(buf, "SSEQ:0;");

	if (socket_send(buf) == 0) {
		buf = socket_receive();
		res = strtok(buf, ",");
		res = strtok(NULL, ";");
		seq = atol(res);
	}

	return seq;
}



static char *pbuff = NULL;

char *printable(char *s, int l)
{
	int	len;
	char	*p;

	if (pbuff) 
		free(pbuff);
	pbuff=NULL;

	if (s == NULL) 
		return (char *)"(null)";

	if (l > 0) 
		len=l;
	else if (l == 0) 
		len=strlen(s);
	else {
		len=strlen(s);
		if (len > -l) 
			len=-l;
	}

	pbuff=(char*)malloc(len*4+1);
	p=pbuff;
	while (len--) {
		if (*(unsigned char*)s >= ' ') 
			*p++=*s;
		else switch (*s) {
			case '\\': *p++='\\'; *p++='\\'; break;
			case '\r': *p++='\\'; *p++='r'; break;
			case '\n': *p++='\\'; *p++='n'; break;
			case '\t': *p++='\\'; *p++='t'; break;
			case '\b': *p++='\\'; *p++='b'; break;
			default:   sprintf(p,"\\%03o",*s); p+=4; break;
		}
		s++;
	}
	*p='\0';
	return pbuff;
}



char *printablec(char c)
{
	return printable(&c,1);
}


