-
Notifications
You must be signed in to change notification settings - Fork 295
/
Copy pathPosixHelperFunctions.c
1799 lines (1676 loc) · 50.3 KB
/
PosixHelperFunctions.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
/*
* PosixHelperFunctions.c
*
* Created on: Mar 10, 2015
* Last Updated on: Apr 10, 2024
* Author: Will Hedgecock
*
* Copyright (C) 2012-2024 Fazecast, Inc.
*
* This file is part of jSerialComm.
*
* jSerialComm is free software: you can redistribute it and/or modify
* it under the terms of either the Apache Software License, version 2, or
* the GNU Lesser General Public License as published by the Free Software
* Foundation, version 3 or above.
*
* jSerialComm 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.
*
* You should have received a copy of both the GNU Lesser General Public
* License and the Apache Software License along with jSerialComm. If not,
* see <http://www.gnu.org/licenses/> and <http://www.apache.org/licenses/>.
*/
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <grp.h>
#include <pwd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include "PosixHelperFunctions.h"
// Common serial port storage functionality
serialPort* pushBack(serialPortVector* vector, const char* key, const char* friendlyName, const char* description, const char* location, const char* serialNumber, const char* manufacturer, int vid, int pid)
{
// Allocate memory for the new SerialPort storage structure
if (vector->capacity == vector->length)
{
serialPort** newArray = (serialPort**)realloc(vector->ports, ++vector->capacity * sizeof(serialPort*));
if (newArray)
vector->ports = newArray;
else
{
vector->capacity--;
return NULL;
}
}
serialPort* port = (serialPort*)malloc(sizeof(serialPort));
if (port)
vector->ports[vector->length++] = port;
else
return NULL;
// Initialize the serial port mutex and condition variables
memset(port, 0, sizeof(serialPort));
pthread_mutex_init(&port->eventMutex, NULL);
pthread_condattr_t conditionVariableAttributes;
pthread_condattr_init(&conditionVariableAttributes);
#if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__ANDROID__)
pthread_condattr_setclock(&conditionVariableAttributes, CLOCK_REALTIME);
#endif
pthread_cond_init(&port->eventReceived, &conditionVariableAttributes);
pthread_condattr_destroy(&conditionVariableAttributes);
// Initialize the storage structure
port->handle = -1;
port->enumerated = 1;
port->vendorID = vid;
port->productID = pid;
port->portPath = (char*)malloc(strlen(key) + 1);
port->portLocation = (char*)malloc(strlen(location) + 1);
port->friendlyName = (char*)malloc(strlen(friendlyName) + 1);
port->serialNumber = (char*)malloc(strlen(serialNumber) + 1);
port->manufacturer = (char*)malloc(strlen(manufacturer) + 1);
port->portDescription = (char*)malloc(strlen(description) + 1);
// Store port strings
strcpy(port->portPath, key);
strcpy(port->portLocation, location);
strcpy(port->friendlyName, friendlyName);
strcpy(port->serialNumber, serialNumber);
strcpy(port->manufacturer, manufacturer);
strcpy(port->portDescription, description);
// Return the newly created serial port structure
return port;
}
serialPort* fetchPort(serialPortVector* vector, const char* key)
{
for (int i = 0; i < vector->length; ++i)
if (strcmp(key, vector->ports[i]->portPath) == 0)
return vector->ports[i];
return NULL;
}
void removePort(serialPortVector* vector, serialPort* port)
{
// Clean up memory associated with the port
free(port->portPath);
free(port->portLocation);
free(port->friendlyName);
free(port->serialNumber);
free(port->manufacturer);
free(port->portDescription);
pthread_cond_destroy(&port->eventReceived);
pthread_mutex_destroy(&port->eventMutex);
// Move up all remaining ports in the serial port listing
for (int i = 0; i < vector->length; ++i)
if (vector->ports[i] == port)
{
for (int j = i; j < (vector->length - 1); ++j)
vector->ports[j] = vector->ports[j+1];
vector->length--;
break;
}
// Free the serial port structure memory
free(port);
}
void cleanUpVector(serialPortVector* vector)
{
while (vector->length)
removePort(vector, vector->ports[0]);
if (vector->ports)
free(vector->ports);
vector->ports = NULL;
vector->length = vector->capacity = 0;
}
// Common string storage functionality
typedef struct stringVector
{
char **strings;
int length, capacity;
} stringVector;
static void pushBackString(stringVector* vector, const char* string)
{
// Allocate memory for the new port path prefix storage structure
if (vector->capacity == vector->length)
{
char** newStringArray = (char**)realloc(vector->strings, ++vector->capacity * sizeof(const char*));
if (newStringArray)
vector->strings = newStringArray;
else
{
vector->capacity--;
return;
}
}
char* newString = (char*)malloc(strlen(string) + 1);
if (newString)
{
strcpy(newString, string);
vector->strings[vector->length++] = newString;
}
}
static void freeStringVector(stringVector* vector)
{
for (int i = 0; i < vector->length; ++i)
free(vector->strings[i]);
if (vector->strings)
free(vector->strings);
vector->strings = NULL;
vector->length = vector->capacity = 0;
}
// Linux-specific functionality
#if defined(__linux__)
#include <linux/serial.h>
#include <asm/ioctls.h>
#include "termios2.h"
static void retrievePhysicalPortPrefixes(stringVector* prefixes)
{
// Open the TTY drivers file
FILE *input = fopen("/proc/tty/drivers", "rb");
if (input)
{
// Read the file line by line
int maxLineSize = 256;
char *line = (char*)malloc(maxLineSize);
while (fgets(line, maxLineSize, input))
{
// Parse the prefix, name, and type fields
int i = 0;
char *token, *remainder = line, *prefix = NULL, *name = NULL, *type = NULL;
while ((token = strtok_r(remainder, " \t\r\n", &remainder)))
if (++i == 1)
name = token;
else if (i == 2)
prefix = token;
else if (i == 5)
type = token;
// Add a new prefix to the vector if the driver type and name are both "serial"
if (prefix && type && name && (strcmp(type, "serial") == 0) && (strcmp(name, "serial") == 0))
pushBackString(prefixes, prefix);
}
// Close the drivers file and clean up memory
free(line);
fclose(input);
}
}
static char isUsbSerialSubsystem(const char *subsystemLink)
{
// Attempt to read the path that the subsystem link points to
struct stat fileInfo;
char *subsystem = NULL, isUsbSerial = 0;
if (lstat(subsystemLink, &fileInfo) == 0)
{
ssize_t bufferSize = fileInfo.st_size ? (fileInfo.st_size + 1) : PATH_MAX;
subsystem = (char*)malloc(bufferSize);
if (subsystem)
{
ssize_t subsystemSize = readlink(subsystemLink, subsystem, bufferSize);
if (subsystemSize >= 0)
{
subsystem[subsystemSize] = '\0';
if (strcmp(1 + strrchr(subsystem, '/'), "usb-serial") == 0)
isUsbSerial = 1;
}
free(subsystem);
}
}
return isUsbSerial;
}
static char isPtyDevice(const char *deviceLink)
{
// Attempt to read the path that the potential PTY device link points to
struct stat fileInfo;
char *symlink = NULL, isPtyDevice = 0;
if ((lstat(deviceLink, &fileInfo) == 0) && fileInfo.st_size && ((fileInfo.st_mode & S_IFMT) == S_IFLNK))
{
ssize_t bufferSize = fileInfo.st_size + 1;
symlink = (char*)malloc(bufferSize);
if (symlink)
{
ssize_t symlinkSize = readlink(deviceLink, symlink, bufferSize);
if (symlinkSize >= 0)
{
symlink[symlinkSize] = '\0';
if (strstr(symlink, "dev/pt"))
isPtyDevice = 1;
}
free(symlink);
}
}
return isPtyDevice;
}
static char isBluetoothDevice(const char *deviceLink)
{
return (strstr(deviceLink, "/rfcomm") != NULL);
}
static void getPortLocation(const char* portDirectory, char* portLocation, int physicalPortNumber)
{
// Set location of busnum and devpath files
char* busnumFile = (char*)malloc(strlen(portDirectory) + 16);
strcpy(busnumFile, portDirectory);
strcat(busnumFile, "busnum");
char* devpathFile = (char*)malloc(strlen(portDirectory) + 16);
strcpy(devpathFile, portDirectory);
strcat(devpathFile, "devpath");
int portLocationLength = 0;
portLocation[0] = '\0';
// Read the bus number
FILE *input = fopen(busnumFile, "rb");
if (input)
{
int ch = getc(input);
while (((char)ch != '\n') && (ch != EOF))
{
portLocation[portLocationLength++] = (char)ch;
ch = getc(input);
}
portLocation[portLocationLength++] = '-';
fclose(input);
}
else
{
portLocation[portLocationLength++] = '0';
portLocation[portLocationLength++] = '-';
}
// Read the device path
input = fopen(devpathFile, "rb");
if (input)
{
int ch = getc(input);
while (((char)ch != '\n') && (ch != EOF))
{
portLocation[portLocationLength++] = (char)ch;
ch = getc(input);
}
portLocation[portLocationLength] = '\0';
fclose(input);
}
else
{
portLocation[portLocationLength++] = '0';
portLocation[portLocationLength] = '\0';
}
// Append the physical port number if applicable
if (physicalPortNumber >= 0)
sprintf(portLocation + portLocationLength, ".%d", physicalPortNumber);
// Clean up the dynamic memory
free(devpathFile);
free(busnumFile);
}
static void assignFriendlyName(const char* portDevPath, char* friendlyName)
{
// Manually assign a friendly name if the port type is known from its name
const char *portName = 1 + strrchr(portDevPath, '/');
if ((strlen(portName) >= 5) && (portName[3] == 'A') && (portName[4] == 'P'))
strcpy(friendlyName, "Advantech Extended Serial Port");
else if ((strlen(portName) >= 6) && (portName[0] == 'r') && (portName[1] == 'f') && (portName[2] == 'c') &&
(portName[3] == 'o') && (portName[4] == 'm') && (portName[5] == 'm'))
strcpy(friendlyName, "Bluetooth-Based Serial Port");
else
{
// Assign a friendly name based on the serial port driver in use
char nameAssigned = 0;
FILE *input = fopen("/proc/tty/drivers", "rb");
if (input)
{
// Read the TTY drivers file line by line
int maxLineSize = 256;
char *line = (char*)malloc(maxLineSize);
while (!nameAssigned && fgets(line, maxLineSize, input))
{
// Parse the prefix, name, and type fields
int i = 0;
char *token, *remainder = line, *prefix = NULL, *name = NULL, *type = NULL;
while ((token = strtok_r(remainder, " \t\r\n", &remainder)))
if (++i == 1)
name = token;
else if (i == 2)
prefix = token;
else if (i == 5)
type = token;
// Assign a friendly name if a matching port prefix was found
if (prefix && name && type && (strcmp(type, "serial") == 0) && (strstr(portDevPath, prefix) == portDevPath))
{
strcpy(friendlyName, "Serial Device (");
strcat(friendlyName, name);
strcat(friendlyName, ")");
nameAssigned = 1;
}
}
// Close the drivers file and clean up memory
free(line);
fclose(input);
}
// If no driver prefix could be found, just assign a generic friendly name
if (!nameAssigned)
strcpy(friendlyName, "USB-Based Serial Port");
}
}
static void getUsbDetails(const char* fileName, char* basePathEnd, int* vendorID, int* productID, char* serialNumber, char* manufacturer)
{
// Attempt to read the Vendor ID
char *temp = (char*)malloc(8);
sprintf(basePathEnd, "../idVendor");
FILE *input = fopen(fileName, "rb");
if (input)
{
fgets(temp, 8, input);
*vendorID = (int)strtol(temp, NULL, 16);
fclose(input);
}
// Attempt to read the Product ID
sprintf(basePathEnd, "../idProduct");
input = fopen(fileName, "rb");
if (input)
{
fgets(temp, 8, input);
*productID = (int)strtol(temp, NULL, 16);
fclose(input);
}
free(temp);
// Attempt to read the Serial Number
strcpy(serialNumber, "Unknown");
sprintf(basePathEnd, "../serial");
input = fopen(fileName, "rb");
if (input)
{
fgets(serialNumber, 128, input);
serialNumber[strcspn(serialNumber, "\r\n")] = 0;
fclose(input);
}
// Attempt to read the Manufacturer
strcpy(manufacturer, "Unknown");
sprintf(basePathEnd, "../manufacturer");
input = fopen(fileName, "rb");
if (input)
{
fgets(manufacturer, 128, input);
manufacturer[strcspn(manufacturer, "\r\n")] = 0;
fclose(input);
}
}
void searchForComPorts(serialPortVector* comPorts)
{
// Set up the necessary local variables
struct stat pathInfo = { 0 };
stringVector physicalPortPrefixes = { NULL, 0, 0 };
int fileNameMaxLength = 0, portDevPathMaxLength = 128, maxLineSize = 256;
char *fileName = NULL, *portDevPath = (char*)malloc(portDevPathMaxLength);
char *line = (char*)malloc(maxLineSize), *friendlyName = (char*)malloc(256);
char *portLocation = (char*)malloc(128), *interfaceDescription = (char*)malloc(256);
char *serialNumber = (char*)malloc(128), *manufacturer = (char*)malloc(128);
// Retrieve the list of /dev/ prefixes for all physical serial ports
retrievePhysicalPortPrefixes(&physicalPortPrefixes);
// Iterate through the system TTY directory
DIR *directoryIterator = opendir("/sys/class/tty/");
if (directoryIterator)
{
struct dirent *directoryEntry = readdir(directoryIterator);
while (directoryEntry)
{
// Ensure that the file name buffer is large enough
if ((64 + strlen(directoryEntry->d_name)) > fileNameMaxLength)
{
fileNameMaxLength = 64 + strlen(directoryEntry->d_name);
fileName = (char*)realloc(fileName, fileNameMaxLength);
}
// Check if the entry represents a valid serial port
strcpy(fileName, "/sys/class/tty/");
strcat(fileName, directoryEntry->d_name);
char *basePathEnd = fileName + strlen(fileName);
sprintf(basePathEnd, "/device/driver");
char isSerialPort = (stat(fileName, &pathInfo) == 0) && S_ISDIR(pathInfo.st_mode);
sprintf(basePathEnd, "/dev");
isSerialPort = isSerialPort && (stat(fileName, &pathInfo) == 0) && S_ISREG(pathInfo.st_mode);
sprintf(basePathEnd, "/uevent");
isSerialPort = isSerialPort && (stat(fileName, &pathInfo) == 0) && S_ISREG(pathInfo.st_mode);
if (!isSerialPort)
{
directoryEntry = readdir(directoryIterator);
continue;
}
// Determine the /dev/ path to the device
isSerialPort = 0;
FILE *input = fopen(fileName, "r");
if (input)
{
while (fgets(line, maxLineSize, input))
if (strstr(line, "DEVNAME=") == line)
{
isSerialPort = 1;
strcpy(portDevPath, "/dev/");
strcat(portDevPath, line + 8);
portDevPath[strcspn(portDevPath, "\r\n")] = '\0';
}
fclose(input);
}
if (!isSerialPort)
{
directoryEntry = readdir(directoryIterator);
continue;
}
// Check if the device is a physical serial port
char isPhysical = 0;
int physicalPortNumber = 0;
for (int i = 0; !isPhysical && (i < physicalPortPrefixes.length); ++i)
if (strstr(portDevPath, physicalPortPrefixes.strings[i]) == portDevPath)
{
isPhysical = 1;
physicalPortNumber = atoi(portDevPath + strlen(physicalPortPrefixes.strings[i]));
}
// Determine the subsystem and bus location of the port
int vendorID = -1, productID = -1;
sprintf(basePathEnd, "/device/subsystem");
if (isUsbSerialSubsystem(fileName))
{
sprintf(basePathEnd, "/device/../");
basePathEnd += 11;
}
else
{
sprintf(basePathEnd, "/device/");
basePathEnd += 8;
}
getUsbDetails(fileName, basePathEnd, &vendorID, &productID, serialNumber, manufacturer);
sprintf(basePathEnd, "../");
getPortLocation(fileName, portLocation, isPhysical ? physicalPortNumber : -1);
// Check if the port has already been enumerated
serialPort *port = fetchPort(comPorts, portDevPath);
if (port)
{
// See if the device has changed locations
int oldLength = strlen(port->portLocation);
int newLength = strlen(portLocation);
if (oldLength != newLength)
{
port->portLocation = (char*)realloc(port->portLocation, newLength + 1);
strcpy(port->portLocation, portLocation);
}
else if (memcmp(port->portLocation, portLocation, newLength))
strcpy(port->portLocation, portLocation);
// Update descriptors if this is not a physical port
if (!isPhysical)
{
// Update the device's registered friendly name
friendlyName[0] = '\0';
sprintf(basePathEnd, "../product");
FILE *input = fopen(fileName, "rb");
if (input)
{
fgets(friendlyName, 256, input);
friendlyName[strcspn(friendlyName, "\r\n")] = '\0';
fclose(input);
}
if (friendlyName[0] == '\0')
assignFriendlyName(portDevPath, friendlyName);
oldLength = strlen(port->friendlyName);
newLength = strlen(friendlyName);
if (oldLength != newLength)
{
port->friendlyName = (char*)realloc(port->friendlyName, newLength + 1);
strcpy(port->friendlyName, friendlyName);
}
else if (memcmp(port->friendlyName, friendlyName, newLength))
strcpy(port->friendlyName, friendlyName);
// Attempt to read the bus-reported device description
interfaceDescription[0] = '\0';
sprintf(basePathEnd, "interface");
input = fopen(fileName, "rb");
if (input)
{
fgets(interfaceDescription, 256, input);
interfaceDescription[strcspn(interfaceDescription, "\r\n")] = '\0';
fclose(input);
}
if (interfaceDescription[0] == '\0')
strcpy(interfaceDescription, friendlyName);
oldLength = strlen(port->portDescription);
newLength = strlen(interfaceDescription);
if (oldLength != newLength)
{
port->portDescription = (char*)realloc(port->portDescription, newLength + 1);
strcpy(port->portDescription, interfaceDescription);
}
else if (memcmp(port->portDescription, interfaceDescription, newLength))
strcpy(port->portDescription, interfaceDescription);
}
// Continue port enumeration
directoryEntry = readdir(directoryIterator);
port->enumerated = 1;
continue;
}
// Retrieve all available port details based on its type
if (isPhysical)
{
// Probe the physical port to see if it actually exists
int fd = open(portDevPath, O_RDWR | O_NONBLOCK | O_NOCTTY);
if (fd >= 0)
{
struct serial_struct serialInfo = { 0 };
if ((ioctl(fd, TIOCGSERIAL, &serialInfo) == 0) && (serialInfo.type != PORT_UNKNOWN))
{
// Add the port to the list of available ports
strcpy(friendlyName, "Physical Port ");
strcat(friendlyName, directoryEntry->d_name+3);
pushBack(comPorts, portDevPath, friendlyName, friendlyName, portLocation, "Unknown", "Unknown", -1, -1);
}
close(fd);
}
}
else // Emulated serial port
{
// See if the device has a registered friendly name
friendlyName[0] = '\0';
sprintf(basePathEnd, "../product");
FILE *input = fopen(fileName, "rb");
if (input)
{
fgets(friendlyName, 256, input);
friendlyName[strcspn(friendlyName, "\r\n")] = '\0';
fclose(input);
}
if (friendlyName[0] == '\0')
assignFriendlyName(portDevPath, friendlyName);
// Attempt to read the bus-reported device description
interfaceDescription[0] = '\0';
sprintf(basePathEnd, "interface");
input = fopen(fileName, "rb");
if (input)
{
fgets(interfaceDescription, 256, input);
interfaceDescription[strcspn(interfaceDescription, "\r\n")] = '\0';
fclose(input);
}
if (interfaceDescription[0] == '\0')
strcpy(interfaceDescription, friendlyName);
// Add the port to the list of available ports
pushBack(comPorts, portDevPath, friendlyName, interfaceDescription, portLocation, serialNumber, manufacturer, vendorID, productID);
}
// Read next TTY directory entry
directoryEntry = readdir(directoryIterator);
}
closedir(directoryIterator);
}
// Search through the system DEV directory for Bluetooth devices and PTY symlinks
directoryIterator = opendir("/dev/");
if (directoryIterator)
{
struct dirent *directoryEntry = readdir(directoryIterator);
while (directoryEntry)
{
// Ensure that the file name buffer is large enough
if ((16 + strlen(directoryEntry->d_name)) > fileNameMaxLength)
{
fileNameMaxLength = 16 + strlen(directoryEntry->d_name);
fileName = (char*)realloc(fileName, fileNameMaxLength);
}
// Check if the entry represents a valid serial port
strcpy(fileName, "/dev/");
strcat(fileName, directoryEntry->d_name);
if (isPtyDevice(fileName))
pushBack(comPorts, fileName, "PTY Device", "Pseudo-Terminal Device", "0-0", "Unknown", "Unknown", -1, -1);
else if (isBluetoothDevice(fileName))
pushBack(comPorts, fileName, "Bluetooth Device", "Bluetooth Device", "0-0", "Unknown", "Unknown", -1, -1);
// Read next TTY directory entry
directoryEntry = readdir(directoryIterator);
}
closedir(directoryIterator);
}
// Clean up dynamically allocated memory
freeStringVector(&physicalPortPrefixes);
if (fileName)
free(fileName);
free(interfaceDescription);
free(serialNumber);
free(manufacturer);
free(portLocation);
free(friendlyName);
free(portDevPath);
free(line);
}
static baud_rate getBaudRateCode(baud_rate baudRate)
{
// Translate a raw baud rate into a system-specified one
switch (baudRate)
{
case 50:
return B50;
case 75:
return B75;
case 110:
return B110;
case 134:
return B134;
case 150:
return B150;
case 200:
return B200;
case 300:
return B300;
case 600:
return B600;
case 1200:
return B1200;
case 1800:
return B1800;
case 2400:
return B2400;
case 4800:
return B4800;
case 9600:
return B9600;
case 19200:
return B19200;
case 38400:
return B38400;
case 57600:
#ifdef B57600
return B57600;
#else
return 0;
#endif
case 76800:
#ifdef B76800
return B76800;
#else
return 0;
#endif
case 115200:
#ifdef B115200
return B115200;
#else
return 0;
#endif
case 153600:
#ifdef B153600
return B153600;
#else
return 0;
#endif
case 230400:
#ifdef B230400
return B230400;
#else
return 0;
#endif
case 307200:
#ifdef B307200
return B307200;
#else
return 0;
#endif
case 460800:
#ifdef B460800
return B460800;
#else
return 0;
#endif
case 500000:
#ifdef B500000
return B500000;
#else
return 0;
#endif
case 576000:
#ifdef B576000
return B576000;
#else
return 0;
#endif
case 614400:
#ifdef B614400
return B614400;
#else
return 0;
#endif
case 921600:
#ifdef B921600
return B921600;
#else
return 0;
#endif
case 1000000:
#ifdef B1000000
return B1000000;
#else
return 0;
#endif
case 1152000:
#ifdef B1152000
return B1152000;
#else
return 0;
#endif
case 1500000:
#ifdef B1500000
return B1500000;
#else
return 0;
#endif
case 2000000:
#ifdef B2000000
return B2000000;
#else
return 0;
#endif
case 2500000:
#ifdef B2500000
return B2500000;
#else
return 0;
#endif
case 3000000:
#ifdef B3000000
return B3000000;
#else
return 0;
#endif
case 3500000:
#ifdef B3500000
return B3500000;
#else
return 0;
#endif
case 4000000:
#ifdef B4000000
return B4000000;
#else
return 0;
#endif
default:
return 0;
}
return 0;
}
int setConfigOptions(int portFD, baud_rate baudRate, struct termios *options)
{
// Set options using different methodologies based on availability of baud rate settings
int retVal = -1;
baud_rate baudRateCode = getBaudRateCode(baudRate);
if (baudRateCode)
{
// Directly set baud rate and apply all configuration options
cfsetispeed(options, baudRateCode);
cfsetospeed(options, baudRateCode);
retVal = tcsetattr(portFD, TCSANOW, options);
}
else
{
// Copy termios info into newer termios2 data structure
struct termios2 options2 = { 0 };
options2.c_cflag = (options->c_cflag & ~(CBAUD | CBAUDEX)) | BOTHER;
options2.c_iflag = options->c_iflag;
options2.c_oflag = options->c_oflag;
options2.c_lflag = options->c_lflag;
options2.c_line = options->c_line;
options2.c_ispeed = baudRate;
options2.c_ospeed = baudRate;
memcpy(options2.c_cc, options->c_cc, K_NCCS * sizeof(cc_t));
retVal = ioctl(portFD, T2CSANOW, &options2);
}
return retVal;
}
// Solaris-specific functionality
#elif defined(__sun__)
void searchForComPorts(serialPortVector* comPorts)
{
// Open the Solaris callout dev directory
DIR *directoryIterator = opendir("/dev/cua/");
if (directoryIterator)
{
// Read all files in the current directory
struct dirent *directoryEntry = readdir(directoryIterator);
while (directoryEntry)
{
// See if the file names a potential serial port
if ((strlen(directoryEntry->d_name) >= 1) && (directoryEntry->d_name[0] != '.'))
{
// Determine system name of port
char* systemName = (char*)malloc(256);
strcpy(systemName, "/dev/cua/");
strcat(systemName, directoryEntry->d_name);
// Check if port is already enumerated
serialPort *port = fetchPort(comPorts, systemName);
if (port)
port->enumerated = 1;
else
{
// Set static friendly name
char* friendlyName = (char*)malloc(256);
strcpy(friendlyName, "Serial Port");
// Add the port to the list if it is not a directory
struct stat fileStats;
stat(systemName, &fileStats);
if (!S_ISDIR(fileStats.st_mode))
pushBack(comPorts, systemName, friendlyName, friendlyName, "0-0", "Unknown", "Unknown", -1, -1);
// Clean up memory
free(friendlyName);
}
// Clean up memory
free(systemName);
}
directoryEntry = readdir(directoryIterator);
}
// Close the directory
closedir(directoryIterator);
}
// Open the Solaris dial-in dev directory
directoryIterator = opendir("/dev/term/");
if (directoryIterator)
{
// Read all files in the current directory
struct dirent *directoryEntry = readdir(directoryIterator);
while (directoryEntry)
{
// See if the file names a potential serial port
if ((strlen(directoryEntry->d_name) >= 1) && (directoryEntry->d_name[0] != '.'))
{
// Determine system name of port
char* systemName = (char*)malloc(256);
strcpy(systemName, "/dev/term/");
strcat(systemName, directoryEntry->d_name);
// Check if port is already enumerated
serialPort *port = fetchPort(comPorts, systemName);
if (port)
port->enumerated = 1;
else
{
// Set static friendly name
char* friendlyName = (char*)malloc(256);
strcpy(friendlyName, "Serial Port (Dial-In)");
// Add the port to the list if the file is not a directory
struct stat fileStats;
stat(systemName, &fileStats);
if (!S_ISDIR(fileStats.st_mode))
pushBack(comPorts, systemName, friendlyName, friendlyName, "0-0", "Unknown", "Unknown", -1, -1);
// Clean up memory
free(friendlyName);
}
// Clean up memory
free(systemName);
}
directoryEntry = readdir(directoryIterator);
}
// Close the directory
closedir(directoryIterator);
}
}
uint32_t __stack_chk_fail_local()
{
return 0;
}
int flock(int fd, int op)
{
int rc = 0;
#if defined(F_SETLK) && defined(F_SETLKW)
struct flock fl = { 0 };
switch (op & (LOCK_EX | LOCK_SH | LOCK_UN))
{
case LOCK_EX:
fl.l_type = F_WRLCK;
break;
case LOCK_SH:
fl.l_type = F_RDLCK;
break;
case LOCK_UN:
fl.l_type = F_UNLCK;
break;
default:
errno = EINVAL;
return -1;
}
fl.l_whence = SEEK_SET;
rc = fcntl(fd, op & LOCK_NB ? F_SETLK : F_SETLKW, &fl);
if (rc && (errno == EAGAIN))