-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
dump1090.c
2665 lines (2397 loc) · 97.4 KB
/
dump1090.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
/* Mode1090, a Mode S messages decoder for RTLSDR devices.
*
* 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 <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <stdint.h>
#include <errno.h>
#include <unistd.h>
#include <math.h>
#include <sys/time.h>
#include <signal.h>
#include <fcntl.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include "rtl-sdr.h"
#include "anet.h"
#define MODES_DEFAULT_RATE 2000000
#define MODES_DEFAULT_FREQ 1090000000
#define MODES_DEFAULT_WIDTH 1000
#define MODES_DEFAULT_HEIGHT 700
#define MODES_ASYNC_BUF_NUMBER 12
#define MODES_DATA_LEN (16*16384) /* 256k */
#define MODES_AUTO_GAIN -100 /* Use automatic gain. */
#define MODES_MAX_GAIN 999999 /* Use max available gain. */
#define MODES_PREAMBLE_US 8 /* microseconds */
#define MODES_LONG_MSG_BITS 112
#define MODES_SHORT_MSG_BITS 56
#define MODES_FULL_LEN (MODES_PREAMBLE_US+MODES_LONG_MSG_BITS)
#define MODES_LONG_MSG_BYTES (112/8)
#define MODES_SHORT_MSG_BYTES (56/8)
#define MODES_ICAO_CACHE_LEN 1024 /* Power of two required. */
#define MODES_ICAO_CACHE_TTL 60 /* Time to live of cached addresses. */
#define MODES_UNIT_FEET 0
#define MODES_UNIT_METERS 1
#define MODES_DEBUG_DEMOD (1<<0)
#define MODES_DEBUG_DEMODERR (1<<1)
#define MODES_DEBUG_BADCRC (1<<2)
#define MODES_DEBUG_GOODCRC (1<<3)
#define MODES_DEBUG_NOPREAMBLE (1<<4)
#define MODES_DEBUG_NET (1<<5)
#define MODES_DEBUG_JS (1<<6)
/* When debug is set to MODES_DEBUG_NOPREAMBLE, the first sample must be
* at least greater than a given level for us to dump the signal. */
#define MODES_DEBUG_NOPREAMBLE_LEVEL 25
#define MODES_INTERACTIVE_REFRESH_TIME 250 /* Milliseconds */
#define MODES_INTERACTIVE_ROWS 15 /* Rows on screen */
#define MODES_INTERACTIVE_TTL 60 /* TTL before being removed */
#define MODES_NET_MAX_FD 1024
#define MODES_NET_OUTPUT_SBS_PORT 30003
#define MODES_NET_OUTPUT_RAW_PORT 30002
#define MODES_NET_INPUT_RAW_PORT 30001
#define MODES_NET_HTTP_PORT 8080
#define MODES_CLIENT_BUF_SIZE 1024
#define MODES_NET_SNDBUF_SIZE (1024*64)
#define MODES_NOTUSED(V) ((void) V)
/* Structure used to describe a networking client. */
struct client {
int fd; /* File descriptor. */
int service; /* TCP port the client is connected to. */
char buf[MODES_CLIENT_BUF_SIZE+1]; /* Read buffer. */
int buflen; /* Amount of data on buffer. */
};
/* Structure used to describe an aircraft in iteractive mode. */
struct aircraft {
uint32_t addr; /* ICAO address */
char hexaddr[7]; /* Printable ICAO address */
char flight[9]; /* Flight number */
int altitude; /* Altitude */
int speed; /* Velocity computed from EW and NS components. */
int track; /* Angle of flight. */
time_t seen; /* Time at which the last packet was received. */
long messages; /* Number of Mode S messages received. */
/* Encoded latitude and longitude as extracted by odd and even
* CPR encoded messages. */
int odd_cprlat;
int odd_cprlon;
int even_cprlat;
int even_cprlon;
double lat, lon; /* Coordinated obtained from CPR encoded data. */
long long odd_cprtime, even_cprtime;
struct aircraft *next; /* Next aircraft in our linked list. */
};
/* Program global state. */
struct {
/* Internal state */
pthread_t reader_thread;
pthread_mutex_t data_mutex; /* Mutex to synchronize buffer access. */
pthread_cond_t data_cond; /* Conditional variable associated. */
unsigned char *data; /* Raw IQ samples buffer */
uint16_t *magnitude; /* Magnitude vector */
uint32_t data_len; /* Buffer length. */
int fd; /* --ifile option file descriptor. */
int data_ready; /* Data ready to be processed. */
uint32_t *icao_cache; /* Recently seen ICAO addresses cache. */
uint16_t *maglut; /* I/Q -> Magnitude lookup table. */
int exit; /* Exit from the main loop when true. */
/* RTLSDR */
int dev_index;
int gain;
int enable_agc;
rtlsdr_dev_t *dev;
int freq;
/* Networking */
char aneterr[ANET_ERR_LEN];
struct client *clients[MODES_NET_MAX_FD]; /* Our clients. */
int maxfd; /* Greatest fd currently active. */
int sbsos; /* SBS output listening socket. */
int ros; /* Raw output listening socket. */
int ris; /* Raw input listening socket. */
int https; /* HTTP listening socket. */
/* Configuration */
char *filename; /* Input form file, --ifile option. */
int loop; /* Read input file again and again. */
int fix_errors; /* Single bit error correction if true. */
int check_crc; /* Only display messages with good CRC. */
int raw; /* Raw output format. */
int debug; /* Debugging mode. */
int net; /* Enable networking. */
int net_only; /* Enable just networking. */
int interactive; /* Interactive mode */
int interactive_rows; /* Interactive mode: max number of rows. */
int interactive_ttl; /* Interactive mode: TTL before deletion. */
int stats; /* Print stats at exit in --ifile mode. */
int onlyaddr; /* Print only ICAO addresses. */
int metric; /* Use metric units. */
int aggressive; /* Aggressive detection algorithm. */
/* Interactive mode */
struct aircraft *aircrafts;
long long interactive_last_update; /* Last screen update in milliseconds */
/* Statistics */
long long stat_valid_preamble;
long long stat_demodulated;
long long stat_goodcrc;
long long stat_badcrc;
long long stat_fixed;
long long stat_single_bit_fix;
long long stat_two_bits_fix;
long long stat_http_requests;
long long stat_sbs_connections;
long long stat_out_of_phase;
} Modes;
/* The struct we use to store information about a decoded message. */
struct modesMessage {
/* Generic fields */
unsigned char msg[MODES_LONG_MSG_BYTES]; /* Binary message. */
int msgbits; /* Number of bits in message */
int msgtype; /* Downlink format # */
int crcok; /* True if CRC was valid */
uint32_t crc; /* Message CRC */
int errorbit; /* Bit corrected. -1 if no bit corrected. */
int aa1, aa2, aa3; /* ICAO Address bytes 1 2 and 3 */
int phase_corrected; /* True if phase correction was applied. */
/* DF 11 */
int ca; /* Responder capabilities. */
/* DF 17 */
int metype; /* Extended squitter message type. */
int mesub; /* Extended squitter message subtype. */
int heading_is_valid;
int heading;
int aircraft_type;
int fflag; /* 1 = Odd, 0 = Even CPR message. */
int tflag; /* UTC synchronized? */
int raw_latitude; /* Non decoded latitude */
int raw_longitude; /* Non decoded longitude */
char flight[9]; /* 8 chars flight number. */
int ew_dir; /* 0 = East, 1 = West. */
int ew_velocity; /* E/W velocity. */
int ns_dir; /* 0 = North, 1 = South. */
int ns_velocity; /* N/S velocity. */
int vert_rate_source; /* Vertical rate source. */
int vert_rate_sign; /* Vertical rate sign. */
int vert_rate; /* Vertical rate. */
int velocity; /* Computed from EW and NS velocity. */
/* DF4, DF5, DF20, DF21 */
int fs; /* Flight status for DF4,5,20,21 */
int dr; /* Request extraction of downlink request. */
int um; /* Request extraction of downlink request. */
int identity; /* 13 bits identity (Squawk). */
/* Fields used by multiple message types. */
int altitude, unit;
};
void interactiveShowData(void);
struct aircraft* interactiveReceiveData(struct modesMessage *mm);
void modesSendRawOutput(struct modesMessage *mm);
void modesSendSBSOutput(struct modesMessage *mm, struct aircraft *a);
void useModesMessage(struct modesMessage *mm);
int fixSingleBitErrors(unsigned char *msg, int bits);
int fixTwoBitsErrors(unsigned char *msg, int bits);
int modesMessageLenByType(int type);
void sigWinchCallback();
int getTermRows();
/* ============================= Utility functions ========================== */
static long long mstime(void) {
struct timeval tv;
long long mst;
gettimeofday(&tv, NULL);
mst = ((long long)tv.tv_sec)*1000;
mst += tv.tv_usec/1000;
return mst;
}
/* =============================== Initialization =========================== */
void modesInitConfig(void) {
Modes.gain = MODES_MAX_GAIN;
Modes.dev_index = 0;
Modes.enable_agc = 0;
Modes.freq = MODES_DEFAULT_FREQ;
Modes.filename = NULL;
Modes.fix_errors = 1;
Modes.check_crc = 1;
Modes.raw = 0;
Modes.net = 0;
Modes.net_only = 0;
Modes.onlyaddr = 0;
Modes.debug = 0;
Modes.interactive = 0;
Modes.interactive_rows = MODES_INTERACTIVE_ROWS;
Modes.interactive_ttl = MODES_INTERACTIVE_TTL;
Modes.aggressive = 0;
Modes.interactive_rows = getTermRows();
Modes.loop = 0;
}
void modesInit(void) {
int i, q;
pthread_mutex_init(&Modes.data_mutex,NULL);
pthread_cond_init(&Modes.data_cond,NULL);
/* We add a full message minus a final bit to the length, so that we
* can carry the remaining part of the buffer that we can't process
* in the message detection loop, back at the start of the next data
* to process. This way we are able to also detect messages crossing
* two reads. */
Modes.data_len = MODES_DATA_LEN + (MODES_FULL_LEN-1)*4;
Modes.data_ready = 0;
/* Allocate the ICAO address cache. We use two uint32_t for every
* entry because it's a addr / timestamp pair for every entry. */
Modes.icao_cache = malloc(sizeof(uint32_t)*MODES_ICAO_CACHE_LEN*2);
memset(Modes.icao_cache,0,sizeof(uint32_t)*MODES_ICAO_CACHE_LEN*2);
Modes.aircrafts = NULL;
Modes.interactive_last_update = 0;
if ((Modes.data = malloc(Modes.data_len)) == NULL ||
(Modes.magnitude = malloc(Modes.data_len*2)) == NULL) {
fprintf(stderr, "Out of memory allocating data buffer.\n");
exit(1);
}
memset(Modes.data,127,Modes.data_len);
/* Populate the I/Q -> Magnitude lookup table. It is used because
* sqrt or round may be expensive and performance may vary a lot
* depending on the libc used.
*
* Note that we don't need to fill the table for negative values, as
* we square both i and q to take the magnitude. So the maximum absolute
* value of i and q is 128, thus the maximum magnitude we get is:
*
* sqrt(128*128+128*128) = ~181.02
*
* Then, to retain the full resolution and be able to distinguish among
* every pair of I/Q values, we scale this range from the float range
* 0-181 to the uint16_t range of 0-65536 by multiplying for 360. */
Modes.maglut = malloc(129*129*2);
for (i = 0; i <= 128; i++) {
for (q = 0; q <= 128; q++) {
Modes.maglut[i*129+q] = round(sqrt(i*i+q*q)*360);
}
}
/* Statistics */
Modes.stat_valid_preamble = 0;
Modes.stat_demodulated = 0;
Modes.stat_goodcrc = 0;
Modes.stat_badcrc = 0;
Modes.stat_fixed = 0;
Modes.stat_single_bit_fix = 0;
Modes.stat_two_bits_fix = 0;
Modes.stat_http_requests = 0;
Modes.stat_sbs_connections = 0;
Modes.stat_out_of_phase = 0;
Modes.exit = 0;
}
/* =============================== RTLSDR handling ========================== */
void modesInitRTLSDR(void) {
int j;
int device_count;
int ppm_error = 0;
char vendor[256], product[256], serial[256];
device_count = rtlsdr_get_device_count();
if (!device_count) {
fprintf(stderr, "No supported RTLSDR devices found.\n");
exit(1);
}
fprintf(stderr, "Found %d device(s):\n", device_count);
for (j = 0; j < device_count; j++) {
rtlsdr_get_device_usb_strings(j, vendor, product, serial);
fprintf(stderr, "%d: %s, %s, SN: %s %s\n", j, vendor, product, serial,
(j == Modes.dev_index) ? "(currently selected)" : "");
}
if (rtlsdr_open(&Modes.dev, Modes.dev_index) < 0) {
fprintf(stderr, "Error opening the RTLSDR device: %s\n",
strerror(errno));
exit(1);
}
/* Set gain, frequency, sample rate, and reset the device. */
rtlsdr_set_tuner_gain_mode(Modes.dev,
(Modes.gain == MODES_AUTO_GAIN) ? 0 : 1);
if (Modes.gain != MODES_AUTO_GAIN) {
if (Modes.gain == MODES_MAX_GAIN) {
/* Find the maximum gain available. */
int numgains;
int gains[100];
numgains = rtlsdr_get_tuner_gains(Modes.dev, gains);
Modes.gain = gains[numgains-1];
fprintf(stderr, "Max available gain is: %.2f\n", Modes.gain/10.0);
}
rtlsdr_set_tuner_gain(Modes.dev, Modes.gain);
fprintf(stderr, "Setting gain to: %.2f\n", Modes.gain/10.0);
} else {
fprintf(stderr, "Using automatic gain control.\n");
}
rtlsdr_set_freq_correction(Modes.dev, ppm_error);
if (Modes.enable_agc) rtlsdr_set_agc_mode(Modes.dev, 1);
rtlsdr_set_center_freq(Modes.dev, Modes.freq);
rtlsdr_set_sample_rate(Modes.dev, MODES_DEFAULT_RATE);
rtlsdr_reset_buffer(Modes.dev);
fprintf(stderr, "Gain reported by device: %.2f\n",
rtlsdr_get_tuner_gain(Modes.dev)/10.0);
}
/* We use a thread reading data in background, while the main thread
* handles decoding and visualization of data to the user.
*
* The reading thread calls the RTLSDR API to read data asynchronously, and
* uses a callback to populate the data buffer.
* A Mutex is used to avoid races with the decoding thread. */
void rtlsdrCallback(unsigned char *buf, uint32_t len, void *ctx) {
MODES_NOTUSED(ctx);
pthread_mutex_lock(&Modes.data_mutex);
if (len > MODES_DATA_LEN) len = MODES_DATA_LEN;
/* Move the last part of the previous buffer, that was not processed,
* on the start of the new buffer. */
memcpy(Modes.data, Modes.data+MODES_DATA_LEN, (MODES_FULL_LEN-1)*4);
/* Read the new data. */
memcpy(Modes.data+(MODES_FULL_LEN-1)*4, buf, len);
Modes.data_ready = 1;
/* Signal to the other thread that new data is ready */
pthread_cond_signal(&Modes.data_cond);
pthread_mutex_unlock(&Modes.data_mutex);
}
/* This is used when --ifile is specified in order to read data from file
* instead of using an RTLSDR device. */
void readDataFromFile(void) {
pthread_mutex_lock(&Modes.data_mutex);
while(1) {
ssize_t nread, toread;
unsigned char *p;
if (Modes.data_ready) {
pthread_cond_wait(&Modes.data_cond,&Modes.data_mutex);
continue;
}
if (Modes.interactive) {
/* When --ifile and --interactive are used together, slow down
* playing at the natural rate of the RTLSDR received. */
pthread_mutex_unlock(&Modes.data_mutex);
usleep(5000);
pthread_mutex_lock(&Modes.data_mutex);
}
/* Move the last part of the previous buffer, that was not processed,
* on the start of the new buffer. */
memcpy(Modes.data, Modes.data+MODES_DATA_LEN, (MODES_FULL_LEN-1)*4);
toread = MODES_DATA_LEN;
p = Modes.data+(MODES_FULL_LEN-1)*4;
while(toread) {
nread = read(Modes.fd, p, toread);
/* In --file mode, seek the file again from the start
* and re-play it if --loop was given. */
if (nread == 0 &&
Modes.filename != NULL &&
Modes.fd != STDIN_FILENO &&
Modes.loop)
{
if (lseek(Modes.fd,0,SEEK_SET) != -1) continue;
}
if (nread <= 0) {
Modes.exit = 1; /* Signal the other thread to exit. */
break;
}
p += nread;
toread -= nread;
}
if (toread) {
/* Not enough data on file to fill the buffer? Pad with
* no signal. */
memset(p,127,toread);
}
Modes.data_ready = 1;
/* Signal to the other thread that new data is ready */
pthread_cond_signal(&Modes.data_cond);
}
}
/* We read data using a thread, so the main thread only handles decoding
* without caring about data acquisition. */
void *readerThreadEntryPoint(void *arg) {
MODES_NOTUSED(arg);
if (Modes.filename == NULL) {
rtlsdr_read_async(Modes.dev, rtlsdrCallback, NULL,
MODES_ASYNC_BUF_NUMBER,
MODES_DATA_LEN);
} else {
readDataFromFile();
}
return NULL;
}
/* ============================== Debugging ================================= */
/* Helper function for dumpMagnitudeVector().
* It prints a single bar used to display raw signals.
*
* Since every magnitude sample is between 0-255, the function uses
* up to 63 characters for every bar. Every character represents
* a length of 4, 3, 2, 1, specifically:
*
* "O" is 4
* "o" is 3
* "-" is 2
* "." is 1
*/
void dumpMagnitudeBar(int index, int magnitude) {
char *set = " .-o";
char buf[256];
int div = magnitude / 256 / 4;
int rem = magnitude / 256 % 4;
memset(buf,'O',div);
buf[div] = set[rem];
buf[div+1] = '\0';
if (index >= 0) {
int markchar = ']';
/* preamble peaks are marked with ">" */
if (index == 0 || index == 2 || index == 7 || index == 9)
markchar = '>';
/* Data peaks are marked to distinguish pairs of bits. */
if (index >= 16) markchar = ((index-16)/2 & 1) ? '|' : ')';
printf("[%.3d%c |%-66s %d\n", index, markchar, buf, magnitude);
} else {
printf("[%.2d] |%-66s %d\n", index, buf, magnitude);
}
}
/* Display an ASCII-art alike graphical representation of the undecoded
* message as a magnitude signal.
*
* The message starts at the specified offset in the "m" buffer.
* The function will display enough data to cover a short 56 bit message.
*
* If possible a few samples before the start of the messsage are included
* for context. */
void dumpMagnitudeVector(uint16_t *m, uint32_t offset) {
uint32_t padding = 5; /* Show a few samples before the actual start. */
uint32_t start = (offset < padding) ? 0 : offset-padding;
uint32_t end = offset + (MODES_PREAMBLE_US*2)+(MODES_SHORT_MSG_BITS*2) - 1;
uint32_t j;
for (j = start; j <= end; j++) {
dumpMagnitudeBar(j-offset, m[j]);
}
}
/* Produce a raw representation of the message as a Javascript file
* loadable by debug.html. */
void dumpRawMessageJS(char *descr, unsigned char *msg,
uint16_t *m, uint32_t offset, int fixable)
{
int padding = 5; /* Show a few samples before the actual start. */
int start = offset - padding;
int end = offset + (MODES_PREAMBLE_US*2)+(MODES_LONG_MSG_BITS*2) - 1;
FILE *fp;
int j, fix1 = -1, fix2 = -1;
if (fixable != -1) {
fix1 = fixable & 0xff;
if (fixable > 255) fix2 = fixable >> 8;
}
if ((fp = fopen("frames.js","a")) == NULL) {
fprintf(stderr, "Error opening frames.js: %s\n", strerror(errno));
exit(1);
}
fprintf(fp,"frames.push({\"descr\": \"%s\", \"mag\": [", descr);
for (j = start; j <= end; j++) {
fprintf(fp,"%d", j < 0 ? 0 : m[j]);
if (j != end) fprintf(fp,",");
}
fprintf(fp,"], \"fix1\": %d, \"fix2\": %d, \"bits\": %d, \"hex\": \"",
fix1, fix2, modesMessageLenByType(msg[0]>>3));
for (j = 0; j < MODES_LONG_MSG_BYTES; j++)
fprintf(fp,"\\x%02x",msg[j]);
fprintf(fp,"\"});\n");
fclose(fp);
}
/* This is a wrapper for dumpMagnitudeVector() that also show the message
* in hex format with an additional description.
*
* descr is the additional message to show to describe the dump.
* msg points to the decoded message
* m is the original magnitude vector
* offset is the offset where the message starts
*
* The function also produces the Javascript file used by debug.html to
* display packets in a graphical format if the Javascript output was
* enabled.
*/
void dumpRawMessage(char *descr, unsigned char *msg,
uint16_t *m, uint32_t offset)
{
int j;
int msgtype = msg[0]>>3;
int fixable = -1;
if (msgtype == 11 || msgtype == 17) {
int msgbits = (msgtype == 11) ? MODES_SHORT_MSG_BITS :
MODES_LONG_MSG_BITS;
fixable = fixSingleBitErrors(msg,msgbits);
if (fixable == -1)
fixable = fixTwoBitsErrors(msg,msgbits);
}
if (Modes.debug & MODES_DEBUG_JS) {
dumpRawMessageJS(descr, msg, m, offset, fixable);
return;
}
printf("\n--- %s\n ", descr);
for (j = 0; j < MODES_LONG_MSG_BYTES; j++) {
printf("%02x",msg[j]);
if (j == MODES_SHORT_MSG_BYTES-1) printf(" ... ");
}
printf(" (DF %d, Fixable: %d)\n", msgtype, fixable);
dumpMagnitudeVector(m,offset);
printf("---\n\n");
}
/* ===================== Mode S detection and decoding ===================== */
/* Parity table for MODE S Messages.
* The table contains 112 elements, every element corresponds to a bit set
* in the message, starting from the first bit of actual data after the
* preamble.
*
* For messages of 112 bit, the whole table is used.
* For messages of 56 bits only the last 56 elements are used.
*
* The algorithm is as simple as xoring all the elements in this table
* for which the corresponding bit on the message is set to 1.
*
* The latest 24 elements in this table are set to 0 as the checksum at the
* end of the message should not affect the computation.
*
* Note: this function can be used with DF11 and DF17, other modes have
* the CRC xored with the sender address as they are reply to interrogations,
* but a casual listener can't split the address from the checksum.
*/
uint32_t modes_checksum_table[112] = {
0x3935ea, 0x1c9af5, 0xf1b77e, 0x78dbbf, 0xc397db, 0x9e31e9, 0xb0e2f0, 0x587178,
0x2c38bc, 0x161c5e, 0x0b0e2f, 0xfa7d13, 0x82c48d, 0xbe9842, 0x5f4c21, 0xd05c14,
0x682e0a, 0x341705, 0xe5f186, 0x72f8c3, 0xc68665, 0x9cb936, 0x4e5c9b, 0xd8d449,
0x939020, 0x49c810, 0x24e408, 0x127204, 0x093902, 0x049c81, 0xfdb444, 0x7eda22,
0x3f6d11, 0xe04c8c, 0x702646, 0x381323, 0xe3f395, 0x8e03ce, 0x4701e7, 0xdc7af7,
0x91c77f, 0xb719bb, 0xa476d9, 0xadc168, 0x56e0b4, 0x2b705a, 0x15b82d, 0xf52612,
0x7a9309, 0xc2b380, 0x6159c0, 0x30ace0, 0x185670, 0x0c2b38, 0x06159c, 0x030ace,
0x018567, 0xff38b7, 0x80665f, 0xbfc92b, 0xa01e91, 0xaff54c, 0x57faa6, 0x2bfd53,
0xea04ad, 0x8af852, 0x457c29, 0xdd4410, 0x6ea208, 0x375104, 0x1ba882, 0x0dd441,
0xf91024, 0x7c8812, 0x3e4409, 0xe0d800, 0x706c00, 0x383600, 0x1c1b00, 0x0e0d80,
0x0706c0, 0x038360, 0x01c1b0, 0x00e0d8, 0x00706c, 0x003836, 0x001c1b, 0xfff409,
0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000,
0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000,
0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000
};
uint32_t modesChecksum(unsigned char *msg, int bits) {
uint32_t crc = 0;
int offset = (bits == 112) ? 0 : (112-56);
int j;
for(j = 0; j < bits; j++) {
int byte = j/8;
int bit = j%8;
int bitmask = 1 << (7-bit);
/* If bit is set, xor with corresponding table entry. */
if (msg[byte] & bitmask)
crc ^= modes_checksum_table[j+offset];
}
return crc; /* 24 bit checksum. */
}
/* Given the Downlink Format (DF) of the message, return the message length
* in bits. */
int modesMessageLenByType(int type) {
if (type == 16 || type == 17 ||
type == 19 || type == 20 ||
type == 21)
return MODES_LONG_MSG_BITS;
else
return MODES_SHORT_MSG_BITS;
}
/* Try to fix single bit errors using the checksum. On success modifies
* the original buffer with the fixed version, and returns the position
* of the error bit. Otherwise if fixing failed -1 is returned. */
int fixSingleBitErrors(unsigned char *msg, int bits) {
int j;
unsigned char aux[MODES_LONG_MSG_BITS/8];
for (j = 0; j < bits; j++) {
int byte = j/8;
int bitmask = 1 << (7-(j%8));
uint32_t crc1, crc2;
memcpy(aux,msg,bits/8);
aux[byte] ^= bitmask; /* Flip j-th bit. */
crc1 = ((uint32_t)aux[(bits/8)-3] << 16) |
((uint32_t)aux[(bits/8)-2] << 8) |
(uint32_t)aux[(bits/8)-1];
crc2 = modesChecksum(aux,bits);
if (crc1 == crc2) {
/* The error is fixed. Overwrite the original buffer with
* the corrected sequence, and returns the error bit
* position. */
memcpy(msg,aux,bits/8);
return j;
}
}
return -1;
}
/* Similar to fixSingleBitErrors() but try every possible two bit combination.
* This is very slow and should be tried only against DF17 messages that
* don't pass the checksum, and only in Aggressive Mode. */
int fixTwoBitsErrors(unsigned char *msg, int bits) {
int j, i;
unsigned char aux[MODES_LONG_MSG_BITS/8];
for (j = 0; j < bits; j++) {
int byte1 = j/8;
int bitmask1 = 1 << (7-(j%8));
/* Don't check the same pairs multiple times, so i starts from j+1 */
for (i = j+1; i < bits; i++) {
int byte2 = i/8;
int bitmask2 = 1 << (7-(i%8));
uint32_t crc1, crc2;
memcpy(aux,msg,bits/8);
aux[byte1] ^= bitmask1; /* Flip j-th bit. */
aux[byte2] ^= bitmask2; /* Flip i-th bit. */
crc1 = ((uint32_t)aux[(bits/8)-3] << 16) |
((uint32_t)aux[(bits/8)-2] << 8) |
(uint32_t)aux[(bits/8)-1];
crc2 = modesChecksum(aux,bits);
if (crc1 == crc2) {
/* The error is fixed. Overwrite the original buffer with
* the corrected sequence, and returns the error bit
* position. */
memcpy(msg,aux,bits/8);
/* We return the two bits as a 16 bit integer by shifting
* 'i' on the left. This is possible since 'i' will always
* be non-zero because i starts from j+1. */
return j | (i<<8);
}
}
}
return -1;
}
/* Hash the ICAO address to index our cache of MODES_ICAO_CACHE_LEN
* elements, that is assumed to be a power of two. */
uint32_t ICAOCacheHashAddress(uint32_t a) {
/* The following three rounds wil make sure that every bit affects
* every output bit with ~ 50% of probability. */
a = ((a >> 16) ^ a) * 0x45d9f3b;
a = ((a >> 16) ^ a) * 0x45d9f3b;
a = ((a >> 16) ^ a);
return a & (MODES_ICAO_CACHE_LEN-1);
}
/* Add the specified entry to the cache of recently seen ICAO addresses.
* Note that we also add a timestamp so that we can make sure that the
* entry is only valid for MODES_ICAO_CACHE_TTL seconds. */
void addRecentlySeenICAOAddr(uint32_t addr) {
uint32_t h = ICAOCacheHashAddress(addr);
Modes.icao_cache[h*2] = addr;
Modes.icao_cache[h*2+1] = (uint32_t) time(NULL);
}
/* Returns 1 if the specified ICAO address was seen in a DF format with
* proper checksum (not xored with address) no more than * MODES_ICAO_CACHE_TTL
* seconds ago. Otherwise returns 0. */
int ICAOAddressWasRecentlySeen(uint32_t addr) {
uint32_t h = ICAOCacheHashAddress(addr);
uint32_t a = Modes.icao_cache[h*2];
uint32_t t = Modes.icao_cache[h*2+1];
return a && a == addr && time(NULL)-t <= MODES_ICAO_CACHE_TTL;
}
/* If the message type has the checksum xored with the ICAO address, try to
* brute force it using a list of recently seen ICAO addresses.
*
* Do this in a brute-force fashion by xoring the predicted CRC with
* the address XOR checksum field in the message. This will recover the
* address: if we found it in our cache, we can assume the message is ok.
*
* This function expects mm->msgtype and mm->msgbits to be correctly
* populated by the caller.
*
* On success the correct ICAO address is stored in the modesMessage
* structure in the aa3, aa2, and aa1 fiedls.
*
* If the function successfully recovers a message with a correct checksum
* it returns 1. Otherwise 0 is returned. */
int bruteForceAP(unsigned char *msg, struct modesMessage *mm) {
unsigned char aux[MODES_LONG_MSG_BYTES];
int msgtype = mm->msgtype;
int msgbits = mm->msgbits;
if (msgtype == 0 || /* Short air surveillance */
msgtype == 4 || /* Surveillance, altitude reply */
msgtype == 5 || /* Surveillance, identity reply */
msgtype == 16 || /* Long Air-Air survillance */
msgtype == 20 || /* Comm-A, altitude request */
msgtype == 21 || /* Comm-A, identity request */
msgtype == 24) /* Comm-C ELM */
{
uint32_t addr;
uint32_t crc;
int lastbyte = (msgbits/8)-1;
/* Work on a copy. */
memcpy(aux,msg,msgbits/8);
/* Compute the CRC of the message and XOR it with the AP field
* so that we recover the address, because:
*
* (ADDR xor CRC) xor CRC = ADDR. */
crc = modesChecksum(aux,msgbits);
aux[lastbyte] ^= crc & 0xff;
aux[lastbyte-1] ^= (crc >> 8) & 0xff;
aux[lastbyte-2] ^= (crc >> 16) & 0xff;
/* If the obtained address exists in our cache we consider
* the message valid. */
addr = aux[lastbyte] | (aux[lastbyte-1] << 8) | (aux[lastbyte-2] << 16);
if (ICAOAddressWasRecentlySeen(addr)) {
mm->aa1 = aux[lastbyte-2];
mm->aa2 = aux[lastbyte-1];
mm->aa3 = aux[lastbyte];
return 1;
}
}
return 0;
}
/* Decode the 13 bit AC altitude field (in DF 20 and others).
* Returns the altitude, and set 'unit' to either MODES_UNIT_METERS
* or MDOES_UNIT_FEETS. */
int decodeAC13Field(unsigned char *msg, int *unit) {
int m_bit = msg[3] & (1<<6);
int q_bit = msg[3] & (1<<4);
if (!m_bit) {
*unit = MODES_UNIT_FEET;
if (q_bit) {
/* N is the 11 bit integer resulting from the removal of bit
* Q and M */
int n = ((msg[2]&31)<<6) |
((msg[3]&0x80)>>2) |
((msg[3]&0x20)>>1) |
(msg[3]&15);
/* The final altitude is due to the resulting number multiplied
* by 25, minus 1000. */
return n*25-1000;
} else {
/* TODO: Implement altitude where Q=0 and M=0 */
}
} else {
*unit = MODES_UNIT_METERS;
/* TODO: Implement altitude when meter unit is selected. */
}
return 0;
}
/* Decode the 12 bit AC altitude field (in DF 17 and others).
* Returns the altitude or 0 if it can't be decoded. */
int decodeAC12Field(unsigned char *msg, int *unit) {
int q_bit = msg[5] & 1;
if (q_bit) {
/* N is the 11 bit integer resulting from the removal of bit
* Q */
*unit = MODES_UNIT_FEET;
int n = ((msg[5]>>1)<<4) | ((msg[6]&0xF0) >> 4);
/* The final altitude is due to the resulting number multiplied
* by 25, minus 1000. */
return n*25-1000;
} else {
return 0;
}
}
/* Capability table. */
char *ca_str[8] = {
/* 0 */ "Level 1 (Survillance Only)",
/* 1 */ "Level 2 (DF0,4,5,11)",
/* 2 */ "Level 3 (DF0,4,5,11,20,21)",
/* 3 */ "Level 4 (DF0,4,5,11,20,21,24)",
/* 4 */ "Level 2+3+4 (DF0,4,5,11,20,21,24,code7 - is on ground)",
/* 5 */ "Level 2+3+4 (DF0,4,5,11,20,21,24,code7 - is on airborne)",
/* 6 */ "Level 2+3+4 (DF0,4,5,11,20,21,24,code7)",
/* 7 */ "Level 7 ???"
};
/* Flight status table. */
char *fs_str[8] = {
/* 0 */ "Normal, Airborne",
/* 1 */ "Normal, On the ground",
/* 2 */ "ALERT, Airborne",
/* 3 */ "ALERT, On the ground",
/* 4 */ "ALERT & Special Position Identification. Airborne or Ground",
/* 5 */ "Special Position Identification. Airborne or Ground",
/* 6 */ "Value 6 is not assigned",
/* 7 */ "Value 7 is not assigned"
};
/* ME message type to description table. */
char *me_str[] = {
};
char *getMEDescription(int metype, int mesub) {
char *mename = "Unknown";
if (metype >= 1 && metype <= 4)
mename = "Aircraft Identification and Category";
else if (metype >= 5 && metype <= 8)
mename = "Surface Position";
else if (metype >= 9 && metype <= 18)
mename = "Airborne Position (Baro Altitude)";
else if (metype == 19 && mesub >=1 && mesub <= 4)
mename = "Airborne Velocity";
else if (metype >= 20 && metype <= 22)
mename = "Airborne Position (GNSS Height)";
else if (metype == 23 && mesub == 0)
mename = "Test Message";
else if (metype == 24 && mesub == 1)
mename = "Surface System Status";
else if (metype == 28 && mesub == 1)
mename = "Extended Squitter Aircraft Status (Emergency)";
else if (metype == 28 && mesub == 2)
mename = "Extended Squitter Aircraft Status (1090ES TCAS RA)";
else if (metype == 29 && (mesub == 0 || mesub == 1))
mename = "Target State and Status Message";
else if (metype == 31 && (mesub == 0 || mesub == 1))
mename = "Aircraft Operational Status Message";
return mename;
}
/* Decode a raw Mode S message demodulated as a stream of bytes by
* detectModeS(), and split it into fields populating a modesMessage
* structure. */
void decodeModesMessage(struct modesMessage *mm, unsigned char *msg) {
uint32_t crc2; /* Computed CRC, used to verify the message CRC. */
char *ais_charset = "?ABCDEFGHIJKLMNOPQRSTUVWXYZ????? ???????????????0123456789??????";
/* Work on our local copy */
memcpy(mm->msg,msg,MODES_LONG_MSG_BYTES);
msg = mm->msg;
/* Get the message type ASAP as other operations depend on this */
mm->msgtype = msg[0]>>3; /* Downlink Format */
mm->msgbits = modesMessageLenByType(mm->msgtype);
/* CRC is always the last three bytes. */
mm->crc = ((uint32_t)msg[(mm->msgbits/8)-3] << 16) |
((uint32_t)msg[(mm->msgbits/8)-2] << 8) |
(uint32_t)msg[(mm->msgbits/8)-1];
crc2 = modesChecksum(msg,mm->msgbits);
/* Check CRC and fix single bit errors using the CRC when
* possible (DF 11 and 17). */
mm->errorbit = -1; /* No error */
mm->crcok = (mm->crc == crc2);
if (!mm->crcok && Modes.fix_errors &&
(mm->msgtype == 11 || mm->msgtype == 17))
{
if ((mm->errorbit = fixSingleBitErrors(msg,mm->msgbits)) != -1) {
mm->crc = modesChecksum(msg,mm->msgbits);
mm->crcok = 1;
} else if (Modes.aggressive && mm->msgtype == 17 &&
(mm->errorbit = fixTwoBitsErrors(msg,mm->msgbits)) != -1)
{
mm->crc = modesChecksum(msg,mm->msgbits);
mm->crcok = 1;
}
}
/* Note that most of the other computation happens *after* we fix
* the single bit errors, otherwise we would need to recompute the
* fields again. */
mm->ca = msg[0] & 7; /* Responder capabilities. */
/* ICAO address */
mm->aa1 = msg[1];
mm->aa2 = msg[2];
mm->aa3 = msg[3];
/* DF 17 type (assuming this is a DF17, otherwise not used) */