/*
 * Remote Laboratory FPGA Server
 *
 * This program 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 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * (c) 2009 Timothy Pearson
 * Raptor Engineering
 * http://www.raptorengineeringinc.com
 */

#include <stdio.h>                /* perror() */
#include <stdlib.h>               /* atoi() */
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>               /* read() */
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <fcntl.h>
#include <glib.h>
#include <gtk/gtk.h>
#include <termios.h>
#include <unistd.h>
#include <sys/signal.h>
#include <sys/types.h>

#include <sasl.h>
#include <saslplug.h>
#include <saslutil.h>

// RAJA FIXME
// Connect this to Autotools...
#define PLUGINDIR "/usr/lib/i386-linux-gnu/sasl2/"

#define NET_SEC_BUF_SIZE (2048)

// Server variables
char authorizationServerNeeded = 0;
char useKerberosAuthorization = 1;
char *authorizationHost = "127.0.0.1";
unsigned short authorizationPort = 4004;
char *serverAddress;
unsigned short serverPort = 4000;
char *cableServerCommand;
char *stopCableServerCommand;
char *fpgaDescription;

// Serial port parameters
char *serialDevice;
long serialBaud;

// Serial stuff
int tty;
struct termios oldtio, newtio;       //place for old and new port settings for serial port
struct termios oldkey, newkey;       //place tor old and new port settings for keyboard teletype
struct sigaction saio;               //definition of signal action
char buf[256];                       //buffer for where data is put
int fd_tty;
int wait_flag=TRUE;                  //TRUE while no signal received

// Network variables
int clientSocket;
int status = 0;
int last_command_acked = 0;
struct hostent *hostPtr = NULL;
struct sockaddr_in serverName = { 0 };
int authentication_timer_check(void);

// Timing variables
unsigned int authentication_timer;
unsigned char enable_authentication_timer;

unsigned char buffer[100000];

// Generic server stuff
#define QLEN 100000
u_short portbase = 0;
struct timeval server_multiplexer;

// Query server stuff
char *queryservice_port = "4001";
struct sockaddr_in fsin_query;
int msock_query;
fd_set rfds_query;
fd_set afds_query;
int alen_query;
int fd_query;
int nfds_query;

// Main server stuff
char *mainservice_port = "4000";
struct sockaddr_in fsin_mainserver;
int msock_mainserver;
fd_set rfds_mainserver;
fd_set afds_mainserver;
int alen_mainserver;
int fd_mainserver;
int nfds_mainserver;
int ssock_mainserver;
char main_server_in_use;
char main_server_fd;
char main_server_state;
char auth_char_pos;
char auth_string[40];

// Configuration stuff
static const char filename[] = "remotefpga.conf";
char linedata [256];

void getMyIP (void)
{
	char Buf [256];
	struct hostent* Host;
	gethostname (Buf, 256);
	Host=(struct hostent *) gethostbyname (Buf);
	serverAddress=strdup(inet_ntoa(*((struct in_addr *)Host->h_addr)));
	//serverAddress=strdup(Buf);
}

int msleep(unsigned long milisec)  {
	struct timespec req={0};
	time_t sec=(int)(milisec/1000);
	milisec=milisec-(sec*1000);
	req.tv_sec=sec;
	req.tv_nsec=milisec*1000000L;
	while(nanosleep(&req,&req)==-1)
		continue;
	return 1;
}

int musleep(unsigned long milisec)  {
	struct timespec req={0};
	time_t sec=(int)(milisec/1000);
	milisec=milisec-(sec*1000);
	req.tv_sec=sec;
	req.tv_nsec=milisec*1000L;
	while(nanosleep(&req,&req)==-1)
		continue;
	return 1;
}

void signal_handler_IO (int status) {
	wait_flag = FALSE;
}

int setupSerial(void) {
	struct termios oldtio,newtio;
	
	fd_tty = open(serialDevice, O_RDWR | O_NOCTTY | O_NONBLOCK | O_APPEND);
	if (fd_tty < 0) {
		printf("[FAIL] Unable to open serial device %s\n\r", serialDevice);
		return 1;
	}
	
	tcgetattr(fd_tty,&oldtio);	// Save current port settings
	
	bzero(&newtio, sizeof(newtio));
	//newtio.c_cflag = serialBaud | CRTSCTS | CS8 | CLOCAL | CREAD;
	newtio.c_cflag = serialBaud | CS8 | CLOCAL | CREAD;
	newtio.c_iflag = IGNPAR;
	newtio.c_oflag = 0;
	
	// Set input mode (non-canonical, no echo,...)
	newtio.c_lflag = 0;
	
	newtio.c_cc[VTIME]    = 0;	// Inter-character timer unused
	newtio.c_cc[VMIN]     = 0;	// Blocking read unused
	
	tcflush(fd_tty, TCIFLUSH);
	tcsetattr(fd_tty,TCSANOW,&newtio);

	return 0;
}

int getConfig(char *parameter, char *line) {
	int i;

	if (strstr(line, parameter) != NULL) {
		for (i=0; i<(strlen(line)-strlen(parameter));i++) {
			linedata[i] = line[i+strlen(parameter)];
		}
		linedata[i-1]=0;

		return 0;
	}
	else {
		return 1;
	}
}

int readConfig(void) {
	int i;

	FILE *file = fopen ( filename, "r" );
	if ( file != NULL ) {
		char line [256];	// or other suitable maximum line size
		// read a line
		while ( fgets ( line, sizeof line, file ) != NULL ) {
			// Parse the line and update global variables (current line in variable "line")
			if (getConfig("AUTH_REQ:", line) == 0) {
				authorizationServerNeeded=atoi(linedata);
				if (authorizationServerNeeded == 1) {
					printf("[INFO] Authorization Required\n\r");
				}
			}
			if (getConfig("AUTH_KRB:", line) == 0) {
				useKerberosAuthorization=atoi(linedata);
				if (useKerberosAuthorization == 1) {
					printf("[INFO] Using Kerberos authorization mechanism\n\r");
				}
			}
			if (getConfig("AUTH_HOST:", line) == 0) {
				authorizationHost = strdup(linedata);
				printf("[INFO] Authorization Host: %s\n\r", authorizationHost);
			}
			if (getConfig("AUTH_PORT:", line) == 0) {
				authorizationPort = atoi(linedata);
				printf("[INFO] Authorization Port: %d\n\r", authorizationPort);
			}
			if (getConfig("SERIAL_PORT:", line) == 0) {
				serialDevice = strdup(linedata);
				printf("[INFO] Serial Port: %s\n\r", serialDevice);
			}
			if (getConfig("BAUD_RATE:", line) == 0) {
				if (strcmp(linedata, "9600") == 0) serialBaud = B9600;
				if (strcmp(linedata, "115200") == 0) serialBaud = B115200;
				//serialBaud = B9600;
				printf("[INFO] Baud Rate: %s [%d]\n\r", linedata, serialBaud);
			}
			if (getConfig("CABLESERVER_COMMAND:", line) == 0) {
				cableServerCommand = strdup(linedata);
				printf("[INFO] Cableserver Command: %s\n\r", cableServerCommand);
			}
			if (getConfig("CABLESERVER_STOP_COMMAND:", line) == 0) {
				stopCableServerCommand = strdup(linedata);
				printf("[INFO] Cableserver Stop Command: %s\n\r", stopCableServerCommand);
			}
			if (getConfig("FPGA_DESCRIPTION:", line) == 0) {
				fpgaDescription = strdup(linedata);
				printf("[INFO] FPGA Description: %s\n\r", fpgaDescription);
			}
		}
		fclose ( file );
	}
	else
	{
		printf("[WARN] Unable to open configuration file %s\n\r", filename);
		return 1;
	}

	return 0;
}

int authentication_timer_check(void) {
	authentication_timer++;

	return enable_authentication_timer;
}

*iplocal = NULL,
*ipremote = NULL,
*searchpath = NULL,
*service = "rcmd",
*localdomain = NULL,
*userdomain = NULL;
sasl_conn_t *conn = NULL;

static int sasl_my_log(void *context __attribute__((unused)), int priority, const char *message) {
	const char *label;
	
	if (!message) {
		return SASL_BADPARAM;
	}
	
	switch (priority) {
		case SASL_LOG_ERR:
			label = "Error";
			break;
		case SASL_LOG_NOTE:
			label = "Info";
			break;
		default:
			label = "Other";
			break;
	}
	
	printf("[SASL %s] %s\n\r", label, message);
	
	return SASL_OK;
}

static int getpath(void *context __attribute__((unused)), char ** path) {
	if (!path) {
		return SASL_BADPARAM;
	}
	
// 	if (searchpath) {
// 		*path = searchpath;
// 	}
// 	else {
		*path = PLUGINDIR;
// 	}
	
	return SASL_OK;
}

static void free_conn(void) {
	if (conn) {
		sasl_dispose(&conn);
	}
}

static void send_sasl_data_to_network(const char *buffer, unsigned length, int netfd)
{
	char *buf;
	unsigned len, alloclen;
	int result;
	char txbuf[NET_SEC_BUF_SIZE];

printf("[RAJA DEBUG 090.0] %s\n\r", buffer);

	alloclen = ((length / 3) + 1) * 4 + 1;
	buf = (char*)malloc(alloclen);
	if (!buf) {
		printf("[ERROR] Unable to malloc()!\n\r");
		return;
	}

	result = sasl_encode64(buffer, length, buf, alloclen, &len);
	if (result != SASL_OK) {
		printf("[ERROR] Encoding data in base64 returned %s (%d)\n\r", sasl_errstring(result, NULL, NULL), result);
		return;
	}

	sprintf(txbuf, "%s\n", buf);
printf("[RAJA DEBUG 100.0] %s\n\r", buf);
	write(netfd, txbuf, strlen(txbuf));

	free(buf);
}

static unsigned int get_sasl_data_from_network(char *buf, int netfd) {
	unsigned int len;
	int result;

	len = 0;
	while (1) {
		if (read(netfd, buf+len, 1) > 0) {
			if (buf[len] == '\n') {
				buf[len] = 0;
				break;
			}
			if (buf[len] != '\r') {
				len++;
			}
		}
	}
	printf("[RAJA DEBUG 100.0] got '%s'\n\r", buf);

	len = strlen(buf);
	result = sasl_decode64(buf, (unsigned) strlen(buf), buf, NET_SEC_BUF_SIZE, &len);
	if (result != SASL_OK) {
		printf("[ERROR] Decoding data from base64 returned %s (%d)\n\r", sasl_errstring(result, NULL, NULL), result);
		return -1;
	}
	buf[len] = '\0';

	return len;
}

int write_data_to_client(int fd, char* readbuf, int cc) {
	int result = 0;
	unsigned int len;
	const char *data;

	if (useKerberosAuthorization == 0) {
		return write(fd, readbuf, cc);
	}
	else {
		result=sasl_encode(conn, readbuf, sizeof(cc), &data, &len);
		if (result != SASL_OK) {
			printf("[ERROR] Encrypting data returned %s (%d)\n\r", sasl_errstring(result, NULL, NULL), result);
			return -1;
		}
		send_sasl_data_to_network(data, len, fd);
	}
}

static sasl_callback_t callbacks[] = {
	{SASL_CB_LOG, (sasl_callback_ft)&sasl_my_log, NULL},
	{SASL_CB_GETPATH, (sasl_callback_ft)&getpath, NULL},
	{SASL_CB_LIST_END, NULL, NULL}
};

int authenticate_connection_with_kerberos(int netfd) {
	char buf[NET_SEC_BUF_SIZE];
	int result = 0;
	int serverlast = 0;
	sasl_security_properties_t secprops;
	const char *ext_authid = NULL;
	unsigned int len;
	int count;
	const char *data;
	char user_authorized = 0;
	sasl_ssf_t *ssf;

	// FIXME
	// Initialize default data structures
	memset(&secprops, 0L, sizeof(secprops));
	secprops.maxbufsize = NET_SEC_BUF_SIZE;
	secprops.max_ssf = UINT_MAX;

	result = sasl_server_init(callbacks, "remotefpga");
	if (result != SASL_OK) {
		printf("[ERROR] Initializing libsasl returned %s (%d)\n\r", sasl_errstring(result, NULL, NULL), result);
		return -1;
	}

	result = sasl_server_new(service, localdomain, userdomain, iplocal, ipremote, NULL, serverlast, &conn);
	if (result != SASL_OK) {
		printf("[ERROR] Allocating sasl connection state returned %s (%d)\n\r", sasl_errstring(result, NULL, NULL), result);
		return -1;
	}

	result = sasl_setprop(conn, SASL_SEC_PROPS, &secprops);

	if (result != SASL_OK) {
		printf("[ERROR] Setting security properties returned %s (%d)\n\r", sasl_errstring(result, NULL, NULL), result);
		free_conn();
		return -1;
	}

	puts("[DEBUG] Generating client mechanism list...");
	result = sasl_listmech(conn, ext_authid, NULL, " ", NULL, &data, &len, &count);
	if (result != SASL_OK) {
		printf("[ERROR] Generating client mechanism list returned %s (%d)\n\r", sasl_errstring(result, NULL, NULL), result);
		free_conn();
		return -1;
	}

	printf("[DEBUG] Sending list of %d mechanism(s)\n\r", count);
	send_sasl_data_to_network(data, len, netfd);

	printf("[DEBUG] Waiting for client mechanism...\n\r");
	len = get_sasl_data_from_network(buf, netfd);
	if (strlen(buf) < len) {
		/* Hmm, there's an initial response here */
		data = buf + strlen(buf) + 1;
		len = len - (unsigned) strlen(buf) - 1;
	}
	else {
		data = NULL;
		len = 0;
	}
	result = sasl_server_start(conn, buf, data, len, &data, &len);
	if (result != SASL_OK && result != SASL_CONTINUE) {
		printf("[ERROR] Starting SASL negotiation returned %s (%d)\n\r", sasl_errstring(result, NULL, NULL), result);
		free_conn();
		return -1;
	}

	while (result == SASL_CONTINUE) {
		if (data) {
			printf("[DEBUG] Sending response...\n\r");
			send_sasl_data_to_network(data, len, netfd);
		}
		else {
			printf("[ERROR] No data to send!\n\r");
			free_conn();
			return -1;
		}
		printf("[DEBUG] Waiting for client reply...\n\r");
		len = get_sasl_data_from_network(buf, netfd);
		data = NULL;
		result = sasl_server_step(conn, buf, len, &data, &len);
		if (result != SASL_OK && result != SASL_CONTINUE) {
			printf("[ERROR] Performing SASL negotiation returned %s (%d)\n\r", sasl_errstring(result, NULL, NULL), result);
			free_conn();
			return -1;
		}
	}
	printf("[DEBUG] Negotiation complete\n\r");

	if(serverlast && data) {
		printf("[DEBUG] Additional information needed to be sent\n\r");
		send_sasl_data_to_network(data, len, netfd);
	}

	result = sasl_getprop(conn, SASL_USERNAME, (const void **)&data);
	if (result != SASL_OK) {
		printf("[WARNING] Unable to determine authenticated username!\n\r");
	}
	else {
		printf("[DEBUG] Authenticated username: %s\n\r", data ? data : "(NULL)");
	}

	result = sasl_getprop(conn, SASL_DEFUSERREALM, (const void **)&data);
	if (result != SASL_OK) {
		printf("[WARNING] Unable to determine authenticated realm!\n\r");
	}
	else {
		printf("[DEBUG] Authenticated realm: %s\n\r", data ? data : "(NULL)");
	}

	result = sasl_getprop(conn, SASL_SSF, (const void **)&ssf);
	if (result != SASL_OK) {
		printf("[WARNING] Unable to determine SSF!\n\r");
	}
	else {
		printf("[DEBUG] Authenticated SSF: %d\n", *ssf);
	}

// #define CLIENT_MSG1 "client message 1"
// #define SERVER_MSG1 "srv message 1"
//   result=sasl_encode(conn,SERVER_MSG1,sizeof(SERVER_MSG1), &data,&len);
//   if (result != SASL_OK)
//       saslfail(result, "sasl_encode", NULL);
//   printf("sending encrypted message '%s'\n",SERVER_MSG1);
//   send_sasl_data_to_network(data, len, netfd);
//   printf("Waiting for encrypted message...\n");
//   len=get_sasl_data_from_network(buf, netfd);
//  {
//  	unsigned int recv_len;
//  	const char *recv_data;
// 	result=sasl_decode(conn,buf,len,&recv_data,&recv_len);
//  	if (result != SASL_OK)
//       saslfail(result, "sasl_encode", NULL);
//     printf("recieved decoded message '%s'\n",recv_data);
//     if(strcmp(recv_data,CLIENT_MSG1)!=0)
//     	saslfail(1,"recive decoded server message",NULL);
//  }

	// RAJA FIXME
	if (user_authorized == 1) {
		main_server_state = 2;
		write_data_to_client(netfd, "OK�", strlen("OK�"));
	}
	else if (user_authorized == -1) {
		main_server_state = 127;
		write(netfd, "You are not allowed to login at this time\n\nPlease try again later�", strlen("You are not allowed to login at this time\n\nPlease try again later�"));
	}
	else {
		main_server_state = 127;
		write(netfd, "Access denied!\n\nPlease make sure your username and password are valid,\nand ensure that your system clock is set properly�", strlen("Access denied!\n\nPlease make sure your username and password are valid,\nand ensure that your system clock is set properly�"));
	}
}

int authenticate_connection(char *authcode, int fd) {
	write(clientSocket, authcode, strlen(authcode));		// Send it the authorization code
	
	// Make sure the authorization server actually responds...
	authentication_timer = 0;
	enable_authentication_timer = 1;
	g_timeout_add_full (G_PRIORITY_HIGH, 10, (GSourceFunc) authentication_timer_check, NULL, NULL);

	while (read(clientSocket, buffer, sizeof(buffer) - 1) == -1) {
		// Do nothing!
		gtk_main_iteration();
		if (authentication_timer > 100) {
			// Hmmm...one second has gone by with no response...
			printf("[FAIL] Authorization server connection failed\n\r");
			return 1;
		}
	}
	printf("[AUTH] Authorization request status: %s\n\r", buffer);
	if (strcmp(buffer, "OK") == 0) {
		main_server_state = 2;
		write(fd, "OK�", strlen("OK�"));
	}
	else if (strcmp(buffer, "HR") == 0) {
		main_server_state = 127;
		write(fd, "You are not allowed to login at this time\n\nPlease try again later�", strlen("You are not allowed to login at this time\n\nPlease try again later�"));
	}
	else {
		main_server_state = 127;
		write(fd, "Access denied!\n\nPlease make sure your username and password are valid,\nand ensure that your system clock is set properly�", strlen("Access denied!\n\nPlease make sure your username and password are valid,\nand ensure that your system clock is set properly�"));
	}
}

int start_authserver_connection(void) {
	int optval;
	int optlen;
	
	clientSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (-1 == clientSocket)
	{
		printf("[FAIL] Connection to authorization server %s failed [Socket Failure]\n\r", authorizationHost);
		return 1;
	}
	
	// Resolve the authorization server name or IP address
	hostPtr = gethostbyname(authorizationHost);
	if (NULL == hostPtr)
	{
		hostPtr = gethostbyaddr(authorizationHost, strlen(authorizationHost), AF_INET);
		if (NULL == hostPtr)
		{
			printf("[FAIL] Connection to authorization server %s failed [Server Unresolvable]\n\r", authorizationHost);
			return 1;
		}
	}
	
	serverName.sin_family = AF_INET;
	serverName.sin_port = htons(authorizationPort);
	(void) memcpy(&serverName.sin_addr, hostPtr->h_addr, hostPtr->h_length);
	
	status = connect(clientSocket, (struct sockaddr*) &serverName, sizeof(serverName));
	if (-1 == status)
	{
		printf("[FAIL] Connection to authorization server %s:%d failed [Server Unreachable]\n\r", authorizationHost, authorizationPort);
		return 1;
	}
	
	status = fcntl(clientSocket, F_SETFL, O_NONBLOCK);
	if (-1 == status)
	{
		printf("[FAIL] Connection to authorization server %s:%d failed [Socket Error]\n\r", authorizationHost, authorizationPort);
		return 1;
	}

	// Done!
	return 0;
}

int passivesock(const char *service, const char *transport, int qlen) {
	struct servent  *pse;
	struct protoent *ppe;
	struct sockaddr_in sin;
	int s;
	int type;
	
	memset(&sin, 0, sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = INADDR_ANY;
	
	// Map service name to port number
	if(pse = getservbyname(service, transport)) {
		sin.sin_port = htons(ntohs((u_short)pse->s_port) + portbase);
	}
	else if((sin.sin_port = htons((u_short)atoi(service))) == 0) {
		printf("[FAIL] Query Server Service Entry %s\n\r", service);
		return -1;
	}
	
	// Map protocol name to protocol number
	if((ppe = getprotobyname(transport)) == 0) {
		printf("[FAIL] Query Server Protocol Entry %s\n\r", transport);
		return -1;
	}
	
	// Use protocol to choose a socket type
	if(strcmp(transport, "udp") == 0) {
		type = SOCK_DGRAM;
	}
	else {
		type = SOCK_STREAM;
	}
	
	// Allocate a socket
	s = socket(PF_INET, type, ppe->p_proto);
	
	if(s < 0) {
		printf("[FAIL] Socket Error\n\r");
		return -1;
	}
	
	// Bind the socket
	if(bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
		printf("[FAIL] Cannot bind to port %s\n\r", service);
		return -1;
	}
	
	if(type == SOCK_STREAM && listen(s, qlen) < 0) {
		printf("[FAIL] Cannot bind to port %s\n\r", service);
		return -1;
	}
	return s;
}

int passiveTCP(const char *service, int qlen) {
	return passivesock(service, "tcp", qlen);
}

int queryserver(int fd) {
	return 0;
}

int mainserver(int fd) {
	char readbuf[100000];
	char writebuf[100000];
	int cc;
	int z;

	cc = 1;
	switch (main_server_state) {
		case 0:		cc = read(fd, readbuf, 32);
				for (z=0;z<cc;z++) {
					auth_string[z+auth_char_pos] = readbuf[z];
					z++;
				}
				auth_char_pos = auth_char_pos + z;
				if (auth_char_pos > 31) {
					readbuf[32]=0;
					printf("[AUTH] Received authorization request with key %s\n\r", readbuf);
					authenticate_connection(readbuf, fd);
				}
				break;
		case 1:		cc = read(fd_tty, readbuf, 100000);
				if (cc > 0) {
					write_data_to_client(fd, readbuf, cc);
					fsync(fd_tty);
					//printf("[DEBG] Got %d bytes from the serial port\n\r", cc);
				}
				cc = read(fd, writebuf, 100000);
				if (cc > 0) {
					write(fd_tty, writebuf, cc);
					fsync(fd);
					//printf("[DEBG] Got %d bytes from the network interface\n\r", cc);
				}
				break;
		case 2:		// Open the serial port
				printf("[INFO] Opening serial port...\n\r");
				if (setupSerial() != 0) {
					printf("[FAIL] Cannot open serial port\n\r");
					cc = 0;
				}
				// Start the cable server
				system(cableServerCommand);
				main_server_state = 1;
				break;
		case 127:	sleep(1);
				cc = 0;
				break;
	}

 	return cc;
}

int RunQueryServer() {
	msock_query = passiveTCP(queryservice_port, QLEN);
	if (msock_query == -1) {
		return -1;
	}
	nfds_query = getdtablesize();
	FD_ZERO(&afds_query);
	FD_SET(msock_query, &afds_query);
}

int RunMainServer() {
	main_server_in_use = 0;
	main_server_fd = -1;
	msock_mainserver = passiveTCP(mainservice_port, QLEN);
	if (msock_mainserver == -1) {
		return -1;
	}
	nfds_mainserver = getdtablesize();;
	FD_ZERO(&afds_mainserver);
	FD_SET(msock_mainserver, &afds_mainserver);
}

int main(int argc, char *argv[])
{
	char successful = 1;

	server_multiplexer.tv_sec = 0;
	server_multiplexer.tv_usec = 10;

	printf("RemoteFPGA Main Server v1.00a\n\r");
	printf("(c) 2009 Timothy Pearson\n\r");

	getMyIP();

	printf("[INFO] Reading configuration from %s...\n\r", filename);
	readConfig();

	printf("[INFO] Opening serial port...\n\r");
	if (setupSerial() != 0) {
		successful = 0;
	}
	printf("[INFO] Closing serial port...\n\r");
	close(fd_tty);

	if ((authorizationServerNeeded == 1) && (useKerberosAuthorization == 0)) {
		printf("[WAIT] Establishing connection with authorization server...\n\r");
		if (start_authserver_connection() == 0) {
			printf("[INFO] Connected to authorization server\n\r");
		}
		else {
			successful = 0;
		}
	}

	if (successful == 1) {
		// Open query port 4001
		if (RunQueryServer() == -1) {
			successful = 0;
		}
		else {
			printf("[INFO] Query process started on %s:%s\n\r", serverAddress, queryservice_port);
		}
	}

	if (successful == 1) {
		// Open main port 4000
		if (RunMainServer() == -1) {
			successful = 0;
		}
		else {
			printf("[INFO] Main port opened on %s:%s\n\r", serverAddress, mainservice_port);
		}
	}

	if (successful == 1) {
		while (1) {
			//musleep(1);
			musleep(10);
			//musleep(50);
			//musleep(100);
			//musleep(250);
			//musleep(1000);

			// Execute Query Server
			memcpy(&rfds_query, &afds_query, sizeof(rfds_query));
			if (select(nfds_query, &rfds_query, (fd_set *)0, (fd_set *)0, &server_multiplexer) < 0) {
				//errexit("select: %s\n\r", strerror(errno));
			}
			if (FD_ISSET(msock_query, &rfds_query)) {
				int ssock_query;
				alen_query = sizeof(fsin_query);
				ssock_query = accept(msock_query, (struct sockaddr *)&fsin_query, &alen_query);
				if (ssock_query >= 0) {
					printf("[INFO] Query received from %s\n\r", inet_ntoa(fsin_query.sin_addr));
					FD_SET(ssock_query, &afds_query);
					if (main_server_in_use == 0) {
						write(ssock_query, fpgaDescription, strlen(fpgaDescription));
					}
					else {
						write(ssock_query, "IN USE", strlen("IN USE"));
					}
				}
			}
 			for (fd_query=0; fd_query < nfds_query; fd_query++) {
 				if(fd_query != msock_query && FD_ISSET(fd_query, &rfds_query)) {
 					if(queryserver(fd_query) == 0) {
 						(void) close(fd_query);
 						FD_CLR(fd_query, &afds_query);
 					}
 				}
 			}
	
			// Execute Main Server
			memcpy(&rfds_mainserver, &afds_mainserver, sizeof(rfds_mainserver));
			if (select(nfds_mainserver, &rfds_mainserver, (fd_set *)0, (fd_set *)0, &server_multiplexer) < 0) {
				//errexit("select: %s\n\r", strerror(errno));
			}
			if (FD_ISSET(msock_mainserver, &rfds_mainserver)) {
				int ssock_mainserver;
				alen_mainserver = sizeof(fsin_mainserver);
				ssock_mainserver = accept(msock_mainserver, (struct sockaddr *)&fsin_mainserver, &alen_mainserver);
				if (ssock_mainserver >= 0) {
					//printf("[INFO] Connection established with %s\n\r", &fsin_mainserver.sin_addr);
				}
				FD_SET(ssock_mainserver, &afds_mainserver);
				if (main_server_in_use == 1) {
					(void) close(ssock_mainserver);
					FD_CLR(ssock_mainserver, &afds_mainserver);
					printf("[INFO] Someone at %s tried to connect while the system was in use!\n\r", inet_ntoa(fsin_mainserver.sin_addr));
				}
				else {
					fcntl(ssock_mainserver, F_SETFL, (fcntl(ssock_mainserver, F_GETFL) | O_NONBLOCK));
					//int sockbufsize = 0;
					//int size = sizeof(int);
    					//getsockopt(ssock_mainserver, SOL_SOCKET, SO_RCVBUF, (char *)&sockbufsize, &size);
					//printf("[DEBG] SO_RCVBUF: %d\n\r", sockbufsize);
					if (authorizationServerNeeded == 1) {
						if (useKerberosAuthorization == 0) {
							auth_char_pos = 0;
							main_server_state = 0;
							//write(ssock_mainserver, "AUTHR\n", strlen("AUTHR\n"));
							write(ssock_mainserver, "AUTHR", strlen("AUTHR"));
						}
						else {
							main_server_state = 0;
							write(ssock_mainserver, "KRBAT", strlen("KRBAT"));
							authenticate_connection_with_kerberos(ssock_mainserver);
						}
					}
					else {
						main_server_state = 1;
						write(ssock_mainserver, "OPENA", strlen("OPENA"));
						// Open the serial port
						printf("[INFO] Opening serial port...\n\r");
						if (setupSerial() != 0) {
							printf("[FAIL] Cannot open serial port\n\r");
							(void) close(ssock_mainserver);
							FD_CLR(ssock_mainserver, &afds_mainserver);
						}
						else {
							// Start the cable server
							system(cableServerCommand);
						}
					}
					main_server_fd = ssock_mainserver;
					printf("[INFO] Connection established with client %s\n\r", inet_ntoa(fsin_mainserver.sin_addr));
				}
				main_server_in_use = 1;
			}
			for (fd_mainserver=0; fd_mainserver < nfds_mainserver; ++fd_mainserver) {
				if (fd_mainserver != msock_mainserver && FD_ISSET(fd_mainserver, &rfds_mainserver)) {
					if (mainserver(fd_mainserver) == 0) {
						(void) close(fd_mainserver);
						FD_CLR(fd_mainserver, &afds_mainserver);
						main_server_in_use = 0;
						main_server_fd = -1;
						free_conn();
						system(stopCableServerCommand);
						printf("[INFO] Closing serial port...\n\r");
						close(fd_tty);
						printf("[INFO] Connection with client terminated\n\r");
					}
				}
			}
			if (main_server_fd != -1) {
				mainserver(main_server_fd);
			}
		}
	}

	return EXIT_SUCCESS;
}
