forked from flightaware/dump1090
-
Notifications
You must be signed in to change notification settings - Fork 0
/
net_io.c
2128 lines (1798 loc) · 69.9 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 dump1090, a Mode S message decoder for RTLSDR devices.
//
// net_io.c: network handling.
//
// Copyright (c) 2014-2016 Oliver Jowett <[email protected]>
//
// This file is free software: you may copy, redistribute and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 2 of the License, or (at your
// option) 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
// permission notice:
//
// 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 "dump1090.h"
/* for PRIX64 */
#include <inttypes.h>
#include <assert.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);
static int decodeBinMessage(struct client *c, char *p);
static int decodeHexMessage(struct client *c, char *hex);
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();
//
//=========================================================================
//
// 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 (!(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->connections = 0;
service->writer = writer;
service->read_sep = sep;
service->read_mode = mode;
service->read_handler = handler;
if (service->writer) {
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;
anetNonBlock(Modes.aneterr, fd);
if (!(c = (struct client *) malloc(sizeof(*c)))) {
fprintf(stderr, "Out of memory allocating a new %s network client\n", service->descr);
exit(1);
}
c->service = service;
c->next = Modes.clients;
c->fd = fd;
c->buflen = 0;
c->modeac_requested = 0;
Modes.clients = c;
++service->connections;
if (service->writer && service->connections == 1) {
service->writer->lastWrite = mstime(); // suppress heartbeat initially
}
return c;
}
// Initiate an outgoing connection which will use the given service.
// Return the new client or NULL if the connection failed
struct client *serviceConnect(struct net_service *service, char *addr, int port)
{
int s;
char buf[20];
// Bleh.
snprintf(buf, 20, "%d", port);
s = anetTcpConnect(Modes.aneterr, addr, buf);
if (s == ANET_ERR)
return NULL;
return createSocketClient(service, s);
}
// 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) {
anetNonBlock(Modes.aneterr, newfds[i]);
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 *s;
signal(SIGPIPE, SIG_IGN);
Modes.clients = NULL;
Modes.services = NULL;
// set up listeners
s = serviceInit("Raw TCP output", &Modes.raw_out, send_raw_heartbeat, READ_MODE_IGNORE, NULL, NULL);
serviceListen(s, Modes.net_bind_address, Modes.net_output_raw_ports);
s = serviceInit("Beast TCP output", &Modes.beast_out, send_beast_heartbeat, READ_MODE_BEAST_COMMAND, NULL, handleBeastCommand);
serviceListen(s, Modes.net_bind_address, Modes.net_output_beast_ports);
s = serviceInit("Basestation TCP output", &Modes.sbs_out, send_sbs_heartbeat, READ_MODE_IGNORE, NULL, NULL);
serviceListen(s, Modes.net_bind_address, Modes.net_output_sbs_ports);
s = serviceInit("Raw TCP input", NULL, NULL, READ_MODE_ASCII, "\n", decodeHexMessage);
serviceListen(s, Modes.net_bind_address, Modes.net_input_raw_ports);
s = makeBeastInputService();
serviceListen(s, Modes.net_bind_address, Modes.net_input_beast_ports);
}
//
//=========================================================================
//
// 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 struct client * modesAcceptClients(void) {
int fd;
struct net_service *s;
for (s = Modes.services; s; s = s->next) {
int i;
for (i = 0; i < s->listener_count; ++i) {
while ((fd = anetTcpAccept(Modes.aneterr, s->listener_fds[i])) >= 0) {
createSocketClient(s, fd);
}
}
}
return Modes.clients;
}
//
//=========================================================================
//
// 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;
}
// Clean up, but defer removing from the list until modesNetCleanup().
// This is because there may be stackframes still pointing at this
// client (unpredictably: reading from client A may cause client B to
// be freed)
close(c->fd);
c->service->connections--;
// mark it as inactive and ready to be freed
c->fd = -1;
c->service = NULL;
c->modeac_requested = 0;
autoset_modeac();
}
//
//=========================================================================
//
// Send the write buffer for the specified writer to all connected clients
//
static void flushWrites(struct net_writer *writer) {
struct client *c;
for (c = Modes.clients; c; c = c->next) {
if (!c->service)
continue;
if (c->service == writer->service) {
#ifndef _WIN32
int nwritten = write(c->fd, writer->data, writer->dataUsed);
#else
int nwritten = send(c->fd, writer->data, writer->dataUsed, 0 );
#endif
if (nwritten != writer->dataUsed) {
modesCloseClient(c);
}
}
}
writer->dataUsed = 0;
writer->lastWrite = mstime();
}
// 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) {
int msgLen = mm->msgbits / 8;
char *p = prepareWrite(&Modes.beast_out, 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(&Modes.beast_out, 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));
}
//
//=========================================================================
//
// 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++) {
sprintf(p, "%02X", 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);
}
//
//=========================================================================
//
// Write SBS output to TCP clients
//
static void modesSendSBSOutput(struct modesMessage *mm, struct aircraft *a) {
char *p;
struct timespec now;
struct tm stTime_receive, stTime_now;
int msgType;
// For now, suppress non-ICAO addresses
if (mm->addr & MODES_NON_ICAO_ADDRESS)
return;
p = prepareWrite(&Modes.sbs_out, 200);
if (!p)
return;
//
// SBS BS style output checked against the following reference
// http://www.homepages.mcb.net/bones/SBS/Article/Barebones42_Socket_Data.htm - seems comprehensive
//
// Decide on the basic SBS Message Type
switch (mm->msgtype) {
case 4:
case 20:
msgType = 5;
break;
break;
case 5:
case 21:
msgType = 6;
break;
case 0:
case 16:
msgType = 7;
break;
case 11:
msgType = 8;
break;
case 17:
case 18:
if (mm->metype >= 1 && mm->metype <= 4) {
msgType = 1;
} else if (mm->metype >= 5 && mm->metype <= 8) {
msgType = 2;
} else if (mm->metype >= 9 && mm->metype <= 18) {
msgType = 3;
} else if (mm->metype == 19) {
msgType = 4;
} else {
return;
}
break;
default:
return;
}
// Fields 1 to 6 : SBS message type and ICAO address of the aircraft and some other stuff
p += sprintf(p, "MSG,%d,1,1,%06X,1,", msgType, mm->addr);
// Find current system time
clock_gettime(CLOCK_REALTIME, &now);
localtime_r(&now.tv_sec, &stTime_now);
// Find message reception time
localtime_r(&mm->sysTimestampMsg.tv_sec, &stTime_receive);
// Fields 7 & 8 are the message reception time and date
p += sprintf(p, "%04d/%02d/%02d,", (stTime_receive.tm_year+1900),(stTime_receive.tm_mon+1), stTime_receive.tm_mday);
p += sprintf(p, "%02d:%02d:%02d.%03u,", stTime_receive.tm_hour, stTime_receive.tm_min, stTime_receive.tm_sec, (unsigned) (mm->sysTimestampMsg.tv_nsec / 1000000U));
// Fields 9 & 10 are the current time and date
p += sprintf(p, "%04d/%02d/%02d,", (stTime_now.tm_year+1900),(stTime_now.tm_mon+1), stTime_now.tm_mday);
p += sprintf(p, "%02d:%02d:%02d.%03u", stTime_now.tm_hour, stTime_now.tm_min, stTime_now.tm_sec, (unsigned) (now.tv_nsec / 1000000U));
// Field 11 is the callsign (if we have it)
if (mm->callsign_valid) {p += sprintf(p, ",%s", mm->callsign);}
else {p += sprintf(p, ",");}
// Field 12 is the altitude (if we have it)
if (mm->altitude_valid) {
if (Modes.use_gnss) {
if (mm->altitude_source == ALTITUDE_GNSS) {
p += sprintf(p, ",%dH", mm->altitude);
} else if (trackDataValid(&a->gnss_delta_valid)) {
p += sprintf(p, ",%dH", mm->altitude + a->gnss_delta);
} else {
p += sprintf(p, ",%d", mm->altitude);
}
} else {
if (mm->altitude_source == ALTITUDE_BARO) {
p += sprintf(p, ",%d", mm->altitude);
} else if (trackDataValid(&a->gnss_delta_valid)) {
p += sprintf(p, ",%d", mm->altitude - a->gnss_delta);
} else {
p += sprintf(p, ",");
}
}
} else {
p += sprintf(p, ",");
}
// Field 13 is the ground Speed (if we have it)
if (mm->speed_valid && mm->speed_source == SPEED_GROUNDSPEED) {
p += sprintf(p, ",%d", mm->speed);
} else {
p += sprintf(p, ",");
}
// Field 14 is the ground Heading (if we have it)
if (mm->heading_valid && mm->heading_source == HEADING_TRUE) {
p += sprintf(p, ",%d", mm->heading);
} else {
p += sprintf(p, ",");
}
// Fields 15 and 16 are the Lat/Lon (if we have it)
if (mm->cpr_decoded) {
p += sprintf(p, ",%1.5f,%1.5f", mm->decoded_lat, mm->decoded_lon);
} else {
p += sprintf(p, ",,");
}
// Field 17 is the VerticalRate (if we have it)
if (mm->vert_rate_valid) {
p += sprintf(p, ",%d", mm->vert_rate);
} else {
p += sprintf(p, ",");
}
// Field 18 is the Squawk (if we have it)
if (mm->squawk_valid) {
p += sprintf(p, ",%04x", mm->squawk);
} else {
p += sprintf(p, ",");
}
// Field 19 is the Squawk Changing Alert flag (if we have it)
if (mm->alert_valid) {
if (mm->alert) {
p += sprintf(p, ",-1");
} else {
p += sprintf(p, ",0");
}
} else {
p += sprintf(p, ",");
}
// Field 20 is the Squawk Emergency flag (if we have it)
if (mm->squawk_valid) {
if ((mm->squawk == 0x7500) || (mm->squawk == 0x7600) || (mm->squawk == 0x7700)) {
p += sprintf(p, ",-1");
} else {
p += sprintf(p, ",0");
}
} else {
p += sprintf(p, ",");
}
// Field 21 is the Squawk Ident flag (if we have it)
if (mm->spi_valid) {
if (mm->spi) {
p += sprintf(p, ",-1");
} else {
p += sprintf(p, ",0");
}
} else {
p += sprintf(p, ",");
}
// Field 22 is the OnTheGround flag (if we have it)
switch (mm->airground) {
case AG_GROUND:
p += sprintf(p, ",-1");
break;
case AG_AIRBORNE:
p += sprintf(p, ",0");
break;
default:
p += sprintf(p, ",");
break;
}
p += sprintf(p, "\r\n");
completeWrite(&Modes.sbs_out, p);
}
static void send_sbs_heartbeat(struct net_service *service)
{
static char *heartbeat_message = "\r\n"; // is there a better one?
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);
}
//
//=========================================================================
//
void modesQueueOutput(struct modesMessage *mm, struct aircraft *a) {
int is_mlat = (mm->source == SOURCE_MLAT);
if (a && !is_mlat && mm->correctedbits < 2) {
// Don't ever forward 2-bit-corrected messages via SBS output.
// Don't ever forward mlat messages via SBS output.
modesSendSBSOutput(mm, a);
}
if (!is_mlat && (Modes.net_verbatim || mm->correctedbits < 2)) {
// Forward 2-bit-corrected messages via raw output only if --net-verbatim is set
// Don't ever forward mlat messages via raw output.
modesSendRawOutput(mm);
}
if ((!is_mlat || Modes.forward_mlat) && (Modes.net_verbatim || mm->correctedbits < 2)) {
// Forward 2-bit-corrected messages via beast output only if --net-verbatim is set
// Forward mlat messages via beast output only if --forward-mlat is set
modesSendBeastOutput(mm);
}
if (a && !is_mlat) {
writeFATSVEvent(mm, a);
}
}
// Decode a little-endian IEEE754 float (binary32)
float ieee754_binary32_le_to_float(uint8_t *data)
{
double sign = (data[3] & 0x80) ? -1.0 : 1.0;
int16_t raw_exponent = ((data[3] & 0x7f) << 1) | ((data[2] & 0x80) >> 7);
uint32_t raw_significand = ((data[2] & 0x7f) << 16) | (data[1] << 8) | data[0];
if (raw_exponent == 0) {
if (raw_significand == 0) {
/* -0 is treated like +0 */
return 0;
} else {
/* denormal */
return ldexp(sign * raw_significand, -126 - 23);
}
}
if (raw_exponent == 255) {
if (raw_significand == 0) {
/* +/-infinity */
return sign < 0 ? -INFINITY : INFINITY;
} else {
/* NaN */
#ifdef NAN
return NAN;
#else
return 0.0f;
#endif
}
}
/* normalized value */
return ldexp(sign * ((1 << 23) | raw_significand), raw_exponent - 127 - 23);
}
static void handle_radarcape_position(float lat, float lon, float alt)
{
if (!isfinite(lat) || lat < -90 || lat > 90 || !isfinite(lon) || lon < -180 || lon > 180 || !isfinite(alt))
return;
writeFATSVPositionUpdate(lat, lon, alt);
if (!(Modes.bUserFlags & MODES_USER_LATLON_VALID)) {
Modes.fUserLat = lat;
Modes.fUserLon = lon;
Modes.bUserFlags |= MODES_USER_LATLON_VALID;
receiverPositionChanged(lat, lon, alt);
}
}
// recompute global Mode A/C setting
static void autoset_modeac() {
struct client *c;
if (!Modes.mode_ac_auto)
return;
Modes.mode_ac = 0;
for (c = Modes.clients; c; c = c->next) {
if (c->modeac_requested) {
Modes.mode_ac = 1;
break;
}
}
}
// Send some Beast settings commands to a client
void sendBeastSettings(struct client *c, const char *settings)
{
int len;
char *buf, *p;
len = strlen(settings) * 3;
buf = p = alloca(len);
while (*settings) {
*p++ = 0x1a;
*p++ = '1';
*p++ = *settings++;
}
anetWrite(c->fd, buf, len);
}
//
// Handle a Beast command message.
// Currently, we just look for the Mode A/C command message
// and ignore everything else.
//
static int handleBeastCommand(struct client *c, char *p) {
if (p[0] != '1') {
// huh?
return 0;
}
switch (p[1]) {
case 'j':
c->modeac_requested = 0;
break;
case 'J':
c->modeac_requested = 1;
break;
}
autoset_modeac();
return 0;
}
//
//=========================================================================
//
// This function decodes a Beast binary format message
//
// The message is passed to the higher level layers, so it feeds
// the selected screen output, the network output and so forth.
//
// If the message looks invalid it is silently discarded.
//
// The function always returns 0 (success) to the caller as there is no
// case where we want broken messages here to close the client connection.
//
static int decodeBinMessage(struct client *c, char *p) {
int msgLen = 0;
int j;
char ch;
unsigned char msg[MODES_LONG_MSG_BYTES + 7];
static struct modesMessage zeroMessage;
struct modesMessage mm;
MODES_NOTUSED(c);
memset(&mm, 0, sizeof(mm));
ch = *p++; /// Get the message type
if (ch == '1' && Modes.mode_ac) {
msgLen = MODEAC_MSG_BYTES;
} else if (ch == '2') {
msgLen = MODES_SHORT_MSG_BYTES;
} else if (ch == '3') {
msgLen = MODES_LONG_MSG_BYTES;
} else if (ch == '5') {
// Special case for Radarcape position messages.
float lat, lon, alt;
for (j = 0; j < 21; j++) { // and the data
msg[j] = ch = *p++;
if (0x1A == ch) {p++;}
}
lat = ieee754_binary32_le_to_float(msg + 4);
lon = ieee754_binary32_le_to_float(msg + 8);
alt = ieee754_binary32_le_to_float(msg + 12);
handle_radarcape_position(lat, lon, alt);
} else {
// Ignore this.
return 0;
}
if (msgLen) {
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;
// Grab the timestamp (big endian format)
mm.timestampMsg = 0;
for (j = 0; j < 6; j++) {
ch = *p++;
mm.timestampMsg = mm.timestampMsg << 8 | (ch & 255);
if (0x1A == ch) {p++;}
}
// record reception time as the time we read it.
clock_gettime(CLOCK_REALTIME, &mm.sysTimestampMsg);
ch = *p++; // Grab the signal level
mm.signalLevel = ((unsigned char)ch / 255.0);
mm.signalLevel = mm.signalLevel * mm.signalLevel;
if (0x1A == ch) {p++;}
for (j = 0; j < msgLen; j++) { // and the data
msg[j] = ch = *p++;
if (0x1A == ch) {p++;}
}
if (msgLen == MODEAC_MSG_BYTES) { // ModeA or ModeC
Modes.stats_current.remote_received_modeac++;
decodeModeAMessage(&mm, ((msg[0] << 8) | msg[1]));
} else {
int result;
Modes.stats_current.remote_received_modes++;
result = decodeModesMessage(&mm, msg);
if (result < 0) {
if (result == -1)
Modes.stats_current.remote_rejected_unknown_icao++;
else
Modes.stats_current.remote_rejected_bad++;
return 0;
} else {
Modes.stats_current.remote_accepted[mm.correctedbits]++;
}
}
useModesMessage(&mm);
}
return (0);
}
//
//=========================================================================
//
// Turn an hex digit into its 4 bit decimal value.
// Returns -1 if the digit is not in the 0-F range.
//
static int hexDigitVal(int c) {
c = tolower(c);
if (c >= '0' && c <= '9') return c-'0';
else if (c >= 'a' && c <= 'f') return c-'a'+10;
else return -1;
}
//
//=========================================================================
//
// This function decodes a string representing message in raw hex format
// like: *8D4B969699155600E87406F5B69F; The string is null-terminated.
//
// The message is passed to the higher level layers, so it feeds
// the selected screen output, the network output and so forth.
//
// If the message looks invalid it is silently discarded.
//
// The function always returns 0 (success) to the caller as there is no
// case where we want broken messages here to close the client connection.
//
static int decodeHexMessage(struct client *c, char *hex) {
int l = strlen(hex), j;
unsigned char msg[MODES_LONG_MSG_BYTES];
struct modesMessage mm;
static struct modesMessage zeroMessage;
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;
// Remove spaces on the left and on the right
while(l && isspace(hex[l-1])) {
hex[l-1] = '\0'; l--;
}
while(isspace(*hex)) {
hex++; l--;
}
// Turn the message into binary.
// Accept *-AVR raw @-AVR/BEAST timeS+raw %-AVR timeS+raw (CRC good) <-BEAST timeS+sigL+raw
// and some AVR records that we can understand
if (hex[l-1] != ';') {return (0);} // not complete - abort
switch(hex[0]) {
case '<': {