forked from Mictronics/readsb-protobuf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
net_io.c
3448 lines (2958 loc) · 119 KB
/
net_io.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
// Part of readsb, a Mode-S/ADSB/TIS message decoder.
//
// net_io.c: network handling.
//
// Copyright (c) 2020 Michael Wolf <[email protected]>
//
// This code is based on a detached fork of dump1090-fa.
//
// Copyright (c) 2014-2016 Oliver Jowett <[email protected]>
//
// This file is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This file is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// This file incorporates work covered by the following copyright and
// license:
//
// Copyright (C) 2012 by Salvatore Sanfilippo <[email protected]>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "readsb.h"
/* for PRIX64 */
#include <inttypes.h>
#include <assert.h>
#include <stdarg.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <poll.h>
#include <pthread.h>
#include <linux/serial.h>
//
// ============================= Networking =============================
//
// Note: here we disregard any kind of good coding practice in favor of
// extreme simplicity, that is:
//
// 1) We only rely on the kernel buffers for our I/O without any kind of
// user space buffering.
// 2) We don't register any kind of event handler, from time to time a
// function gets called and we accept new connections. All the rest is
// handled via non-blocking I/O and manually polling clients to see if
// they have something new to share with us when reading is needed.
static int handleBeastCommand(struct client *c, char *p, int remote);
static int decodeBinMessage(struct client *c, char *p, int remote);
static int decodeHexMessage(struct client *c, char *hex, int remote);
static int decodeSbsLine(struct client *c, char *line, int remote);
static void send_raw_heartbeat(struct net_service *service);
static void send_beast_heartbeat(struct net_service *service);
static void send_sbs_heartbeat(struct net_service *service);
static void writeFATSVEvent(struct modesMessage *mm, struct aircraft *a);
static void writeFATSVPositionUpdate(float lat, float lon, float alt);
static void autoset_modeac();
static int hexDigitVal(int c);
static void *pthreadGetaddrinfo(void *param);
static void flushClient(struct client *c, uint64_t now);
//
//=========================================================================
//
// Networking "stack" initialization
//
// Init a service with the given read/write characteristics, return the new service.
// Doesn't arrange for the service to listen or connect
struct net_service *serviceInit(const char *descr, struct net_writer *writer, heartbeat_fn hb, read_mode_t mode, const char *sep, read_fn handler) {
struct net_service *service;
if (!descr) {
fprintf(stderr, "Fatal: no service description\n");
exit(1);
}
if (!(service = calloc(sizeof (*service), 1))) {
fprintf(stderr, "Out of memory allocating service %s\n", descr);
exit(1);
}
service->next = Modes.services;
Modes.services = service;
service->descr = descr;
service->listener_count = 0;
service->pusher_count = 0;
service->connections = 0;
service->writer = writer;
service->read_sep = sep;
service->read_sep_len = sep ? strlen(sep) : 0;
service->read_mode = mode;
service->read_handler = handler;
service->clients = NULL;
if (service->writer) {
if (!service->writer->data) {
if (!(service->writer->data = malloc(MODES_OUT_BUF_SIZE))) {
fprintf(stderr, "Out of memory allocating output buffer for service %s\n", descr);
exit(1);
}
}
service->writer->service = service;
service->writer->dataUsed = 0;
service->writer->lastWrite = mstime();
service->writer->send_heartbeat = hb;
}
return service;
}
// Create a client attached to the given service using the provided socket FD
struct client *createSocketClient(struct net_service *service, int fd) {
anetSetSendBuffer(Modes.aneterr, fd, (MODES_NET_SNDBUF_SIZE << Modes.net_sndbuf_size));
return createGenericClient(service, fd);
}
// Create a client attached to the given service using the provided FD (might not be a socket!)
struct client *createGenericClient(struct net_service *service, int fd) {
struct client *c;
uint64_t now = mstime();
if (anetNonBlock(Modes.aneterr, fd) == ANET_ERR) {
fprintf(stderr, "%s fd %d: Failed to set non-block: %s\n", service->descr, fd, Modes.aneterr);
}
if (!service || fd == -1) {
fprintf(stderr, "Fatal: createGenericClient called with invalid parameters!\n");
exit(1);
}
if (!(c = (struct client *) calloc(1, sizeof (*c)))) {
fprintf(stderr, "Out of memory allocating a new %s network client\n", service->descr);
exit(1);
}
c->service = service;
c->next = service->clients;
c->fd = fd;
c->buflen = 0;
c->modeac_requested = 0;
c->last_flush = now;
c->last_send = now;
c->sendq_len = 0;
c->sendq_max = 0;
c->sendq = NULL;
c->con = NULL;
if (service->writer) {
if (!(c->sendq = malloc(MODES_NET_SNDBUF_SIZE << Modes.net_sndbuf_size))) {
fprintf(stderr, "Out of memory allocating client SendQ\n");
exit(1);
}
// Have to keep track of this manually
c->sendq_max = MODES_NET_SNDBUF_SIZE << Modes.net_sndbuf_size;
}
service->clients = c;
++service->connections;
if (service->writer && service->connections == 1) {
service->writer->lastWrite = now; // suppress heartbeat initially
}
return c;
}
// Timer callback checking periodically whether the push service lost its server
// connection and requires a re-connect.
void serviceReconnectCallback(uint64_t now) {
// Loop through the connectors, and
// - If it's not connected:
// - If it's "connecting", check to see if the fd is ready
// - Otherwise, if enough time has passed, try reconnecting
for (int i = 0; i < Modes.net_connectors_count; i++) {
struct net_connector *con = Modes.net_connectors[i];
if (!con->connected) {
if (con->connecting) {
// Check to see...
checkServiceConnected(con);
} else {
if (con->next_reconnect <= now) {
serviceConnect(con);
}
}
}
}
}
struct client *checkServiceConnected(struct net_connector *con) {
int rv;
struct pollfd pfd = {con->fd, (POLLIN | POLLOUT), 0};
rv = poll(&pfd, 1, 0);
if (rv == -1) {
// select() error, just return a NULL here, but log it
fprintf(stderr, "checkServiceConnected: select() error: %s\n", strerror(errno));
return NULL;
}
if (rv == 0) {
// If we've exceeded our connect timeout, bail but try again.
if (mstime() >= con->connect_timeout) {
fprintf(stderr, "%s: Connection timed out: %s:%s port %s\n",
con->service->descr, con->address, con->port, con->resolved_addr);
con->connecting = 0;
anetCloseSocket(con->fd);
}
return NULL;
}
// At this point, we need to check getsockopt() to see if we succeeded or failed...
int optval = -1;
socklen_t optlen = sizeof (optval);
if (getsockopt(con->fd, SOL_SOCKET, SO_ERROR, &optval, &optlen) == -1) {
fprintf(stderr, "getsockopt failed: %d (%s)\n", errno, strerror(errno));
// Bad stuff going on, but clear this anyway
con->connecting = 0;
anetCloseSocket(con->fd);
return NULL;
}
if (optval != 0) {
// only 0 means "connection ok"
fprintf(stderr, "%s: Connection to %s%s port %s failed: %d (%s)\n",
con->service->descr, con->address, con->resolved_addr, con->port, optval, strerror(optval));
con->connecting = 0;
anetCloseSocket(con->fd);
return NULL;
}
// If we're able to create this "client", save the sockaddr info and print a msg
struct client *c;
c = createSocketClient(con->service, con->fd);
if (!c) {
con->connecting = 0;
fprintf(stderr, "createSocketClient failed on fd %d to %s%s port %s\n",
con->fd, con->address, con->resolved_addr, con->port);
anetCloseSocket(con->fd);
return NULL;
}
strncpy(c->host, con->address, sizeof (c->host) - 1);
strncpy(c->port, con->port, sizeof (c->port) - 1);
fprintf(stderr, "%s: Connection established: %s%s port %s\n",
con->service->descr, con->address, con->resolved_addr, con->port);
con->connecting = 0;
con->connected = 1;
c->con = con;
return c;
}
// Initiate an outgoing connection.
// Return the new client or NULL if the connection failed
struct client *serviceConnect(struct net_connector *con) {
int fd;
if (con->try_addr && con->try_addr->ai_next) {
// iterate the address info
con->try_addr = con->try_addr->ai_next;
} else {
// get the address info
if (!con->gai_request_in_progress) {
// launch a pthread for async getaddrinfo
con->try_addr = NULL;
if (con->addr_info) {
freeaddrinfo(con->addr_info);
con->addr_info = NULL;
}
if (pthread_create(&con->thread, NULL, pthreadGetaddrinfo, con)) {
con->next_reconnect = mstime() + 15000;
fprintf(stderr, "%s: pthread_create ERROR for %s port %s: %s\n", con->service->descr, con->address, con->port, strerror(errno));
return NULL;
}
con->gai_request_in_progress = 1;
con->next_reconnect = mstime() + 10;
return NULL;
} else {
if (pthread_mutex_trylock(con->mutex)) {
// couldn't acquire lock, request not finished
con->next_reconnect = mstime() + 50;
return NULL;
}
if (pthread_join(con->thread, NULL)) {
fprintf(stderr, "%s: pthread_join ERROR for %s port %s: %s\n", con->service->descr, con->address, con->port, strerror(errno));
con->next_reconnect = mstime() + 15000;
return NULL;
}
con->gai_request_in_progress = 0;
if (con->gai_error) {
fprintf(stderr, "%s: Name resolution for %s failed: %s\n", con->service->descr, con->address, gai_strerror(con->gai_error));
con->next_reconnect = mstime() + Modes.net_connector_delay;
return NULL;
}
con->try_addr = con->addr_info;
// SUCCESS!
}
}
getnameinfo(con->try_addr->ai_addr, con->try_addr->ai_addrlen,
con->resolved_addr, sizeof (con->resolved_addr) - 3,
NULL, 0,
NI_NUMERICHOST | NI_NUMERICSERV);
if (strcmp(con->resolved_addr, con->address) == 0) {
con->resolved_addr[0] = '\0';
} else {
char tmp[sizeof (con->resolved_addr) + 3]; // shut up gcc
snprintf(tmp, sizeof (tmp), " (%s)", con->resolved_addr);
memcpy(con->resolved_addr, tmp, sizeof (con->resolved_addr));
}
if (!con->try_addr->ai_next) {
con->next_reconnect = mstime() + Modes.net_connector_delay;
} else {
con->next_reconnect = mstime() + 100;
}
fd = anetTcpNonBlockConnectAddr(Modes.aneterr, con->try_addr);
if (fd == ANET_ERR) {
fprintf(stderr, "%s: Connection to %s%s port %s failed: %s\n",
con->service->descr, con->address, con->resolved_addr, con->port, Modes.aneterr);
return NULL;
}
con->connecting = 1;
con->connect_timeout = mstime() + 10 * 1000; // 10 sec TODO: Move to var
con->fd = fd;
if (anetTcpKeepAlive(Modes.aneterr, fd) != ANET_OK) {
fprintf(stderr, "%s: Unable to set keepalive: connection to %s port %s ...\n", con->service->descr, con->address, con->port);
}
// Since this is a non-blocking connect, it will always return right away.
// We'll need to periodically check to see if it did, in fact, connect, but do it once here.
return checkServiceConnected(con);
}
// Set up the given service to listen on an address/port.
// _exits_ on failure!
void serviceListen(struct net_service *service, char *bind_addr, char *bind_ports) {
int *fds = NULL;
int n = 0;
char *p, *end;
char buf[128];
if (service->listener_count > 0) {
fprintf(stderr, "Tried to set up the service %s twice!\n", service->descr);
exit(1);
}
if (!bind_ports || !strcmp(bind_ports, "") || !strcmp(bind_ports, "0"))
return;
p = bind_ports;
while (p && *p) {
int newfds[16];
int nfds, i;
end = strpbrk(p, ", ");
if (!end) {
strncpy(buf, p, sizeof (buf));
buf[sizeof (buf) - 1] = 0;
p = NULL;
} else {
size_t len = end - p;
if (len >= sizeof (buf))
len = sizeof (buf) - 1;
memcpy(buf, p, len);
buf[len] = 0;
p = end + 1;
}
nfds = anetTcpServer(Modes.aneterr, buf, bind_addr, newfds, sizeof (newfds));
if (nfds == ANET_ERR) {
fprintf(stderr, "Error opening the listening port %s (%s): %s\n",
buf, service->descr, Modes.aneterr);
exit(1);
}
fds = realloc(fds, (n + nfds) * sizeof (int));
if (!fds) {
fprintf(stderr, "out of memory\n");
exit(1);
}
for (i = 0; i < nfds; ++i) {
if (anetNonBlock(Modes.aneterr, newfds[i]) == ANET_ERR) {
fprintf(stderr, "%s port %s: Failed to set non-block: %s\n", service->descr, buf, Modes.aneterr);
}
fds[n++] = newfds[i];
}
}
service->listener_count = n;
service->listener_fds = fds;
}
struct net_service *makeBeastInputService(void) {
return serviceInit("Beast TCP input", NULL, NULL, READ_MODE_BEAST, NULL, decodeBinMessage);
}
struct net_service *makeFatsvOutputService(void) {
return serviceInit("FATSV TCP output", &Modes.fatsv_out, NULL, READ_MODE_IGNORE, NULL, NULL);
}
void modesInitNet(void) {
struct net_service *beast_out;
struct net_service *beast_reduce_out;
struct net_service *beast_in;
struct net_service *raw_out;
struct net_service *raw_in;
struct net_service *vrs_out;
struct net_service *sbs_out;
struct net_service *sbs_in;
uint64_t now = mstime();
signal(SIGPIPE, SIG_IGN);
Modes.services = NULL;
// set up listeners
raw_out = serviceInit("Raw TCP output", &Modes.raw_out, send_raw_heartbeat, READ_MODE_IGNORE, NULL, NULL);
serviceListen(raw_out, Modes.net_bind_address, Modes.net_output_raw_ports);
beast_out = serviceInit("Beast TCP output", &Modes.beast_out, send_beast_heartbeat, READ_MODE_BEAST_COMMAND, NULL, handleBeastCommand);
serviceListen(beast_out, Modes.net_bind_address, Modes.net_output_beast_ports);
beast_reduce_out = serviceInit("BeastReduce TCP output", &Modes.beast_reduce_out, send_beast_heartbeat, READ_MODE_IGNORE, NULL, NULL);
serviceListen(beast_reduce_out, Modes.net_bind_address, Modes.net_output_beast_reduce_ports);
vrs_out = serviceInit("VRS json output", &Modes.vrs_out, NULL, READ_MODE_IGNORE, NULL, NULL);
serviceListen(vrs_out, Modes.net_bind_address, Modes.net_output_vrs_ports);
sbs_out = serviceInit("Basestation TCP output", &Modes.sbs_out, send_sbs_heartbeat, READ_MODE_IGNORE, NULL, NULL);
serviceListen(sbs_out, Modes.net_bind_address, Modes.net_output_sbs_ports);
sbs_in = serviceInit("Basestation TCP input", NULL, NULL, READ_MODE_ASCII, "\n", decodeSbsLine);
serviceListen(sbs_in, Modes.net_bind_address, Modes.net_input_sbs_ports);
raw_in = serviceInit("Raw TCP input", NULL, NULL, READ_MODE_ASCII, "\n", decodeHexMessage);
serviceListen(raw_in, Modes.net_bind_address, Modes.net_input_raw_ports);
/* Beast input via network */
beast_in = makeBeastInputService();
serviceListen(beast_in, Modes.net_bind_address, Modes.net_input_beast_ports);
/* Beast input from local Modes-S Beast via USB */
if (Modes.sdr_type == SDR_MODESBEAST || Modes.sdr_type == SDR_GNS) {
createGenericClient(beast_in, Modes.beast_fd);
}
for (int i = 0; i < Modes.net_connectors_count; i++) {
struct net_connector *con = Modes.net_connectors[i];
if (strcmp(con->protocol, "beast_out") == 0)
con->service = beast_out;
else if (strcmp(con->protocol, "beast_in") == 0)
con->service = beast_in;
if (strcmp(con->protocol, "beast_reduce_out") == 0)
con->service = beast_reduce_out;
else if (strcmp(con->protocol, "raw_out") == 0)
con->service = raw_out;
else if (strcmp(con->protocol, "raw_in") == 0)
con->service = raw_in;
else if (strcmp(con->protocol, "vrs_out") == 0)
con->service = vrs_out;
else if (strcmp(con->protocol, "sbs_out") == 0)
con->service = sbs_out;
else if (strcmp(con->protocol, "sbs_in") == 0)
con->service = sbs_in;
con->mutex = malloc(sizeof (pthread_mutex_t));
if (!con->mutex || pthread_mutex_init(con->mutex, NULL)) {
fprintf(stderr, "Unable to initialize connector mutex!\n");
exit(1);
}
pthread_mutex_lock(con->mutex);
}
serviceReconnectCallback(now);
}
//
//=========================================================================
//
// This function gets called from time to time when the decoding thread is
// awakened by new data arriving. This usually happens a few times every second
//
static uint64_t modesAcceptClients(uint64_t now) {
int fd;
struct net_service *s;
struct client *c;
for (s = Modes.services; s; s = s->next) {
int i;
for (i = 0; i < s->listener_count; ++i) {
struct sockaddr_storage storage;
struct sockaddr *saddr = (struct sockaddr *) &storage;
socklen_t slen = sizeof (storage);
while ((fd = anetGenericAccept(Modes.aneterr, s->listener_fds[i], saddr, &slen)) >= 0) {
c = createSocketClient(s, fd);
if (c) {
// We created the client, save the sockaddr info and 'hostport'
getnameinfo(saddr, slen,
c->host, sizeof (c->host),
c->port, sizeof (c->port),
NI_NUMERICHOST | NI_NUMERICSERV);
if (anetTcpKeepAlive(Modes.aneterr, fd) != ANET_OK) {
fprintf(stderr, "%s: Unable to set keepalive on connection from %s port %s (fd %d)\n", c->service->descr, c->host, c->port, fd);
}
} else {
fprintf(stderr, "%s: Fatal: createSocketClient shouldn't fail!\n", s->descr);
exit(1);
}
}
if (errno != EMFILE && errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK) {
fprintf(stderr, "%s: Error accepting new connection: %s\n", s->descr, Modes.aneterr);
}
}
}
// temporarily stop trying to accept new clients if we are limited by file descriptors
if (errno == EMFILE) {
fprintf(stderr, "Accepting new connections suspended for 3 seconds: %s\n", Modes.aneterr);
return (now + 3000);
}
// only check for new clients not sooner than 150 ms from now
return (now + 150);
}
//
//=========================================================================
//
// On error free the client, collect the structure, adjust maxfd if needed.
//
static void modesCloseClient(struct client *c) {
if (!c->service) {
fprintf(stderr, "warning: double close of net client\n");
return;
}
if (Modes.exit == 0 && c->fd == Modes.beast_fd) {
fprintf(stderr, "Closing client: USB handle failed?\n");
Modes.exit = 3;
}
anetCloseSocket(c->fd);
c->service->connections--;
if (c->con) {
// Clean this up and set the next_reconnect timer for another try.
// If the connection had been established and the connect didn't fail,
// only wait a short time to reconnect
c->con->connecting = 0;
c->con->connected = 0;
c->con->next_reconnect = mstime() + Modes.net_connector_delay / 10;
}
// mark it as inactive and ready to be freed
c->fd = -1;
c->service = NULL;
c->modeac_requested = 0;
c->sendq_len = 0;
if (c->sendq) {
free(c->sendq);
c->sendq = NULL;
}
autoset_modeac();
}
//
// Send data to clients, if we can...
//
static void flushClient(struct client *c, uint64_t now) {
int towrite = c->sendq_len;
char *psendq = c->sendq;
int loops = 0;
int max_loops = 2;
int total_nwritten = 0;
int done = 0;
do {
int nwritten = write(c->fd, psendq, towrite);
int err = errno;
loops++;
// If we get -1, it's only fatal if it's not EAGAIN/EWOULDBLOCK
if (nwritten < 0) {
if (err != EAGAIN && err != EWOULDBLOCK) {
fprintf(stderr, "%s: Send Error: %s: %s port %s (fd %d, SendQ %d, RecvQ %d)\n",
c->service->descr, strerror(err), c->host, c->port,
c->fd, c->sendq_len, c->buflen);
modesCloseClient(c);
}
done = 1; // Blocking, just bail, try later.
} else {
if (nwritten > 0) {
// We've written something, add it to the total
total_nwritten += nwritten;
// Advance buffer
psendq += nwritten;
towrite -= nwritten;
}
if (total_nwritten == c->sendq_len) {
done = 1;
}
}
} while (!done && (loops < max_loops));
if (total_nwritten > 0) {
c->last_send = now; // If we wrote anything, update this.
if (total_nwritten == c->sendq_len) {
c->sendq_len = 0;
} else {
c->sendq_len -= total_nwritten;
memmove((void*) c->sendq, c->sendq + total_nwritten, towrite);
}
c->last_flush = now;
}
// If writing has failed for 5 seconds, disconnect.
if (c->last_flush + 5000 < now) {
fprintf(stderr, "%s: Unable to send data, disconnecting: %s port %s (fd %d, SendQ %d)\n", c->service->descr, c->host, c->port, c->fd, c->sendq_len);
modesCloseClient(c);
}
}
//
//=========================================================================
//
// Send the write buffer for the specified writer to all connected clients
//
static void flushWrites(struct net_writer *writer) {
struct client *c;
uint64_t now = mstime();
for (c = writer->service->clients; c; c = c->next) {
if (!c->service)
continue;
if (c->service->writer == writer->service->writer) {
uintptr_t psendq_end = (uintptr_t) c->sendq + c->sendq_len; // Pointer to end of sendq
// Add the buffer to the client's SendQ
if ((c->sendq_len + writer->dataUsed) >= c->sendq_max) {
// Too much data in client SendQ. Drop client - SendQ exceeded.
fprintf(stderr, "%s: Dropped due to full SendQ: %s port %s (fd %d, SendQ %d, RecvQ %d)\n",
c->service->descr, c->host, c->port,
c->fd, c->sendq_len, c->buflen);
modesCloseClient(c);
continue; // Go to the next client
}
// Append the data to the end of the queue, increment len
memcpy((void*) psendq_end, writer->data, writer->dataUsed);
c->sendq_len += writer->dataUsed;
// Try flushing...
flushClient(c, now);
}
}
writer->dataUsed = 0;
writer->lastWrite = mstime();
return;
}
// Prepare to write up to 'len' bytes to the given net_writer.
// Returns a pointer to write to, or NULL to skip this write.
static void *prepareWrite(struct net_writer *writer, int len) {
if (!writer ||
!writer->service ||
!writer->service->connections ||
!writer->data)
return NULL;
if (len > MODES_OUT_BUF_SIZE)
return NULL;
if (writer->dataUsed + len >= MODES_OUT_BUF_SIZE) {
// Flush now to free some space
flushWrites(writer);
}
return writer->data + writer->dataUsed;
}
// Complete a write previously begun by prepareWrite.
// endptr should point one byte past the last byte written
// to the buffer returned from prepareWrite.
static void completeWrite(struct net_writer *writer, void *endptr) {
writer->dataUsed = endptr - writer->data;
if (writer->dataUsed >= Modes.net_output_flush_size) {
flushWrites(writer);
}
}
//
//=========================================================================
//
// Write raw output in Beast Binary format with Timestamp to TCP clients
//
static void modesSendBeastOutput(struct modesMessage *mm, struct net_writer *writer) {
int msgLen = mm->msgbits / 8;
char *p = prepareWrite(writer, 2 + 2 * (7 + msgLen));
char ch;
int j;
int sig;
unsigned char *msg = (Modes.net_verbatim ? mm->verbatim : mm->msg);
if (!p)
return;
*p++ = 0x1a;
if (msgLen == MODES_SHORT_MSG_BYTES) {
*p++ = '2';
} else if (msgLen == MODES_LONG_MSG_BYTES) {
*p++ = '3';
} else if (msgLen == MODEAC_MSG_BYTES) {
*p++ = '1';
} else {
return;
}
/* timestamp, big-endian */
*p++ = (ch = (mm->timestampMsg >> 40));
if (0x1A == ch) {
*p++ = ch;
}
*p++ = (ch = (mm->timestampMsg >> 32));
if (0x1A == ch) {
*p++ = ch;
}
*p++ = (ch = (mm->timestampMsg >> 24));
if (0x1A == ch) {
*p++ = ch;
}
*p++ = (ch = (mm->timestampMsg >> 16));
if (0x1A == ch) {
*p++ = ch;
}
*p++ = (ch = (mm->timestampMsg >> 8));
if (0x1A == ch) {
*p++ = ch;
}
*p++ = (ch = (mm->timestampMsg));
if (0x1A == ch) {
*p++ = ch;
}
sig = round(sqrt(mm->signalLevel) * 255);
if (mm->signalLevel > 0 && sig < 1)
sig = 1;
if (sig > 255)
sig = 255;
*p++ = ch = (char) sig;
if (0x1A == ch) {
*p++ = ch;
}
for (j = 0; j < msgLen; j++) {
*p++ = (ch = msg[j]);
if (0x1A == ch) {
*p++ = ch;
}
}
completeWrite(writer, p);
}
static void send_beast_heartbeat(struct net_service *service) {
static char heartbeat_message[] = {0x1a, '1', 0, 0, 0, 0, 0, 0, 0, 0, 0};
char *data;
if (!service->writer)
return;
data = prepareWrite(service->writer, sizeof (heartbeat_message));
if (!data)
return;
memcpy(data, heartbeat_message, sizeof (heartbeat_message));
completeWrite(service->writer, data + sizeof (heartbeat_message));
}
//
//=========================================================================
//
// Print the two hex digits to a string for a single byte.
//
static void printHexDigit(char *p, unsigned char c) {
const char hex_lookup[] = "0123456789ABCDEF";
p[0] = hex_lookup[(c >> 4) & 0x0F];
p[1] = hex_lookup[c & 0x0F];
}
//
//=========================================================================
//
// Write raw output to TCP clients
//
static void modesSendRawOutput(struct modesMessage *mm) {
int msgLen = mm->msgbits / 8;
char *p = prepareWrite(&Modes.raw_out, msgLen * 2 + 15);
int j;
unsigned char *msg = (Modes.net_verbatim ? mm->verbatim : mm->msg);
if (!p)
return;
if (Modes.mlat && mm->timestampMsg) {
/* timestamp, big-endian */
sprintf(p, "@%012" PRIX64,
mm->timestampMsg);
p += 13;
} else
*p++ = '*';
for (j = 0; j < msgLen; j++) {
printHexDigit(p, msg[j]);
p += 2;
}
*p++ = ';';
*p++ = '\n';
completeWrite(&Modes.raw_out, p);
}
static void send_raw_heartbeat(struct net_service *service) {
static char *heartbeat_message = "*0000;\n";
char *data;
int len = strlen(heartbeat_message);
if (!service->writer)
return;
data = prepareWrite(service->writer, len);
if (!data)
return;
memcpy(data, heartbeat_message, len);
completeWrite(service->writer, data + len);
}
//
//=========================================================================
//
// Read SBS input from TCP clients
//
static int decodeSbsLine(struct client *c, char *line, int remote) {
struct modesMessage mm;
static struct modesMessage zeroMessage;
char *p = line;
char *t[23]; // leave 0 indexed entry empty, place 22 tokens into array
MODES_NOTUSED(remote);
MODES_NOTUSED(c);
mm = zeroMessage;
// Mark messages received over the internet as remote so that we don't try to
// pass them off as being received by this instance when forwarding them
mm.remote = 1;
mm.signalLevel = 0;
mm.sbs_in = 1;
// sample message from mlat-client basestation output
//MSG,3,1,1,4AC8B3,1,2019/12/10,19:10:46.320,2019/12/10,19:10:47.789,,36017,,,51.1001,10.1915,,,,,,
//
for (int i = 1; i < 23; i++) {
t[i] = strsep(&p, ",");
if (!p && i < 22)
return 0;
}
// check field 1
if (!t[1] || strcmp(t[1], "MSG") != 0)
return 0;
if (!t[2] || strlen(t[2]) != 1)
return 0; // decoder limited to type 3 messages for now
if (!t[5] || strlen(t[5]) != 6)
return 0; // icao must be 6 characters
char *icao = t[5];
unsigned char *chars = (unsigned char *) &(mm.addr);
for (int j = 0; j < 6; j += 2) {
int high = hexDigitVal(icao[j]);
int low = hexDigitVal(icao[j + 1]);
if (high == -1 || low == -1) return 0;
chars[2 - j / 2] = (high << 4) | low;
}
if (mm.addr == 0)
return 0;
//field 11, callsign
if (t[11] && strlen(t[11]) > 0) {
strncpy(mm.callsign, t[11], 9);
mm.callsign_valid = 1;
//fprintf(stderr, "call: %s, ", mm.callsign);
}
// field 12, altitude
if (t[12] && strlen(t[12]) > 0) {
mm.altitude_baro = atoi(t[12]);
if (mm.altitude_baro < -5000 || mm.altitude_baro > 100000)
return 0;
mm.altitude_baro_valid = 1;
mm.altitude_baro_unit = UNIT_FEET;
//fprintf(stderr, "alt: %d, ", mm.altitude_baro);
}
// field 13, groundspeed
if (t[13] && strlen(t[13]) > 0) {
mm.gs.v0 = strtod(t[13], NULL);
if (mm.gs.v0 > 0)
mm.gs_valid = 1;
//fprintf(stderr, "gs: %.1f, ", mm.gs.selected);
}
//field 14, heading
if (t[14] && strlen(t[14]) > 0) {
mm.heading_valid = 1;
mm.heading = strtod(t[14], NULL);
mm.heading_type = HEADING_GROUND_TRACK;
//fprintf(stderr, "track: %.1f, ", mm.heading);
}
// field 15 and 16, position
if (t[15] && strlen(t[15]) && t[16] && strlen(t[16])) {
mm.decoded_lat = strtod(t[15], NULL);
mm.decoded_lon = strtod(t[16], NULL);