1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
|
/*
* 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;
}
|