-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcommon.c
2429 lines (1934 loc) · 104 KB
/
common.c
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
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ========================================================================================================
// ========================================================================================================
// *********************************************** common.c ***********************************************
// ========================================================================================================
// ========================================================================================================
//
//--------------------------------------------------------------------------------
// Company: IC-Safety, LLC and University of New Mexico
// Engineer: Professor Jim Plusquellic
// Exclusive License: IC-Safety, LLC
// Copyright: Univ. of New Mexico
//--------------------------------------------------------------------------------
#include "utility.h"
#include "common.h"
#include <math.h>
#include <errno.h>
#include <netinet/in.h>
#define TRUE 1
#define FALSE 0
// ===========================================================================================================
// ===========================================================================================================
// Create a new string at dest and copy from src.
void StringCreateAndCopy(char **dest, const char *src)
{
*dest = (char *)malloc((size_t)(strlen(src)+1));
strcpy(*dest, src);
return;
}
// ===========================================================================================================
// ===========================================================================================================
void Allocate1DString(char **one_dim_arr_ptr, int size)
{
if ( (*one_dim_arr_ptr = (char *)calloc(size, sizeof(char))) == NULL )
{ printf("ERROR: Allocate1DString(): Failed to allocate string array!\n"); exit(EXIT_FAILURE); }
return;
}
// ===========================================================================================================
// ===========================================================================================================
void Free1DString(char **one_dim_arr_ptr)
{
if ( *one_dim_arr_ptr == NULL )
{ printf("ERROR: Free2DString(): 1-D array of strings is NULL!\n"); exit(EXIT_FAILURE); }
free(*one_dim_arr_ptr);
*one_dim_arr_ptr = NULL;
return;
}
// ===========================================================================================================
// ===========================================================================================================
unsigned char *Allocate1DUnsignedChar(int size)
{
unsigned char *one_dim_arr;
if ( (one_dim_arr = (unsigned char *)calloc(size, sizeof(unsigned char))) == NULL )
{ printf("ERROR: Allocate1DUnsignedChar(): Failed to allocate string array!\n"); exit(EXIT_FAILURE); }
return one_dim_arr;
}
// ===========================================================================================================
// ===========================================================================================================
void Allocate2DStrings(char ***two_dim_arr_ptr, int first_dim_size, int second_dim_size)
{
int i;
if ( (*two_dim_arr_ptr = (char **)malloc(first_dim_size * sizeof(char *))) == NULL )
{ printf("ERROR: Allocate2DString(): Failed to allocate outer dimension of string array!\n"); exit(EXIT_FAILURE); }
for ( i = 0; i < first_dim_size; i++ )
if ( ((*two_dim_arr_ptr)[i] = (char *)calloc(second_dim_size, sizeof(char))) == NULL )
{ printf("ERROR: Allocate2DString(): Failed to allocate inner dimension of string array!\n"); exit(EXIT_FAILURE); }
return;
}
// ===========================================================================================================
// ===========================================================================================================
// Adds one element to the outter array. ASSUMES *two_dim_arr_ptr is NUL initially
void ReAllocate2DStrings(char ***two_dim_arr_ptr, int *first_dim_size_ptr, int second_dim_size)
{
(*first_dim_size_ptr)++;
if ( (*two_dim_arr_ptr = (char **)realloc(*two_dim_arr_ptr, *first_dim_size_ptr * sizeof(char *))) == NULL )
{ printf("ERROR: Allocate2DString(): Failed to re-allocate outer dimension of string array!\n"); exit(EXIT_FAILURE); }
if ( ((*two_dim_arr_ptr)[*first_dim_size_ptr - 1] = (char *)calloc(second_dim_size, sizeof(char))) == NULL )
{ printf("ERROR: Allocate2DString(): Failed to allocate inner dimension of string array!\n"); exit(EXIT_FAILURE); }
return;
}
// ===========================================================================================================
// ===========================================================================================================
void Free2DStrings(char ***two_dim_arr_ptr, int first_dim_size)
{
int i;
if ( *two_dim_arr_ptr == NULL )
{ printf("ERROR: Free2DString(): Root of 2-D array of strings is NULL!\n"); exit(EXIT_FAILURE); }
for ( i = 0; i < first_dim_size; i++ )
{
if ( (*two_dim_arr_ptr)[i] == NULL )
{ printf("ERROR: Free2DString(): Child of 2-D array of strings is NULL!\n"); exit(EXIT_FAILURE); }
free((*two_dim_arr_ptr)[i]);
}
free(*two_dim_arr_ptr);
*two_dim_arr_ptr = NULL;
return;
}
// ===========================================================================================================
// ===========================================================================================================
// Dynamically allocate 2-D array.
char **Allocate2DCharArray(int dim1_size, int dim2_size)
{
int dim1_num;
char **TwoDimArray;
// Allocate space for chips.
if ( (TwoDimArray = (char **)malloc(sizeof(char *)*dim1_size)) == NULL )
{ printf("ERROR: Allocate2DCharArray(): Initial malloc failed\n"); exit(EXIT_FAILURE); }
for ( dim1_num = 0; dim1_num < dim1_size; dim1_num++ )
if ( (TwoDimArray[dim1_num] = (char *)malloc(sizeof(char)*dim2_size)) == NULL )
{ printf("ERROR: Allocate2DCharArray(): Malloc failed for dim1_num %d\n", dim1_num); exit(EXIT_FAILURE); }
return TwoDimArray;
}
// ===========================================================================================================
// ===========================================================================================================
// Dynamically allocate 3-D array.
char ***Allocate3DCharArray(int dim1_size, int dim2_size, int dim3_size)
{
int dim1_num, dim2_num;
char ***ThreeDimArray;
// Allocate space for chips.
if ( (ThreeDimArray = (char ***)malloc(sizeof(char **)*dim1_size)) == NULL )
{ printf("ERROR: Allocate3DCharArray(): Initial malloc failed\n"); exit(EXIT_FAILURE); }
for ( dim1_num = 0; dim1_num < dim1_size; dim1_num++ )
{
// Allocate another set of max_TV pointers to char arrays.
if ( (ThreeDimArray[dim1_num] = (char **)malloc(sizeof(char *)*dim2_size)) == NULL )
{ printf("ERROR: Allocate3DCharArray(): Malloc failed for chip %d\n", dim1_num); exit(EXIT_FAILURE); }
// Now allocate space for the PNs
for ( dim2_num = 0; dim2_num < dim2_size; dim2_num++ )
{
if ( (ThreeDimArray[dim1_num][dim2_num] = (char *)malloc(sizeof(char)*dim3_size)) == NULL )
{ printf("ERROR: Allocate3DCharArray(): Malloc failed for chip %d and TV num %d\n", dim1_num, dim2_num); exit(EXIT_FAILURE); }
}
}
return ThreeDimArray;
}
// ===========================================================================================================
// ===========================================================================================================
int *Allocate1DIntArray(int dim1_size)
{
int *one_dim_arr;
if ( (one_dim_arr = (int *)calloc(dim1_size, sizeof(int))) == NULL )
{ printf("ERROR: Allocate1DIntArray(): Failed to allocate int array!\n"); exit(EXIT_FAILURE); }
return one_dim_arr;
}
// ===========================================================================================================
// ===========================================================================================================
float *Allocate1DFloatArray(int dim1_size)
{
float *one_dim_arr;
if ( (one_dim_arr = (float *)calloc(dim1_size, sizeof(float))) == NULL )
{ printf("ERROR: Allocate1DFloatArray(): Failed to allocate float array!\n"); exit(EXIT_FAILURE); }
return one_dim_arr;
}
// ===========================================================================================================
// ===========================================================================================================
// Dynamically allocate 2-D array.
float **Allocate2DFloatArray(int dim1_size, int dim2_size)
{
int dim1_num;
float **TwoDimArray;
// Allocate space for chips.
if ( (TwoDimArray = (float **)malloc(sizeof(float *)*dim1_size)) == NULL )
{ printf("ERROR: Allocate2DFloatArray(): Initial malloc failed\n"); exit(EXIT_FAILURE); }
for ( dim1_num = 0; dim1_num < dim1_size; dim1_num++ )
if ( (TwoDimArray[dim1_num] = (float *)malloc(sizeof(float)*dim2_size)) == NULL )
{ printf("ERROR: Allocate2DFloatArray(): Malloc failed for dim1_num %d\n", dim1_num); exit(EXIT_FAILURE); }
return TwoDimArray;
}
// ===========================================================================================================
// ===========================================================================================================
void Free2DFloatArray(float ***two_dim_arr_ptr, int dim1_size)
{
int i;
if ( *two_dim_arr_ptr == NULL )
{ printf("ERROR: Free2DFloatArray(): Root of 2-D array of floats is NULL!\n"); exit(EXIT_FAILURE); }
for ( i = 0; i < dim1_size; i++ )
{
if ( (*two_dim_arr_ptr)[i] == NULL )
{ printf("ERROR: Free2DFloatArray(): Child of 2-D array of floats is NULL!\n"); exit(EXIT_FAILURE); }
free((*two_dim_arr_ptr)[i]);
}
free(*two_dim_arr_ptr);
*two_dim_arr_ptr = NULL;
return;
}
// ===========================================================================================================
// ===========================================================================================================
// Dynamically allocate 3-D array.
float ***Allocate3DFloatArray(int dim1_size, int dim2_size, int dim3_size)
{
int chip_num, TV_num;
float ***ThreeDimArray;
// Allocate space for chips.
if ( (ThreeDimArray = (float ***)malloc(sizeof(float **)*dim1_size)) == NULL )
{ printf("ERROR: Allocate3DFloatArray(): Initial malloc failed\n"); exit(EXIT_FAILURE); }
for ( chip_num = 0; chip_num < dim1_size; chip_num++ )
{
// Allocate another set of max_TV pointers to float arrays.
if ( (ThreeDimArray[chip_num] = (float **)malloc(sizeof(float *)*dim2_size)) == NULL )
{ printf("ERROR: Allocate3DFloatArray(): Malloc failed for chip %d\n", chip_num); exit(EXIT_FAILURE); }
// Now allocate space for the PNs
for ( TV_num = 0; TV_num < dim2_size; TV_num++ )
{
if ( (ThreeDimArray[chip_num][TV_num] = (float *)malloc(sizeof(float)*dim3_size)) == NULL )
{ printf("ERROR: Allocate3DFloatArray(): Malloc failed for chip %d and TV num %d\n", chip_num, TV_num); exit(EXIT_FAILURE); }
}
}
return ThreeDimArray;
}
// ===========================================================================================================
// ===========================================================================================================
void Free3DFloatArray(float ****three_dim_arr_ptr, int dim1_size, int dim2_size)
{
int i, j;
if ( *three_dim_arr_ptr == NULL )
{ printf("ERROR: Free3DFloatArray(): Root of 3-D array of floats is NULL!\n"); exit(EXIT_FAILURE); }
for ( i = 0; i < dim1_size; i++ )
{
if ( (*three_dim_arr_ptr)[i] == NULL )
{ printf("ERROR: Free3DFloatArray(): First child of 3-D array of floats is NULL!\n"); exit(EXIT_FAILURE); }
for ( j = 0; j < dim2_size; j++ )
{
if ( (*three_dim_arr_ptr)[i][j] == NULL )
{ printf("ERROR: Free3DFloatArray(): Second child of 3-D array of floats is NULL!\n"); exit(EXIT_FAILURE); }
free((*three_dim_arr_ptr)[i][j]);
}
free((*three_dim_arr_ptr)[i]);
}
free(*three_dim_arr_ptr);
*three_dim_arr_ptr = NULL;
return;
}
// ===========================================================================================================
// ===========================================================================================================
// Reads files with strings, one per line
int ReadXFile(int str_length, char *in_file, int max_vals, char **names)
{
char line[str_length], *char_ptr;
FILE *INFILE;
int count = 0;
if ( (INFILE = fopen(in_file, "r")) == NULL )
{ printf("ERROR: ReadXFile(): Data file '%s' open failed for reading!\n", in_file); exit(EXIT_FAILURE); }
// fgets reads upto 'str_length' characters and writes a terminating char after the last char read.
while ( fgets(line, str_length - 1, INFILE) != NULL )
{
// Find the newline and eliminate it.
if ((char_ptr = strrchr(line, '\n')) != NULL)
*char_ptr = '\0';
// Skip blank lines
if ( strlen(line) == 0 )
continue;
// Skip lines that are commented out. Returns a non-NULL pointer if any of characters in right string
// occur in left string.
if ( strstr(line, "#") != NULL )
continue;
// Check to make sure we don't overrun the array.
if ( count == max_vals )
{ printf("ERROR: ReadXFile(): Number of vals read (%d) is larger than MAX (%d)!\n", count, max_vals); exit(EXIT_FAILURE); }
strcpy(names[count], line);
count++;
}
fclose(INFILE);
return count;
}
// ========================================================================================================
// ========================================================================================================
// Free up vectors and masks.
void FreeVectorsAndMasks(int *num_vecs_ptr, int *num_rise_vecs_ptr, unsigned char ***first_vecs_b_ptr,
unsigned char ***second_vecs_b_ptr, unsigned char ***masks_b_ptr)
{
int vec_mask_num;
if ( first_vecs_b_ptr != NULL && *first_vecs_b_ptr != NULL )
{
for ( vec_mask_num = 0; vec_mask_num < *num_vecs_ptr; vec_mask_num++ )
if ( (*first_vecs_b_ptr)[vec_mask_num] != NULL )
free((*first_vecs_b_ptr)[vec_mask_num]);
else
{ printf("ERROR: FreeVectorsAndMasks(): Actual first_vecs_b_ptr[%d] IS NULL!\n", vec_mask_num); exit(EXIT_FAILURE); }
free(*first_vecs_b_ptr);
}
else
{
#ifdef DEBUG
printf("WARNING: FreeVectorsAndMasks(): Called with NULL first_vecs_b_ptr!\n");
#endif
}
*first_vecs_b_ptr = NULL;
if ( second_vecs_b_ptr != NULL && *second_vecs_b_ptr != NULL )
{
for ( vec_mask_num = 0; vec_mask_num < *num_vecs_ptr; vec_mask_num++ )
if ( (*second_vecs_b_ptr)[vec_mask_num] != NULL )
free((*second_vecs_b_ptr)[vec_mask_num]);
else
{ printf("ERROR: FreeVectorsAndMasks(): Actual second_vecs_b_ptr[%d] IS NULL!\n", vec_mask_num); exit(EXIT_FAILURE); }
free(*second_vecs_b_ptr);
}
else
{
#ifdef DEBUG
printf("WARNING: FreeVectorsAndMasks(): Called with NULL second_vecs_b_ptr!\n");
#endif
}
*second_vecs_b_ptr = NULL;
if ( masks_b_ptr != NULL && *masks_b_ptr != NULL )
{
for ( vec_mask_num = 0; vec_mask_num < *num_vecs_ptr; vec_mask_num++ )
if ( (*masks_b_ptr)[vec_mask_num] != NULL )
free((*masks_b_ptr)[vec_mask_num]);
else
{ printf("ERROR: FreeVectorsAndMasks(): Actual masks_b_ptr[%d] IS NULL!\n", vec_mask_num); exit(EXIT_FAILURE); }
free(*masks_b_ptr);
}
else
{
#ifdef DEBUG
printf("WARNING: FreeVectorsAndMasks(): Called with NULL masks_b_ptr!\n");
#endif
}
*masks_b_ptr = NULL;
*num_vecs_ptr = 0;
*num_rise_vecs_ptr = 0;
return;
}
// ========================================================================================================
// ========================================================================================================
// Get the IP address associated with the target interface.
void GetMyIPAddr(int max_string_len, const char *target_interface_name, char **IP_addr_ptr)
{
struct if_nameindex *if_nidxs, *intf;
int interface_present;
printf("GetMyIPAddr(): CALLED!\n"); fflush(stdout);
#ifdef DEBUG
#endif
// Check to make sure the target interface exists.
if_nidxs = if_nameindex();
interface_present = 0;
if ( if_nidxs != NULL )
{
for (intf = if_nidxs; intf->if_index != 0 || intf->if_name != NULL; intf++)
{
printf("%s\n", intf->if_name); fflush(stdout);
if ( strcmp(intf->if_name, target_interface_name) == 0 )
interface_present = 1;
}
if_freenameindex(if_nidxs);
}
fflush(stdout);
if ( interface_present == 0 )
{ printf("ERROR: GetMyIPAddr(): Target interface '%s' is NOT present!\n", target_interface_name); exit(EXIT_FAILURE); }
int gethostname(char *name, size_t namelen);
char hostbuffer[MAX_STRING_LEN];
// struct hostent *host_entry;
hostbuffer[max_string_len - 1] = '\0';
if ( gethostname(hostbuffer, MAX_STRING_LEN - 1) == -1 )
{ printf("ERROR: GetMyIPAddr(): 'gethostname' failed!\n"); exit(EXIT_FAILURE); }
printf("Hostname: '%s'\n", hostbuffer); fflush(stdout);
printf("GetMyIPAddr(): DONE!\n"); fflush(stdout);
#ifdef DEBUG
#endif
return;
}
// ========================================================================================================
// ========================================================================================================
// Open up multiple sockets and listen for connections from clients
int OpenMultipleSocketServer(int max_string_len, int *master_socket_ptr, char *server_IP, int port_number,
char *client_IP, int max_clients, int *client_sockets, int *client_index_ptr, int initialize)
{
int new_socket, activity, i, sd;
int opt = TRUE;
int max_sd;
struct sockaddr_in address;
int addrlen;
// Set of socket descriptors
fd_set readfds;
// First call, open master.
if ( initialize == 1 )
{
// Create a master socket
if( (*master_socket_ptr = socket(AF_INET, SOCK_STREAM , 0)) == 0 )
{ perror("OpenMultipleSocketServer(): socket failed"); exit(EXIT_FAILURE); }
// Set master socket to allow multiple connections, this is just a good habit, it will work without this.
if( setsockopt(*master_socket_ptr, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)) < 0 )
{ perror("OpenMultipleSocketServer(): setsockopt"); exit(EXIT_FAILURE); }
// Prepare the sockaddr_in structure for the server. For the XWIN version when the devices are on different subnets, e.g.
// 192.168.1.10 and 192.168.2.10, etc, use INADDR_ANY to allow them to connect to the server. Can't do this if running
// multiple command line versions of the protocol.
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(server_IP);
// address.sin_addr.s_addr = ntohl(INADDR_ANY); // Added ntohl 4_27_2020 from reading http://alas.matf.bg.ac.rs/manuals/lspe/snode=27.html
address.sin_port = htons(port_number);
// Bind the socket to localhost port
if ( bind(*master_socket_ptr, (struct sockaddr *)&address, sizeof(address)) < 0 )
{ perror("OpenMultipleSocketServer(): bind failed"); exit(EXIT_FAILURE); }
printf("OpenMultipleSocketServer(): Listener on port %d\n", port_number);
// Try to specify maximum of n pending connections for the master socket
if ( listen(*master_socket_ptr, max_clients) < 0 )
{ perror("OpenMultipleSocketServer(): listen"); exit(EXIT_FAILURE); }
// Accept the incoming connection
puts("Waiting for connections ...");
}
// ================================================
while (1)
{
struct timeval to;
// Initially, set all bits in the file descriptor masks to 0 (clear the socket set)
FD_ZERO(&readfds);
// 'master_socket_ptr' is just an integer. This sets the mask bit associated with the master socket descriptor.
FD_SET(*master_socket_ptr, &readfds);
max_sd = *master_socket_ptr;
// Time out value
to.tv_sec = 0;
to.tv_usec = 100;
// Do the same for all socket descriptors currently open -- set the corresponding mask bit.
for ( i = 0 ; i < max_clients ; i++ )
{
// Socket descriptor
sd = client_sockets[i];
// If valid socket descriptor then add to read list. Note, I now take out (temporarily at the Bank) sockets being serviced by Threads
// by setting their client_socket[i] to -1.
if ( sd > 0 )
FD_SET(sd, &readfds);
// Highest file descriptor number, need it for the select function
if ( sd > max_sd )
max_sd = sd;
}
// Wait for an activity on one of the sockets, timeout is NULL, so wait indefinitely. We are waiting on one class and ask "Is the socket
// ready for a read operation?"
activity = select(max_sd + 1, &readfds, NULL, NULL, &to);
if ( (activity < 0) && (errno != EINTR) )
{
printf("OpenMultipleSocketServer(): select ERROR\t");
if ( errno == EBADF )
printf("Invalid file descriptor!\n");
else if ( errno == EBADF )
printf("nfds is negative or exceeds a resource limit!\n");
else if ( errno == EINVAL )
printf("Timeout value is invalid!\n");
else if ( errno == ENOMEM )
printf("Unable to allocate memory for internal tables!\n");
else
printf("UNKNOWN error!\n");
}
else if ( activity > 0 )
break;
#ifdef DEBUG
printf("OpenMultipleSocketServer(): Waiting on select: Returned %d!\n", activity); fflush(stdout);
#endif
}
#ifdef DEBUG
printf("OpenMultipleSocketServer(): Activity occurred on one of the sockets => Is master_socket %d FD_ISSET %d!\n", *master_socket_ptr,
FD_ISSET(*master_socket_ptr, &readfds)); fflush(stdout);
#endif
// ---------------------------------------------------------------------------
// If something happened on the master socket, then its an incoming connection
if ( FD_ISSET(*master_socket_ptr, &readfds) )
{
addrlen = sizeof(address);
if ( (new_socket = accept(*master_socket_ptr, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0 )
{ perror("accept"); exit(EXIT_FAILURE); }
// Inform user of socket number - used in send and receive commands
#ifdef DEBUG
printf("OpenMultipleSocketServer(): New connection, socket fd is %d, IP is %s, port %d\n", new_socket, inet_ntoa(address.sin_addr), ntohs(address.sin_port));
fflush(stdout);
#endif
// Copy connecting client IP into return variable.
strcpy(client_IP, inet_ntoa(address.sin_addr));
// Add new socket to array of sockets
for ( i = 0; i < max_clients; i++ )
{
// If position is empty, add the new socket descriptor to the array.
if ( client_sockets[i] == 0 )
{
client_sockets[i] = new_socket;
#ifdef DEBUG
printf("OpenMultipleSocketServer(): Added to list of sockets as %d\n" , i); fflush(stdout);
#endif
break;
}
}
// If none are found, return error code.
if ( i < max_clients )
*client_index_ptr = i;
else
{
*client_index_ptr = -1;
printf("ERROR: OpenMultipleSocketServer(): NO sockets are available! Increase size of client_sockets array!\n"); exit(EXIT_FAILURE);
}
return new_socket;
}
// ---------------------------------------------------------------------------
// Else its an IO operation on some other socket that is already open
*client_index_ptr = -1;
for ( i = 0; i < max_clients; i++ )
{
sd = client_sockets[i];
// Do NOT check sockets that are open but in use by a thread.
if ( sd == -1 )
continue;
// Check if sd is still present in the readfds set of socket descriptors
if ( FD_ISSET(sd, &readfds) )
{
// IP retrieval doesn't seem to work... Returns 0.0.0.0.
getpeername(sd, (struct sockaddr*)&address, (socklen_t*)&addrlen);
strcpy(client_IP, inet_ntoa(address.sin_addr));
#ifdef DEBUG
int count;
ioctl(sd, FIONREAD, &count);
printf("Connected host IP %s number of bytes %d (NOT ZERO %d)!\n" , client_IP, count, (int)(count != 0)); fflush(stdout);
#endif
#ifdef DEBUG
printf("Connected host IP %s has sent another message!\n" , client_IP); fflush(stdout);
#endif
*client_index_ptr = i;
// Check if it was for closing, and also read the incoming message
// if ( (valread = read(sd, buffer, 1024)) == 0 )
// {
// Somebody disconnected, get his details and print
// getpeername(sd, (struct sockaddr*)&address, (socklen_t*)&addrlen);
// printf("Host disconnected, IP %s, port %d\n" , inet_ntoa(address.sin_addr) , ntohs(address.sin_port));
// Close the socket and mark as 0 in list for reuse
// close(sd);
// client_sockets[i] = 0;
// }
// Echo back the message that came in
// else
// {
// Set the string terminating NULL byte on the end of the data read
// buffer[valread] = '\0';
// send(sd, buffer, strlen(buffer), 0);
// }
}
}
return 0;
}
// ========================================================================================================
// ========================================================================================================
// Open up a socket and listen for connections from clients
int OpenSocketServer(int max_string_len, int *server_socket_desc_ptr, char *server_IP, int port_number,
int *client_socket_desc_ptr, struct sockaddr_in *client_addr_ptr, int accept_only, int check_and_return)
{
struct sockaddr_in server_addr;
int sizeof_sock;
int queue_size = 1;
int opt = TRUE;
// Create a socket and prepare the socket_in structure.
if ( accept_only == 0 )
{
// printf("OpenSocketServer(): Creating a socket\n"); fflush(stdout);
*server_socket_desc_ptr = socket(AF_INET, SOCK_STREAM, 0);
if ( *server_socket_desc_ptr == -1 )
{ printf("ERROR: OpenSocketServer(): Could not create socket"); fflush(stdout); }
// Set master socket to allow multiple connections, this is just a good habit, it will work without this.
if( setsockopt(*server_socket_desc_ptr, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)) < 0 )
{ perror("OpenSocketServer(): setsockopt"); exit(EXIT_FAILURE); }
// Do non-block fctrl call
if ( check_and_return == 1 )
{
int flags = fcntl(*server_socket_desc_ptr, F_GETFL, 0);
if (flags < 0) return 0;
flags = flags | O_NONBLOCK;
if ( fcntl(*server_socket_desc_ptr, F_SETFL, flags) != 0 )
{ printf("ERROR: OpenSocketServer(): Failed to set 'fcntl' flags to non-blocking!\n"); exit(EXIT_FAILURE); }
}
// Prepare the sockaddr_in structure for the server. For the XWIN version when the devices are on different subnets, e.g.
// 192.168.1.10 and 192.168.2.10, etc, use INADDR_ANY to allow them to connect to the server. Can't do this if running
// multiple command line versions of the protocol.
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(server_IP);
// server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(port_number);
memset(server_addr.sin_zero, 0, 8);
// Bind the server with the socket.
if ( bind(*server_socket_desc_ptr, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0 )
{ printf("ERROR: OpenSocketServer(): Failed to bind!\n"); exit(EXIT_FAILURE); }
// printf("OpenSocketServer(): Bind done!\n"); fflush(stdout);
// Listen to the socket. 'queue_size' indicates how many requests can be pending before an error is
// returned to the remote computer requesting a connection.
listen(*server_socket_desc_ptr, queue_size);
}
// printf("OpenSocketServer(): Waiting for incoming connections from clients ....\n"); fflush(stdout);
// Waiting and accept incoming connection from the client. Device address information is returned
// Note: you can also use 'select' here to determine if a connection request exists.
sizeof_sock = sizeof(struct sockaddr_in);
if ( check_and_return == 0 )
{
while ( (*client_socket_desc_ptr = accept(*server_socket_desc_ptr, (struct sockaddr *)client_addr_ptr, (socklen_t*)&sizeof_sock)) < 0 )
;
// if (*client_socket_desc_ptr < 0)
// { printf("ERROR: OpenSocketServer(): Failed accept\n"); exit(EXIT_FAILURE); }
// printf("OpenSocketServer(): Connection accepted!\n"); fflush(stdout);
return 1;
}
else
{
if ( (*client_socket_desc_ptr = accept(*server_socket_desc_ptr, (struct sockaddr *)client_addr_ptr, (socklen_t*)&sizeof_sock)) < 0 )
return 0;
else
return 1;
}
return 1;
}
// ========================================================================================================
// ========================================================================================================
// Open up a client socket connection. Returns 0 on success and -1 if fails.
int OpenSocketClient(int max_string_len, char *server_IP, int port_number, int *server_socket_desc_ptr)
{
struct sockaddr_in server_addr;
int result;
// printf("OpenSocketClient(): Creating a socket\n"); fflush(stdout);
if ( (*server_socket_desc_ptr = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
{ printf("ERROR: OpenSocketClient(): Could not create socket"); exit(EXIT_FAILURE); }
server_addr.sin_addr.s_addr = inet_addr(server_IP);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port_number);
memset(server_addr.sin_zero, 0, 8);
// Connect to it. 9/14/2018: Changing this from 'exit' to return error.
if ( (result = connect(*server_socket_desc_ptr, (struct sockaddr *)&server_addr, sizeof(server_addr))) < 0 )
{ printf("INFO: OpenSocketClient: Connect failed -- no listener\n"); fflush(stdout); }
// printf("OpenSocketClient(): Connected\n"); fflush(stdout);
// Close the socket if the connect fails.
if ( result < 0 )
close(*server_socket_desc_ptr);
return result;
}
// ========================================================================================================
// ========================================================================================================
// Open up a datagram socket for receiving broadcasts
int OpenSocketServerUDP(int max_string_len, int *bcast_server_socket_desc_ptr, char *server_IP, int port_number,
struct sockaddr_in *client_addr_ptr, int accept_only, int check_and_return, char *buff, char *bcast_subnet_IP)
{
struct sockaddr_in my_addr;
unsigned int sizeof_sock;
int opt = TRUE;
int broadcastEnable = 1;
// Initialize the buffer to a NULL string.
buff[0] = '\0';
// Create a socket and prepare the socket_in structure.
if ( accept_only == 0 )
{
if ( (*bcast_server_socket_desc_ptr = socket(AF_INET, SOCK_DGRAM, 0)) < 0 )
{ perror("ERROR: OpenSocketServerUDP(): Cannnot create DATAGRAM socket!"); exit(EXIT_FAILURE); }
// Set master socket to allow multiple connections, this is just a good habit, it will work without this.
if( setsockopt(*bcast_server_socket_desc_ptr, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)) < 0 )
{ perror("ERROR: OpenSocketServerUDP(): setsockopt to allow multiple connections"); exit(EXIT_FAILURE); }
// Enable reception of broadcast messages.
setsockopt(*bcast_server_socket_desc_ptr, SOL_SOCKET, SO_BROADCAST, &broadcastEnable, sizeof(broadcastEnable));
// Do non-block fctrl call
if ( check_and_return == 1 )
{
struct timeval read_timeout;
read_timeout.tv_sec = 0;
read_timeout.tv_usec = 1000;
setsockopt(*bcast_server_socket_desc_ptr, SOL_SOCKET, SO_RCVTIMEO, &read_timeout, sizeof(read_timeout));
// int flags = fcntl(*bcast_server_socket_desc_ptr, F_GETFL, 0);
// if (flags < 0) return 0;
// flags = flags | O_NONBLOCK;
// if ( fcntl(*bcast_server_socket_desc_ptr, F_SETFL, flags) != 0 )
// { printf("ERROR: OpenSocketServerUDP(): Failed to set 'fcntl' flags to non-blocking!\n"); exit(EXIT_FAILURE); }
}
// Prepare the sockaddr_in structure for the server.
memset(&my_addr, '\0', sizeof(struct sockaddr_in));
my_addr.sin_family = AF_INET;
my_addr.sin_port = (in_port_t)htons(port_number+1);
// my_addr.sin_addr.s_addr = inet_addr(server_IP);
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
// my_addr.sin_addr.s_addr = inet_addr(bcast_subnet_IP);
if ( bind(*bcast_server_socket_desc_ptr, (struct sockaddr *)&my_addr, sizeof(my_addr)) < 0 )
{ perror("ERROR: OpenSockeServerUDP(): Failed to bind"); }
// No 'listen' call for UDP.
}
#ifdef DEBUG
printf("Checking\n"); fflush(stdout);
#endif
sizeof_sock = sizeof(struct sockaddr_in);
recvfrom(*bcast_server_socket_desc_ptr, buff, max_string_len, 0, (struct sockaddr *)client_addr_ptr, &sizeof_sock);
return 1;
}
// ========================================================================================================
// ========================================================================================================
// This function is designed to buffer data but in kernel space. It allows binary data to be transmitted.
// To accomplish this, the first two bytes are interpreted as the length of the binary byte stream that follows.
int SockGetB(unsigned char *buffer, int buffer_size, int socket_desc)
{
int tot_bytes_received, target_num_bytes;
unsigned char buffer_num_bytes[4];
// Call until two bytes are returned. The 2-byte buffer represents a number that is to be interpreted as the exact
// number of binary bytes that will follow in the socket.
target_num_bytes = 3;
tot_bytes_received = 0;
while ( tot_bytes_received < target_num_bytes )
if ( (tot_bytes_received += recv(socket_desc, &buffer_num_bytes[tot_bytes_received], target_num_bytes - tot_bytes_received, 0)) < 0 )
{ printf("ERROR: SockGetB(): Error in receiving three byte cnt!\n"); fflush(stdout); return -1; }
// Translate the binary bytes into an integer.
target_num_bytes = (int)(buffer_num_bytes[2] << 16) + (int)(buffer_num_bytes[1] << 8) + (int)buffer_num_bytes[0];
// DEBUG
//printf("SockGetB(): fetching %d bytes from socket\n", target_num_bytes); fflush(stdout);
// Sanity check.
if ( target_num_bytes > buffer_size )
{
printf("ERROR: SockGetB(): 'target_num_bytes' %d is larger than buffer input size %d\n",
target_num_bytes, buffer_size); fflush(stdout); return -1;
}
// Now start reading binary bytes from the socket
tot_bytes_received = 0;
while ( tot_bytes_received < target_num_bytes )
if ( (tot_bytes_received += recv(socket_desc, &buffer[tot_bytes_received], target_num_bytes - tot_bytes_received, 0)) < 0 )
{ printf("ERROR: SockGetB(): Error in receiving transmitted data!\n"); fflush(stdout); return -1; }
// Sanity check
if ( tot_bytes_received != target_num_bytes )
{
printf("ERROR: SockGetB(): Read more bytes then requested -- 'tot_bytes_received' %d is larger than target %d\n",
tot_bytes_received, target_num_bytes); fflush(stdout); return -1;
}
// DEBUG
//printf("SockGetB(): received %d bytes\n", tot_bytes_received); fflush(stdout);
return tot_bytes_received;
}
// ========================================================================================================
// ========================================================================================================
// This function sends binary or ASCII data of 'buffer_size' unsigned characters through the socket. It first
// sends two binary bytes that represent the length of the binary or ASCII byte stream that follows.
int SockSendB(unsigned char *buffer, int buffer_size, int socket_desc)
{
unsigned char num_bytes[3];
// Sanity check. Don't yet support transfers larger than 16,777,215 bytes.
if ( buffer_size > 16777215 )
{ printf("ERROR: SockSendB(): Size of buffer %d larger than max (16777215)!\n", buffer_size); fflush(stdout); return -1; }
num_bytes[2] = (unsigned char)((buffer_size & 0x00FF0000) >> 16);
num_bytes[1] = (unsigned char)((buffer_size & 0x0000FF00) >> 8);
num_bytes[0] = (unsigned char)(buffer_size & 0x000000FF);
if ( send(socket_desc, num_bytes, 3, 0) < 0 )
{ printf("ERROR: SockSendB(): Send 'num_bytes' %d failed\n", buffer_size); fflush(stdout); return -1; }
if ( send(socket_desc, buffer, buffer_size, 0) < 0 )
{ printf("ERROR: SockSendB(): Send failed\n"); fflush(stdout); return -1; }
return 0;
}
// ========================================================================================================
// ========================================================================================================
// This function prints a header followed by a block of hex digits. Used in DEBUG mode.
void PrintHeaderAndHexVals(char *header_str, int num_bytes, unsigned char *vals, int max_vals_per_row)
{
int i;
printf("%s", header_str);
printf("\t\t");
fflush(stdout);
for ( i = 0; i < num_bytes; i++ )
{
printf("%02X ", vals[i]);
if ( (i+1) % max_vals_per_row == 0 )
printf("\n\t\t");
}
// printf("\n\t\tThis last byte may have additional bits if non-zero (given left-to-right) %02X\n", vals[num_bytes]);
printf("\n\n");
fflush(stdout);
return;
}
// ========================================================================================================
// ========================================================================================================
// This function prints a header followed by a block of hex digits. Used in DEBUG mode.
void PrintHeaderAndBinVals(char *header_str, int num_bits, unsigned char *vals, int max_vals_per_row)
{
int i;
printf("%s", header_str);
printf("\t\t");
fflush(stdout);