forked from nutechsoftware/ser2sock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ser2sock.c
2293 lines (2019 loc) · 54.1 KB
/
ser2sock.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
/******************************************************************************\
*
* MODULE: ser2sock.c
* Copyright (C) 2013 Nu Tech Software Solutions, Inc.
* All rights reserved
* Reproduction without permission is prohibited
*
* This file may be used under the terms of the GNU General Public
* License versions 3.0 as published by the Free Software Foundation
* and appearing in the file COPYING included in the packaging of this project.
*
* This file is provided "AS IS" with NO WARRANTY OF ANY KIND,
* INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE. Nu Tech reserves all rights not expressly
* granted herein.
*
*
* PURPOSE: Connect to a given device file such as a serial device and multiplex
* all messages from this file to every socket that is connected.
*
* DEVELOPED BY: Sean Mathews
* https://www.nutech.com/
*
*
* Thanks to Richard Perlman [ad2usb at perlman.com] for his help testing on
* bsd and excellent feedback on features. Also a big thanks to everyone
* that helped support the AD2USB project get off the ground.
*
\******************************************************************************/
#define _GNU_SOURCE
#include "config.h"
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <syslog.h>
#include <signal.h>
#include <stdarg.h>
#include <time.h>
#include <sys/time.h>
#include <arpa/inet.h>
#include <ctype.h>
#ifdef _POSIX_SOURCE
#include <sched.h>
#endif
#ifdef HAVE_LIBSSL
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#endif
#define SER2SOCK_VERSION "V1.5.2"
#define TRUE 1
#define FALSE 0
#define MAXCLIENTCONNECTIONS 10
#define MAXCONNECTIONS MAXCLIENTCONNECTIONS+2
#define MAX_FIFO_BUFFERS 30
#define SERIAL_CONNECTED_MSG "!SER2SOCK SERIAL_CONNECTED\r\n"
#define SERIAL_DISCONNECTED_MSG "!SER2SOCK SERIAL_DISCONNECTED\r\n"
#define SOCKET_CONNECTED_MSG "!SER2SOCK Connected\r\n"
#define DEFAULT_CONFIG_PATH "/etc/ser2sock/ser2sock.conf"
#define DEFAULT_CRL_LOCATION "/etc/ser2sock/ser2sock.crl"
#define DAEMON_NAME "ser2sock"
#define PID_FILE "/var/run/ser2sock.pid"
/* <Types and Constants> */
typedef int BOOL;
const char terminal_init_string[] = "\377\375\042";
const char * fd_type_strings[] =
{ "NA", "LISTEN", "CLIENT", "SERIAL" };
enum FD_TYPES
{
NA, LISTEN_SOCKET = 1, CLIENT_SOCKET, SERIAL
} fd_types;
#define STREAM_MAIN 0
#define STREAM_SERIAL 1
char * syslog_format_type_strings[] =
{ "", "[✔] ", "[‼] ", "[✘] " };
int syslog_format_type_priority[] =
{ LOG_INFO, LOG_INFO, LOG_WARNING, LOG_ERR };
char * stderr_format_type_strings[] =
{ "", "[\033[1;32m✔\033[0m] ", "[\033[1;33m‼\033[0m] ", "[\033[1;31m✘\033[0m] " };
enum MESSAGE_TYPES
{
MSG_NONE = 0, MSG_GOOD, MSG_WARN, MSG_BAD
} msg_types;
typedef struct
{
char *name;
int flag;
} speed_spec;
speed_spec speeds[] =
{
{ "1200", B1200 },
{ "2400", B2400 },
{ "4800", B4800 },
{ "9600", B9600 },
{ "19200", B19200 },
{ "38400", B38400 },
{ "57600", B57600 },
{ "115200", B115200 },
{ NULL, 0 } };
/* </Types and Constants> */
#if defined __FreeBSD__
typedef unsigned char byte_t;
#else
typedef char byte_t;
#endif
/* <Structures> */
typedef struct
{
int last;
char message[2048];
} logstream;
typedef struct
{
int size, in, out, avail;
void **table;
} fifo;
typedef struct
{
int size;
byte_t buffer[];
} fifo_buffer;
typedef struct
{
/* flags */
int inuse;
int fd_type;
/* the fd */
int fd;
#ifdef HAVE_LIBSSL
/* SSL descriptor */
BIO* ssl;
BOOL handshake_done;
#endif
/* persistent settings */
struct termios oldtio;
/* the buffer */
fifo send_buffer;
} FDs;
/* </Structures> */
/* <Prototypes> */
int init_system();
int init_listen_socket_fd();
int init_serial_fd(char *path);
void add_to_all_socket_fds(char *message, unsigned int len);
void add_to_serial_fd(char * message, unsigned int len);
int cleanup_fd(int n);
void set_non_blocking(int fd);
void print_serial_fd_status(int fd);
int get_baud(char *szbaud);
void listen_loop();
void log_message(int stream,int type, char *msg, ...);
void vlog_message(int stream,int type, char *msg, va_list arg);
void error(char *msg, ...);
int kbhit();
int add_fd(int fd, int fd_type);
int __nsleep(const struct timespec *req, struct timespec *rem);
int msleep(unsigned long milisec);
void show_help();
void signal_handler(int sig);
BOOL read_config(char* filename);
// fifo buffer stuff
void fifo_init(fifo *f, int size);
void fifo_destroy(fifo *f);
int fifo_empty(fifo *f);
void* fifo_make_buffer(void *in_buffer, unsigned int len);
int fifo_add(fifo *f, void *next);
void* fifo_get(fifo *f);
void fifo_clear(fifo *f);
static void writepid(void);
#ifdef HAVE_LIBSSL
BOOL init_ssl();
void shutdown_ssl();
void shutdown_ssl_conn(BIO* sslbio);
#ifdef SSL_DEBUGGING
long tls_bio_dump_cb(BIO *bio, int cmd, const char *argp, int argi,
long unused_argl, long ret);
void apps_ssl_info_callback(const SSL *s, int where, int ret);
void ssl_msg_callback(int write_p, int version, int content_type,
const void *buf, size_t len, SSL * ssl, void *arg);
#endif
#endif
/* </Prototypes> */
/* <Globals> */
/* Our process ID and Session ID */
pid_t pid=0, sid=0;
volatile sig_atomic_t got_hup = 0;
char * serial_device_name = 0;
int listen_port = 10000;
int socket_timeout = 10;
int listen_backlog = 10;
FDs my_fds[MAXCONNECTIONS];
/* our listen socket */
int listen_sock_fd = -1;
struct sockaddr_in serv_addr;
struct sockaddr_in peer_addr;
// fifo buffer
fifo data_buffer;
char * option_config_path = NULL;
char * option_bind_ip = NULL;
char * option_baud_rate = NULL;
BOOL option_daemonize = FALSE;
BOOL option_raw_device_mode = FALSE;
BOOL option_send_terminal_init = FALSE;
int option_debug_level = 0;
BOOL option_keep_connection = FALSE;
int option_open_serial_delay = 5000;
char * option_pid_file = NULL;
int serial_connected = 0;
struct timeval tv_serial_start, tv_last_serial_check;
#ifdef HAVE_LIBSSL
BOOL option_ssl = FALSE;
SSL_CTX* sslctx = 0;
BIO* bio = 0, *abio = 0;
char* option_ca_certificate = NULL;
char* option_ssl_certificate = NULL;
char* option_ssl_key = NULL;
char* option_ssl_crl = DEFAULT_CRL_LOCATION;
#endif
/* </Globals> */
/* <Code> */
/*
show our error message and die
todo: add params.
*/
void error(char *msg, ...)
{
char * szError = strerror(errno);
va_list arg;
va_start(arg, msg);
vlog_message(STREAM_MAIN,MSG_BAD, msg, arg);
va_end(arg);
log_message(STREAM_MAIN,MSG_BAD, " :");
log_message(STREAM_MAIN,MSG_BAD, szError);
log_message(STREAM_MAIN,MSG_BAD, "\n");
log_message(STREAM_MAIN,MSG_BAD, "exiting\n");
exit(EXIT_FAILURE);
}
/*
log a message to console or syslog
*/
void log_message(int stream, int type,char *msg, ...)
{
va_list arg;
if (msg)
{
va_start(arg, msg);
vlog_message(stream,type, msg, arg);
va_end(arg);
}
}
void vlog_message(int s,int type, char *msg, va_list arg)
{
/* 2 queue's so we can watch 2 log streams for \n's static so auto init to 0's */
static logstream ls[2];
static BOOL syslog_open=FALSE;
int x,y,z=0;
BOOL done=FALSE;
if (option_daemonize && !syslog_open) {
openlog(DAEMON_NAME, LOG_CONS | LOG_NDELAY | LOG_PERROR | LOG_PID,
LOG_USER);
syslog_open=TRUE;
}
ls[s].last += vsnprintf(&ls[s].message[ls[s].last], sizeof(ls[0].message) - ls[s].last, msg, arg);
/* check for overflow error */
if (ls[s].last >= sizeof(ls[0].message))
ls[s].last = 0;
if (ls[s].last) {
/* keep trying till we exause all \n's */
while(!done)
{
/* look for an eol char */
for (x = 0; x < ls[s].last ; x++) {
if(ls[s].message[x] == '\n' || ls[s].message[x] == '\r') {
ls[s].message[x]=0;
if(x)
{
if (option_daemonize)
{
if (type) {
syslog(syslog_format_type_priority[type], "%s%s",
syslog_format_type_strings[type], ls[s].message);
}
else
syslog(LOG_INFO, "%s", ls[s].message);
}
else
{
if (type)
fprintf(stderr, "%s%s\n", stderr_format_type_strings[type], ls[s].message);
else {
fprintf(stderr, "%s\n", ls[s].message);
fflush(stderr);
}
}
}
/* move the rest to the start and clean out any non printable chars */
z = 0;
for(y = x+1; y < ls[s].last ; y++) {
if((ls[s].message[y]>0x1f && ls[s].message[y]<0x7f) || ls[s].message[y]=='\n') {
ls[s].message[z++]=ls[s].message[y];
}
}
/* set our next fill position */
ls[s].last = z;
/* again */
break;
}
}
/* ok we reached the end of our buffer and found no more \n's */
done = TRUE;
}
}
}
/*
nanosecond sleep
*/
int __nsleep(const struct timespec *req, struct timespec *rem)
{
struct timespec temp_rem;
if (nanosleep(req, rem) == -1)
__nsleep(rem, &temp_rem);
return TRUE;
}
/*
sleep for N milliseconds
*/
int msleep(unsigned long milisec)
{
struct timespec req =
{ 0 }, rem =
{ 0 };
time_t sec = (int) (milisec / 1000);
milisec = milisec - (sec * 1000);
req.tv_sec = sec;
req.tv_nsec = milisec * 1000000L;
__nsleep(&req, &rem);
return 1;
}
/*
show help info
*/
void show_help(const char *appName)
{
fprintf(
stderr,
"Usage: %s -p <socket listen port> -s <serial port dev>\n\n"
" -h, -help display this help and exit\n"
" -f <config path> override config file path and name\n"
" -p port socket port to listen on\n"
" -s <serial device> serial device; ex /dev/ttyUSB0\n"
"options\n"
" -i IP bind to a specific ip address; default is ALL\n"
" -b baudrate set baud rate; defaults to 9600\n"
" -d daemonize\n"
" -0 raw device mode - no info messages\n"
" -t send terminal init string\n"
" -P <pid pathname> override default PID file path and name\n"
" -g debug level 0-3\n"
" -c keep incoming connections when a serial device is disconnected\n"
" -w milliseconds delay between attempts to open a serial device (5000)\n"
#ifdef HAVE_LIBSSL
" -e use SSL to encrypt the connection\n"
#endif
"\n", appName);
}
/*
Initialize any structures etc.
*/
int init_system()
{
int x;
for (x = 0; x < MAXCONNECTIONS; x++)
{
my_fds[x].inuse = FALSE;
my_fds[x].fd = -1;
my_fds[x].fd_type = NA;
#ifdef HAVE_LIBSSL
my_fds[x].ssl = 0;
my_fds[x].handshake_done = FALSE;
#endif
fifo_init(&my_fds[x].send_buffer, MAX_FIFO_BUFFERS);
}
/* Setup signal handling if we are to daemonize */
if (option_daemonize)
{
signal(SIGTERM, signal_handler);
signal(SIGINT, signal_handler);
signal(SIGQUIT, signal_handler);
setlogmask(LOG_UPTO(LOG_DEBUG));
}
// HUP is always bound.
signal(SIGHUP, signal_handler);
return TRUE;
}
/*
clear all memory used before we exit
*/
int free_system()
{
int x;
for (x = 0; x < MAXCONNECTIONS; x++)
{
cleanup_fd(x);
fifo_destroy(&my_fds[x].send_buffer);
}
#ifdef HAVE_LIBSSL
if (option_ssl)
shutdown_ssl();
#endif
return TRUE;
}
/*
Initialize our listening socket and related api's
*/
int init_listen_socket_fd()
{
BOOL bOptionTrue = TRUE;
int results;
struct linger solinger;
#ifdef HAVE_LIBSSL
if (option_ssl)
{
if (!init_ssl())
return FALSE;
}
else
#endif
{
/* create a listening socket fd */
listen_sock_fd = socket(AF_INET, SOCK_STREAM, 0);
if (listen_sock_fd < 0)
{
log_message(STREAM_MAIN, MSG_BAD, "Fatal error creating our listening socket errno: %i\n",errno);
return FALSE;
}
/* clear our socket address structure */
bzero((char *) &serv_addr, sizeof(serv_addr));
if (option_bind_ip != NULL)
{
results = inet_pton(AF_INET, option_bind_ip, &serv_addr.sin_addr);
if (results != 1)
{
log_message(STREAM_MAIN, MSG_BAD, "Fatal error unable to bind to provided IP %s errno: %i\n",
option_bind_ip,errno);
return FALSE;
}
}
else
{
serv_addr.sin_addr.s_addr = INADDR_ANY;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(listen_port);
setsockopt(listen_sock_fd, SOL_SOCKET, SO_SNDTIMEO,
(char *) &socket_timeout, sizeof(socket_timeout));
setsockopt(listen_sock_fd, SOL_SOCKET, SO_RCVTIMEO,
(char *) &socket_timeout, sizeof(socket_timeout));
setsockopt(listen_sock_fd, SOL_SOCKET, SO_REUSEADDR, (char *) &bOptionTrue,
sizeof(bOptionTrue));
solinger.l_onoff = TRUE;
solinger.l_linger = 0;
setsockopt(listen_sock_fd, SOL_SOCKET, SO_LINGER, &solinger, sizeof(solinger));
if (bind(listen_sock_fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr))< 0)
{
log_message(STREAM_MAIN, MSG_BAD, "Fatal error binding to server port %i errno: %i\n",listen_port,errno);
return FALSE;
}
listen(listen_sock_fd, listen_backlog);
set_non_blocking(listen_sock_fd);
}
add_fd(listen_sock_fd, LISTEN_SOCKET);
log_message(STREAM_MAIN, MSG_GOOD, "Listening socket created on port %i\n", listen_port);
return TRUE;
}
/*
Init serial port and add fd to our list of sockets
*/
int init_serial_fd(char * szPortPath)
{
struct termios newtio;
int id, x;
long BAUD;
int fd = open(szPortPath, O_RDWR | O_NOCTTY | O_NDELAY);
if (fd < 0)
{
log_message(STREAM_MAIN, MSG_BAD, "Error can not open com port at %s errno: %i '%s'\n", szPortPath, errno, strerror(errno));
return fd;
}
log_message(STREAM_MAIN, MSG_GOOD, "Opened com port at %s\n", szPortPath);
/* add it and get our structure */
id = add_fd(fd, SERIAL);
if (id < 0)
{
log_message(STREAM_MAIN, MSG_BAD, "Error can not add the serial fd\n");
close(fd);
return 0;
}
// derived baud rate from command line default to B9600
BAUD = get_baud(option_baud_rate);
/* alredy done above in the open but Richard had this in his tests and it worked so
I am adding it back in for now maybe some bug in the os */
fcntl(fd, F_SETFL, FNDELAY);
/* backup the original terminal io settings to restore back to later
removed for now Richards mod didnt save the old value */
tcgetattr(fd, &my_fds[id].oldtio);
/* get the current terminal settings */
tcgetattr(fd, &newtio);
/* Set the baud rates */
cfsetispeed(&newtio, BAUD);
cfsetospeed(&newtio, BAUD);
/* change our c_cflag settings a little for the port */
newtio.c_cflag |= (CLOCAL | CREAD); /* Enable the receiver and set local mode */
newtio.c_cflag &= ~PARENB; /* Mask the character size to 8 bits, no parity */
newtio.c_cflag &= ~CSTOPB;
newtio.c_cflag &= ~CSIZE;
newtio.c_cflag |= CS8; /* Select 8 data bits */
newtio.c_cflag &= ~CRTSCTS; /* Disable hardware flow control */
if (option_debug_level > 2)
log_message(STREAM_MAIN, MSG_WARN, "c_cflags old:%08x new:%08x\n", my_fds[id].oldtio.c_cflag,
newtio.c_cflag);
/* change our c_lflag settings enable raw input mode */
newtio.c_lflag &= ~(ICANON | ECHO | ISIG);
if (option_debug_level > 2)
log_message(STREAM_MAIN, MSG_WARN, "c_lflags old:%08x new:%08x\n", my_fds[id].oldtio.c_lflag,
newtio.c_lflag);
/* change our c_iflag settings (turn off all flags) */
newtio.c_iflag = 0;
if (option_debug_level > 2)
log_message(STREAM_MAIN, MSG_WARN, "c_iflags old:%08x new:%08x\n", my_fds[id].oldtio.c_iflag,
newtio.c_iflag);
/* change our c_oflag settings (turn off all flags) */
newtio.c_oflag = 0;
if (option_debug_level > 2)
log_message(STREAM_MAIN, MSG_WARN, "c_oflags old:%08x new:%08x\n", my_fds[id].oldtio.c_oflag,
newtio.c_oflag);
/* dump bytes out of old c_cc */
if (option_debug_level > 2)
{
log_message(STREAM_MAIN, MSG_WARN, "c_cc old: ");
for (x = 0; x < sizeof(my_fds[id].oldtio.c_cc); x++)
{
log_message(STREAM_MAIN, MSG_WARN, "%02x:", my_fds[id].oldtio.c_cc[x]);
}
log_message(STREAM_MAIN, MSG_WARN, "\n");
}
newtio.c_cc[VINTR] = 0; /* Ctrl-c */
newtio.c_cc[VQUIT] = 0; /* Ctrl-\ */
newtio.c_cc[VERASE] = 0; /* del */
newtio.c_cc[VKILL] = 0; /* @ */
newtio.c_cc[VEOF] = 4; /* Ctrl-d */
newtio.c_cc[VTIME] = 0; /* inter-character timer unused */
newtio.c_cc[VMIN] = 1; /* blocking read until 1 character arrives */
# ifdef VSWTC
newtio.c_cc[VSWTC] = 0;
# endif
newtio.c_cc[VSTART] = 0; /* Ctrl-q */
newtio.c_cc[VSTOP] = 0; /* Ctrl-s */
newtio.c_cc[VSUSP] = 0; /* Ctrl-z */
newtio.c_cc[VEOL] = 0; /* '\0' */
newtio.c_cc[VREPRINT] = 0; /* Ctrl-r */
newtio.c_cc[VDISCARD] = 0; /* Ctrl-u */
newtio.c_cc[VWERASE] = 0; /* Ctrl-w */
newtio.c_cc[VLNEXT] = 0; /* Ctrl-v */
newtio.c_cc[VEOL2] = 0; /* '\0' */
/* dump bytes out of new c_cc */
if (option_debug_level > 2)
{
log_message(STREAM_MAIN, MSG_WARN, "c_cc new: ");
for (x = 0; x < sizeof(newtio.c_cc); x++)
{
log_message(STREAM_MAIN, MSG_WARN, "%02x:", newtio.c_cc[x]);
}
log_message(STREAM_MAIN, MSG_WARN, "\n");
}
tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &newtio);
if (option_debug_level > 2)
print_serial_fd_status(fd);
log_message(STREAM_MAIN, MSG_GOOD, "Set speed successful\n");
return 1;
}
/*
prints out the specific serial fd terminal flags
*/
void print_serial_fd_status(int fd)
{
int status;
unsigned int arg;
status = ioctl(fd, TIOCMGET, &arg);
log_message(STREAM_MAIN, MSG_GOOD, "Serial status (%i) ",status);
if (arg & TIOCM_RTS)
log_message(STREAM_MAIN, MSG_GOOD, "RTS ");
if (arg & TIOCM_CTS)
log_message(STREAM_MAIN, MSG_GOOD, "CTS ");
if (arg & TIOCM_DSR)
log_message(STREAM_MAIN, MSG_GOOD, "DSR ");
if (arg & TIOCM_CAR)
log_message(STREAM_MAIN, MSG_GOOD, "DCD ");
if (arg & TIOCM_DTR)
log_message(STREAM_MAIN, MSG_GOOD, "DTR ");
if (arg & TIOCM_RNG)
log_message(STREAM_MAIN, MSG_GOOD, "RI ");
log_message(STREAM_MAIN, MSG_GOOD, "\n");
}
/*
gets the baud numeric from a string constant
*/
int get_baud(char * szbaud)
{
speed_spec *s;
int speed = 0;
if (szbaud != 0)
{
for (s = speeds; s->name; s++)
{
if (strcmp(s->name, szbaud) == 0)
{
speed = s->flag;
break;
}
}
}
/* default to 3 in our array or 9600 */
if (speed == 0)
s = &speeds[3];
log_message(STREAM_MAIN, MSG_GOOD, "Setting speed %s\n", s->name);
return s->flag;
}
/*
Makes a fd non blocking
*/
void set_non_blocking(int fd)
{
int nonb = 0;
int res = 1;
nonb |= O_NONBLOCK;
if (ioctl(fd, FIONBIO, &res) < 0)
error("Error setting FIONBIO");
}
/*
Add a fd to our array so we can poll it in our state machien loop
*/
int add_fd(int fd, int fd_type)
{
int x;
int results = -1;
struct linger solinger;
for (x = 0; x < MAXCONNECTIONS; x++)
{
if (my_fds[x].inuse == FALSE)
{
if (option_debug_level > 2)
log_message(STREAM_MAIN, MSG_WARN, "Adding %s fd at %i\n", fd_type_strings[fd_type], x);
if (fd_type != SERIAL)
{
solinger.l_onoff = TRUE;
solinger.l_linger = 0;
setsockopt(fd, SOL_SOCKET, SO_LINGER, &solinger, sizeof(solinger));
}
my_fds[x].inuse = TRUE;
my_fds[x].fd_type = fd_type;
my_fds[x].fd = fd;
results = x;
break;
}
}
return results;
}
/*
Cleanup an entry in the fd array and do any fd_type specific cleanup
*/
int cleanup_fd(int n)
{
/* don't do anything unless its in was active */
if (my_fds[n].inuse)
{
/* if this is a terminal or serial fd then restore its settings */
if (my_fds[n].fd_type == SERIAL)
{
tcsetattr(my_fds[n].fd, TCSANOW, &my_fds[n].oldtio);
serial_connected = FALSE;
}
#ifdef HAVE_LIBSSL
if (my_fds[n].ssl != NULL)
shutdown_ssl_conn(my_fds[n].ssl);
my_fds[n].ssl = NULL;
my_fds[n].handshake_done = FALSE;
#endif
/* close the fd */
close(my_fds[n].fd);
my_fds[n].fd = -1;
/* clear any data we have saved */
fifo_clear(&my_fds[n].send_buffer);
/* mark the element as free for reuse */
my_fds[n].inuse = FALSE;
/* set the type to null */
my_fds[n].fd_type = NA;
}
return TRUE;
}
/*
Diff two time values
*/
long get_time_difference(struct timeval *startTime)
{
struct timeval endTime;
long seconds, nseconds;
gettimeofday(&endTime, NULL);
seconds = endTime.tv_sec - startTime->tv_sec;
nseconds = endTime.tv_usec - startTime->tv_usec;
return seconds * 1000 + nseconds / 1000;
}
#define clear_serial(n) \
tv_serial_start.tv_sec = 0; \
tv_serial_start.tv_usec = 0; \
serial_connected = 0; \
cleanup_fd(n); \
if (!option_raw_device_mode) { \
add_to_all_socket_fds("\r\n", 0); \
add_to_all_socket_fds(SERIAL_DISCONNECTED_MSG, 0); \
} \
msleep(100); \
/*
check for a hup signal and hup work if needed
*/
BOOL hup_check()
{
/* did we get a hup signal? */
if (!got_hup)
return FALSE;
/* clear it */
got_hup = 0;
free_system();
read_config(option_config_path ? option_config_path : DEFAULT_CONFIG_PATH);
init_system();
init_listen_socket_fd();
return TRUE;
}
/*
poll the serial port reconnect if needed
*/
void poll_serial_port()
{
/* if our port is not connected check if we should try to reconnect */
if (!serial_connected)
{
if ((tv_serial_start.tv_sec == 0) || (get_time_difference(&tv_serial_start)
>= option_open_serial_delay))
{
gettimeofday(&tv_serial_start, NULL);
if (init_serial_fd(serial_device_name) > 0)
{
serial_connected = 1;
tv_last_serial_check.tv_sec = 0;
tv_last_serial_check.tv_usec = 0;
if (!option_raw_device_mode)
add_to_all_socket_fds(SERIAL_CONNECTED_MSG, 0);
}
else
msleep(10);
}
else
msleep(10);
return;
}
#ifdef USE_TIOCMGET
int n,tmp;
/* periodic serial device checking */
if ((tv_last_serial_check.tv_sec == 0) || (get_time_difference(
&tv_last_serial_check) >= 100))
{
errno = 0;
gettimeofday(&tv_last_serial_check, NULL);
for (n = 0; n < MAXCONNECTIONS; n++)
{
if (my_fds[n].fd_type == SERIAL && my_fds[n].inuse == TRUE)
{
if (ioctl(my_fds[n].fd, TIOCMGET, &tmp) < 0)
{
log_message(STREAM_MAIN, MSG_WARN, "Serial disconnected on check. errno: %i '%s'\n", errno, strerror(errno));
clear_serial(n);
}
/* currently only 1 serial port so we are done */
break;
}
}
}
#endif
}
/*
add all of our fd to our r,w and e fd sets
*/
void build_fdsets(fd_set *read_fdset, fd_set *write_fdset, fd_set *except_fdset)
{
int n;
/* add all sockets to our fdset */
FD_ZERO(read_fdset);
FD_ZERO(write_fdset);
FD_ZERO(except_fdset);
for (n = 0; n < MAXCONNECTIONS; n++)
{
if (my_fds[n].inuse == TRUE)
{
FD_SET(my_fds[n].fd,read_fdset);
FD_SET(my_fds[n].fd,write_fdset);
FD_SET(my_fds[n].fd,except_fdset);
}
}
}
/*
poll any exception fd's return TRUE if we did some work
*/
BOOL poll_exception_fdset(fd_set *except_fdset)
{
int n;
BOOL did_work = FALSE;
for (n = 0; n < MAXCONNECTIONS; n++)
{
if (my_fds[n].inuse == TRUE)
{
if (FD_ISSET(my_fds[n].fd,except_fdset))
{
if (my_fds[n].fd_type == CLIENT_SOCKET)
{
did_work = TRUE;
log_message(STREAM_MAIN, MSG_WARN, "Exception occured on socket fd slot %i closing the socket.\n",n);
cleanup_fd(n);
}
}
}
}
return did_work;
}
/*
poll any read fd's return TRUE if we did do some work
*/
BOOL poll_read_fdset(fd_set *read_fdset)
{
int x, n, received, newsockfd, added_slot;
unsigned int clilen;
byte_t *tempbuffer;
BOOL did_work = FALSE;
byte_t buffer[1024];
#ifdef HAVE_LIBSSL
BIO* newbio = 0;
#endif
clilen = sizeof(struct sockaddr_in);
/* check every socket to find the one that needs read */
for (n = 0; n < MAXCONNECTIONS; n++)
{
if (my_fds[n].inuse == TRUE)
{
/* check read fd */
if (FD_ISSET(my_fds[n].fd,read_fdset))
{
/* if this is a listening socket then we accept on it and
* get a new client socket
*/
if (my_fds[n].fd_type == LISTEN_SOCKET)
{