/* * 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 /* perror() */ #include /* atoi() */ #include #include #include /* read() */ #include #include #include #include #include #include #include #include #include #include // Server variables char authorizationServerNeeded = 0; 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_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; } 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 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(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) { 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) { 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 = 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; 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; }