forked from wiedehopf/readsb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.c
2110 lines (1744 loc) · 68.8 KB
/
api.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
#include "readsb.h"
#define API_HASH_BITS (16)
#define API_BUCKETS (1 << API_HASH_BITS)
static int apiUpdate();
static inline uint32_t hexHash(uint32_t addr) {
return addrHash(addr, API_HASH_BITS);
}
static inline uint32_t regHash(char *reg) {
const uint64_t seed = 0x30732349f7810465ULL;
uint64_t h = fasthash64(reg, 12, seed);
uint32_t bits = API_HASH_BITS;
uint64_t res = h ^ (h >> 32);
if (bits < 16)
res ^= (res >> 16);
res ^= (res >> bits);
// mask to fit the requested bit width
res &= (((uint64_t) 1) << bits) - 1;
return (uint32_t) res;
}
static inline uint32_t callsignHash(char *callsign) {
const uint64_t seed = 0x30732349f7810465ULL;
uint64_t h = fasthash64(callsign, 8, seed);
uint32_t bits = API_HASH_BITS;
uint64_t res = h ^ (h >> 32);
if (bits < 16)
res ^= (res >> 16);
res ^= (res >> bits);
// mask to fit the requested bit width
res &= (((uint64_t) 1) << bits) - 1;
return (uint32_t) res;
}
static int antiSpam(int64_t *nextPrint, int64_t interval) {
int64_t now = mstime();
if (now > *nextPrint) {
*nextPrint = now + interval;
return 1;
} else {
return 0;
}
}
static int compareLon(const void *p1, const void *p2) {
struct apiEntry *a1 = (struct apiEntry*) p1;
struct apiEntry *a2 = (struct apiEntry*) p2;
return (a1->bin.lon > a2->bin.lon) - (a1->bin.lon < a2->bin.lon);
}
static struct range findLonRange(int32_t ref_from, int32_t ref_to, struct apiEntry *list, int len) {
struct range res;
memset(&res, 0, sizeof(res));
if (len == 0 || ref_from > ref_to)
return res;
// get lower bound
int i = 0;
int j = len - 1;
while (j > i + 1) {
int pivot = (i + j) / 2;
if (list[pivot].bin.lon < ref_from)
i = pivot;
else
j = pivot;
}
if (list[j].bin.lon < ref_from) {
res.from = j + 1;
} else if (list[i].bin.lon < ref_from) {
res.from = i + 1;
} else {
res.from = i;
}
// get upper bound (exclusive)
i = imin(res.from, len - 1);
j = len - 1;
while (j > i + 1) {
int pivot = (i + j) / 2;
if (list[pivot].bin.lon <= ref_to)
i = pivot;
else
j = pivot;
}
if (list[j].bin.lon <= ref_to) {
res.to = j + 1;
} else if (list[i].bin.lon <= ref_to) {
res.to = i + 1;
} else {
res.to = i;
}
return res;
}
static int filter_alt_baro(struct apiEntry *haystack, int haylen, struct apiEntry *matches, size_t *alloc, struct apiOptions *options) {
int count = 0;
float reverse_alt_factor = 1.0f / BINCRAFT_ALT_FACTOR;
for (int i = 0; i < haylen; i++) {
struct apiEntry *e = &haystack[i];
int32_t alt = INT32_MIN;
if (e->bin.baro_alt_valid) {
alt = e->bin.baro_alt * reverse_alt_factor;
} else if (e->bin.airground == AG_GROUND) {
alt = 0;
}
if (alt >= options->above_alt_baro && alt <= options->below_alt_baro && alt != INT32_MIN) {
matches[count++] = *e;
*alloc += e->jsonOffset.len;
}
}
return count;
}
static int filter_dbFlags(struct apiEntry *haystack, int haylen, struct apiEntry *matches, size_t *alloc, struct apiOptions *options) {
int count = 0;
for (int i = 0; i < haylen; i++) {
struct apiEntry *e = &haystack[i];
if (
(options->filter_mil && (e->bin.dbFlags & 1))
|| (options->filter_interesting && (e->bin.dbFlags & 2))
|| (options->filter_pia && (e->bin.dbFlags & 4))
|| (options->filter_ladd && (e->bin.dbFlags & 8))
) {
matches[count++] = *e;
*alloc += e->jsonOffset.len;
}
}
return count;
}
static int filterWithPos(struct apiEntry *haystack, int haylen, struct apiEntry *matches, size_t *alloc) {
int count = 0;
for (int i = 0; i < haylen; i++) {
struct apiEntry *e = &haystack[i];
if (e->bin.position_valid) {
matches[count++] = *e;
*alloc += e->jsonOffset.len;
}
}
return count;
}
static int filterSquawk(struct apiEntry *haystack, int haylen, struct apiEntry *matches, size_t *alloc, unsigned squawk) {
int count = 0;
for (int i = 0; i < haylen; i++) {
struct apiEntry *e = &haystack[i];
//fprintf(stderr, "%04x %04x\n", options->squawk, e->bin.squawk);
if (e->bin.squawk == squawk && e->bin.squawk_valid) {
matches[count++] = *e;
*alloc += e->jsonOffset.len;
}
}
return count;
}
static int filterCallsignPrefix(struct apiEntry *haystack, int haylen, struct apiEntry *matches, size_t *alloc, char *callsign_prefix) {
int count = 0;
int prefix_len = strlen(callsign_prefix);
for (int j = 0; j < haylen; j++) {
struct apiEntry *e = &haystack[j];
if (e->bin.callsign_valid && strncmp(e->bin.callsign, callsign_prefix, prefix_len) == 0) {
matches[count++] = *e;
*alloc += e->jsonOffset.len;
}
}
return count;
}
static int filterCallsignExact(struct apiEntry *haystack, int haylen, struct apiEntry *matches, size_t *alloc, char *callsign) {
// replace null padding with space padding
for (int i = 0; i < 8; i++) {
if (callsign[i] == '\0') {
callsign[i] = ' ';
}
}
int count = 0;
for (int j = 0; j < haylen; j++) {
struct apiEntry *e = &haystack[j];
if (e->bin.callsign_valid && strncmp(e->bin.callsign, callsign, 8) == 0) {
matches[count++] = *e;
*alloc += e->jsonOffset.len;
}
}
return count;
}
static int filterTypeList(struct apiEntry *haystack, int haylen, char *typeList, int typeCount, struct apiEntry *matches, size_t *alloc) {
int count = 0;
for (int k = 0; k < typeCount; k++) {
char *typeCode = typeList + 4 * k;
// upper case typeCode
for (int i = 0; i < 4; i++) {
typeCode[i] = toupper(typeCode[i]);
}
}
for (int j = 0; j < haylen; j++) {
struct apiEntry *e = &haystack[j];
for (int k = 0; k < typeCount; k++) {
char *typeCode = typeList + 4 * k;
if (strncmp(e->bin.typeCode, typeCode, 4) == 0) {
//fprintf(stderr, "typeCode: %.4s %.4s alloc increase by %d\n", e->bin.typeCode, typeCode, e->jsonOffset.len);
matches[count++] = *e;
*alloc += e->jsonOffset.len;
// break inner loop
break;
}
}
}
return count;
}
static int inLatRange(struct apiEntry *e, int32_t lat1, int32_t lat2, struct apiOptions *options) {
return (e->bin.lat >= lat1 && e->bin.lat <= lat2 && (e->bin.position_valid || options->binCraft));
}
static int findInBox(struct apiEntry *haystack, int haylen, struct apiOptions *options, struct apiEntry *matches, size_t *alloc) {
double *box = options->box;
struct range r[2];
memset(r, 0, sizeof(r));
int count = 0;
int32_t lat1 = (int32_t) (box[0] * 1E6);
int32_t lat2 = (int32_t) (box[1] * 1E6);
int32_t lon1 = (int32_t) (box[2] * 1E6);
int32_t lon2 = (int32_t) (box[3] * 1E6);
if (lon1 <= lon2) {
r[0] = findLonRange(lon1, lon2, haystack, haylen);
} else if (lon1 > lon2) {
r[0] = findLonRange(lon1, 180E6, haystack, haylen);
r[1] = findLonRange(-180E6, lon2, haystack, haylen);
//fprintf(stderr, "%.1f to 180 and -180 to %1.f\n", lon1 / 1E6, lon2 / 1E6);
}
for (int k = 0; k < 2; k++) {
for (int j = r[k].from; j < r[k].to; j++) {
struct apiEntry *e = &haystack[j];
if (inLatRange(e, lat1, lat2, options)) {
matches[count++] = *e;
*alloc += e->jsonOffset.len;
}
}
}
//fprintf(stderr, "box: lat %.1f to %.1f, lon %.1f to %.1f, count: %d\n", box[0], box[1], box[2], box[3], count);
return count;
}
static int findRegList(struct apiEntry **hashList, char *regList, int regCount, struct apiEntry *matches, size_t *alloc) {
int count = 0;
for (int k = 0; k < regCount; k++) {
char *reg = ®List[k * 12];
// upper case reg
for (int i = 0; i < 12; i++) {
reg[i] = toupper(reg[i]);
}
//fprintf(stderr, "reg: %s\n", reg);
uint32_t hash = regHash(reg);
struct apiEntry *e = hashList[hash];
while (e) {
if (strncmp(e->bin.registration, reg, 12) == 0) {
matches[count++] = *e;
*alloc += e->jsonOffset.len;
break;
}
e = e->nextReg;
}
}
return count;
}
static int findCallsignList(struct apiEntry **hashList, char *callsignList, int callsignCount, struct apiEntry *matches, size_t *alloc) {
int count = 0;
for (int k = 0; k < callsignCount; k++) {
char *callsign = &callsignList[k * 8];
// replace null padding with space padding, upper case input
for (int i = 0; i < 8; i++) {
callsign[i] = toupper(callsign[i]);
if (callsign[i] == '\0') {
callsign[i] = ' ';
}
}
uint32_t hash = callsignHash(callsign);
//fprintf(stderr, "callsign: %8s hash: %u\n", callsign, hash);
struct apiEntry *e = hashList[hash];
while (e) {
//fprintf(stderr, "callsign: %8s\n", e->bin.callsign);
if (strncmp(e->bin.callsign, callsign, 8) == 0) {
matches[count++] = *e;
*alloc += e->jsonOffset.len;
break;
}
e = e->nextCallsign;
}
}
return count;
}
static int findHexList(struct apiEntry **hashList, uint32_t *hexList, int hexCount, struct apiEntry *matches, size_t *alloc) {
int count = 0;
for (int k = 0; k < hexCount; k++) {
uint32_t addr = hexList[k];
uint32_t hash = hexHash(addr);
struct apiEntry *e = hashList[hash];
while (e) {
if (e->bin.hex == addr) {
matches[count++] = *e;
*alloc += e->jsonOffset.len;
break;
}
e = e->nextHex;
}
}
return count;
}
static int findInCircle(struct apiEntry *haystack, int haylen, struct apiOptions *options, struct apiEntry *matches, size_t *alloc) {
struct apiCircle *circle = &options->circle;
struct range r[2];
memset(r, 0, sizeof(r));
int count = 0;
double lat = circle->lat;
double lon = circle->lon;
double radius = circle->radius; // in meters
bool onlyClosest = circle->onlyClosest;
double circum = 40075e3; // earth circumference is 40075km
double fudge = 1.002; // make the box we check a little bigger
double londiff = fudge * radius / (cos(lat * M_PI / 180.0) * circum + 1) * 360;
double o1 = lon - londiff;
double o2 = lon + londiff;
o1 = o1 < -180 ? o1 + 360: o1;
o2 = o2 > 180 ? o2 - 360 : o2;
if (londiff >= 180) {
// just check all lon
o1 = -180;
o2 = 180;
}
double latdiff = fudge * radius / (circum / 2) * 180.0;
double a1 = lat - latdiff;
double a2 = lat + latdiff;
if (a1 < -90 || a2 > 90) {
// going over a pole, just check all lon
o1 = -180;
o2 = 180;
}
int32_t lat1 = (int32_t) (a1 * 1E6);
int32_t lat2 = (int32_t) (a2 * 1E6);
int32_t lon1 = (int32_t) (o1 * 1E6);
int32_t lon2 = (int32_t) (o2 * 1E6);
//fprintf(stderr, "radius:%8.0f latdiff: %8.0f londiff: %8.0f\n", radius, greatcircle(a1, lon, lat, lon), greatcircle(lat, o1, lat, lon, 0));
if (lon1 <= lon2) {
r[0] = findLonRange(lon1, lon2, haystack, haylen);
} else if (lon1 > lon2) {
r[0] = findLonRange(lon1, 180E6, haystack, haylen);
r[1] = findLonRange(-180E6, lon2, haystack, haylen);
//fprintf(stderr, "%.1f to 180 and -180 to %1.f\n", lon1 / 1E6, lon2 / 1E6);
}
if (onlyClosest) {
bool found = false;
double minDistance = 300E6; // larger than any distances we encounter, also how far light travels in a second
for (int k = 0; k < 2; k++) {
for (int j = r[k].from; j < r[k].to; j++) {
struct apiEntry *e = &haystack[j];
if (inLatRange(e, lat1, lat2, options)) {
double dist = greatcircle(lat, lon, e->bin.lat / 1E6, e->bin.lon / 1E6, 0);
if (dist < radius && dist < minDistance) {
// first match is overwritten repeatedly
matches[0] = *e;
matches[0].distance = (float) dist;
minDistance = dist;
found = true;
}
}
}
}
if (found) {
// calculate bearing for (the only) match
struct apiEntry *e = &matches[0];
*alloc += e->jsonOffset.len;
e->direction = (float) bearing(lat, lon, e->bin.lat / 1E6, e->bin.lon / 1E6);
count = 1;
}
}
if (!onlyClosest) {
for (int k = 0; k < 2; k++) {
for (int j = r[k].from; j < r[k].to; j++) {
struct apiEntry *e = &haystack[j];
if (inLatRange(e, lat1, lat2, options)) {
double dist = greatcircle(lat, lon, e->bin.lat / 1E6, e->bin.lon / 1E6, 0);
if (dist < radius) {
matches[count] = *e;
matches[count].distance = (float) dist;
matches[count].direction = (float) bearing(lat, lon, e->bin.lat / 1E6, e->bin.lon / 1E6);
*alloc += e->jsonOffset.len;
count++;
}
}
}
}
}
//fprintf(stderr, "circle count: %d\n", count);
return count;
}
static struct apiEntry *apiAlloc(int count) {
struct apiEntry *buf = cmalloc(count * sizeof(struct apiEntry));
if (!buf) {
fprintf(stderr, "FATAL: apiAlloc malloc fail\n");
setExit(2);
}
return buf;
}
static struct char_buffer apiReq(struct apiThread *thread, struct apiOptions *options) {
int flip = atomic_load(&Modes.apiFlip[thread->index]);
struct apiBuffer *buffer = &Modes.apiBuffer[flip];
struct apiEntry *haystack;
int haylen;
struct range pos_range;
struct range all_range;
if (options->filter_dbFlag) {
haystack = buffer->list_flag;
haylen = buffer->len_flag;
pos_range = buffer->list_flag_pos_range;
all_range.from = 0;
all_range.to = haylen;
} else {
haystack = buffer->list;
haylen = buffer->len;
pos_range = buffer->list_pos_range;
all_range.from = 0;
all_range.to = haylen;
}
struct char_buffer cb = { 0 };
struct apiEntry *matches = NULL;
size_t alloc_base = API_REQ_PADSTART + 1024;
size_t alloc = alloc_base;
int count = 0;
int doFree = 0;
if (options->is_box) {
int combined_len = haylen;
if (options->is_hexList) {
// this is a special case, in addition to the box, also return results for the hexList
// we don't bother deduplicating, so this can return results more than once
// thus allocate haylen and then also the number of hexes queried in addition
combined_len += options->hexCount;
}
doFree = 1; matches = apiAlloc(combined_len); if (!matches) { return cb; };
// first get matches for the box
count = findInBox(haystack, haylen, options, matches, &alloc);
if (options->is_hexList) {
// optionally add matches for &find_hex
count += findHexList(buffer->hexHash, options->hexList, options->hexCount, matches + count, &alloc);
}
} else if (options->is_circle) {
doFree = 1; matches = apiAlloc(haylen); if (!matches) { return cb; };
count = findInCircle(haystack, haylen, options, matches, &alloc);
alloc += count * 30; // adding 27 characters per entry: ,"dst":1000.000, "dir":357
} else if (options->is_hexList) {
doFree = 1; matches = apiAlloc(options->hexCount); if (!matches) { return cb; };
count = findHexList(buffer->hexHash, options->hexList, options->hexCount, matches, &alloc);
} else if (options->is_regList) {
doFree = 1; matches = apiAlloc(options->regCount); if (!matches) { return cb; };
count = findRegList(buffer->regHash, options->regList, options->regCount, matches, &alloc);
} else if (options->is_callsignList) {
doFree = 1; matches = apiAlloc(options->callsignCount); if (!matches) { return cb; };
count = findCallsignList(buffer->callsignHash, options->callsignList, options->callsignCount, matches, &alloc);
} else if (options->is_typeList) {
doFree = 1; matches = apiAlloc(haylen); if (!matches) { return cb; };
count = filterTypeList(haystack, haylen, options->typeList, options->typeCount, matches, &alloc);
} else if (options->all || options->all_with_pos) {
struct range range;
if (options->all) {
range = all_range;
} else if ( options->all_with_pos) {
range = pos_range;
} else {
fprintf(stderr, "FATAL: unreachablei ahchoh8R\n");
setExit(2);
return cb;
}
count = range.to - range.from;
if (count > 0) {
struct apiEntry *first = &haystack[range.from];
struct apiEntry *last = &haystack[range.to - 1];
// assume continuous allocation from generation of api buffer
alloc += last->jsonOffset.offset + last->jsonOffset.len - first->jsonOffset.offset;
doFree = 0;
matches = first;
} else {
doFree = 0;
matches = NULL;
}
}
if (options->filter_squawk) {
struct apiEntry *filtered = apiAlloc(count); if (!filtered) { return cb; }
size_t alloc = alloc_base;
count = filterSquawk(matches, count, filtered, &alloc, options->squawk);
if (doFree) { sfree(matches); }; doFree = 1; matches = filtered;
}
// filter all_with_pos as pos_range unreliable due do gpsOkBefore f***ery
if (options->filter_with_pos || options->all_with_pos) {
struct apiEntry *filtered = apiAlloc(count); if (!filtered) { return cb; }
size_t alloc = alloc_base;
count = filterWithPos(matches, count, filtered, &alloc);
if (doFree) { sfree(matches); }; doFree = 1; matches = filtered;
}
if (options->filter_dbFlag) {
struct apiEntry *filtered = apiAlloc(count); if (!filtered) { return cb; }
size_t alloc = alloc_base;
count = filter_dbFlags(matches, count, filtered, &alloc, options);
if (doFree) { sfree(matches); }; doFree = 1; matches = filtered;
}
if (options->filter_alt_baro) {
struct apiEntry *filtered = apiAlloc(count); if (!filtered) { return cb; }
size_t alloc = alloc_base;
count = filter_alt_baro(matches, count, filtered, &alloc, options);
if (doFree) { sfree(matches); }; doFree = 1; matches = filtered;
}
if (options->filter_callsign_prefix) {
struct apiEntry *filtered = apiAlloc(count); if (!filtered) { return cb; }
size_t alloc = alloc_base;
count = filterCallsignPrefix(matches, count, filtered, &alloc, options->callsign_prefix);
if (doFree) { sfree(matches); }; doFree = 1; matches = filtered;
}
if (options->filter_callsign_exact) {
struct apiEntry *filtered = apiAlloc(count); if (!filtered) { return cb; }
size_t alloc = alloc_base;
count = filterCallsignExact(matches, count, filtered, &alloc, options->callsign_exact);
if (doFree) { sfree(matches); }; doFree = 1; matches = filtered;
}
if (options->filter_typeList) {
struct apiEntry *filtered = apiAlloc(count); if (!filtered) { return cb; }
size_t alloc = alloc_base;
count = filterTypeList(matches, count, options->typeList, options->typeCount, filtered, &alloc);
if (doFree) { sfree(matches); }; doFree = 1; matches = filtered;
}
// elementSize only applies to binCraft output
uint32_t elementSize = sizeof(struct binCraft);
if (options->binCraft) {
alloc = API_REQ_PADSTART + 2 * elementSize + count * elementSize;
}
cb.buffer = cmalloc(alloc);
if (!cb.buffer)
return cb;
char *payload = cb.buffer + API_REQ_PADSTART;
char *p = payload;
char *end = cb.buffer + alloc;
if (options->binCraft) {
memset(p, 0, elementSize);
#define memWrite(p, var) do { if (p + sizeof(var) > end) { break; }; memcpy(p, &var, sizeof(var)); p += sizeof(var); } while(0)
int64_t now = buffer->timestamp;
memWrite(p, now);
memWrite(p, elementSize);
uint32_t ac_count_pos = Modes.globalStatsCount.readsb_aircraft_with_position;
memWrite(p, ac_count_pos);
uint32_t index = 0;
memWrite(p, index);
int16_t south = -90;
int16_t west = -180;
int16_t north = 90;
int16_t east = 180;
if (options->is_box) {
south = nearbyint(options->box[0]);
north = nearbyint(options->box[1]);
west = nearbyint(options->box[2]);
east = nearbyint(options->box[3]);
}
memWrite(p, south);
memWrite(p, west);
memWrite(p, north);
memWrite(p, east);
uint32_t messageCount = Modes.stats_current.messages_total + Modes.stats_alltime.messages_total;
memWrite(p, messageCount);
uint32_t resultCount = count;
memWrite(p, resultCount);
int32_t dummy = 0;
memWrite(p, dummy);
memWrite(p, Modes.binCraftVersion);
uint32_t messageRate = nearbyint(Modes.messageRate * 10);
memWrite(p, messageRate);
#undef memWrite
if (p - payload > (int) elementSize) {
fprintf(stderr, "apiBin: too many details in first element\n");
}
p = payload + elementSize;
for (int i = 0; i < count; i++) {
if (unlikely(p + elementSize > end)) {
fprintf(stderr, "search code deeK9OoR: count: %d need: %ld alloc: %ld\n", count, (long) ((count + 1) * elementSize), (long) alloc);
break;
}
struct apiEntry *e = &matches[i];
memcpy(p, &e->bin, elementSize);
p += elementSize;
}
} else {
if (options->jamesv2) {
p = safe_snprintf(p, end, "{\"ac\":[");
} else {
p = safe_snprintf(p, end, "{\"now\": %.3f", buffer->timestamp / 1000.0);
p = safe_snprintf(p, end, "\n,\"aircraft\":[");
}
char *json = buffer->json;
for (int i = 0; i < count; i++) {
struct apiEntry *e = &matches[i];
struct offset off = e->jsonOffset; // READ-ONLY here
if (unlikely(p + off.len + 100 >= end)) {
fprintf(stderr, "search code ieva2aeV: count: %d need: %ld alloc: %ld\n", count, (long) ((p + off.len + 100) - payload), (long) alloc);
break;
}
memcpy(p, json + off.offset, off.len);
p += off.len;
if (options->is_circle) {
// json objects in cache are terminated by a comma: \n{ .... },
p -= 2; // remove \} and , and make sure printf puts those back
p = safe_snprintf(p, end, ",\"dst\":%.3f,\"dir\":%.1f},", e->distance / 1852.0, e->direction);
}
}
// json objects in cache are terminated by a comma: \n{ .... },
if (*(p - 1) == ',')
p--; // remove trailing comma if necessary
options->request_processed = microtime();
p = safe_snprintf(p, end, "\n]");
if (options->jamesv2) {
p = safe_snprintf(p, end, "\n,\"msg\": \"No error\"");
p = safe_snprintf(p, end, "\n,\"now\": %lld", (long long) buffer->timestamp);
p = safe_snprintf(p, end, "\n,\"total\": %d", count);
p = safe_snprintf(p, end, "\n,\"ctime\": %lld", (long long) buffer->timestamp);
p = safe_snprintf(p, end, "\n,\"ptime\": %lld", (long long) nearbyint((options->request_processed - options->request_received) / 1000.0));
} else {
p = safe_snprintf(p, end, "\n,\"resultCount\": %d", count);
p = safe_snprintf(p, end, "\n,\"ptime\": %.3f", (options->request_processed - options->request_received) / 1000.0);
}
p = safe_snprintf(p, end, "\n}\n");
}
cb.len = p - cb.buffer;
size_t payload_len = p - payload;
if (cb.len > alloc) {
fprintf(stderr, "apiReq buffer insufficient\n");
}
if (doFree) {
sfree(matches);
}
if (options->zstd) {
struct char_buffer new = { 0 };
size_t new_alloc = API_REQ_PADSTART + ZSTD_compressBound(alloc);
new.buffer = cmalloc(new_alloc);
memset(new.buffer, 0x0, new_alloc);
struct char_buffer dst;
dst.buffer = new.buffer + API_REQ_PADSTART;
dst.len = new_alloc - API_REQ_PADSTART;
//fprintf(stderr, "payload_len %ld\n", (long) payload_len);
size_t compressedSize = ZSTD_compressCCtx(thread->cctx,
dst.buffer, dst.len,
payload, payload_len,
API_ZSTD_LVL);
dst.len = compressedSize;
new.len = API_REQ_PADSTART + compressedSize;
ident(dst);
//free uncompressed buffer
sfree(cb.buffer);
cb = new;
if (ZSTD_isError(compressedSize)) {
fprintf(stderr, "API zstd error: %s\n", ZSTD_getErrorName(compressedSize));
sfree(cb.buffer);
cb.buffer = NULL;
cb.len = 0;
return cb;
}
//fprintf(stderr, "first 4 bytes: %08x len: %ld\n", *((uint32_t *) cb.buffer), (long) cb.len);
}
return cb;
}
static inline void apiAdd(struct apiBuffer *buffer, struct aircraft *a, int64_t now) {
if (!(includeAircraftJson(now, a)))
return;
struct apiEntry *entry = &(buffer->list[buffer->len]);
memset(entry, 0, sizeof(struct apiEntry));
toBinCraft(a, &entry->bin, now);
if (trackDataValid(&a->pos_reliable_valid)) {
// position valid
// else if (trackDataAge(now, &a->pos_reliable_valid) < 30 * MINUTES)
} else if (a->nogpsCounter >= NOGPS_SHOW && now - a->seenAdsbReliable < NOGPS_DWELL) {
// keep in box
} else {
// change lat / lon for sorting purposes
entry->bin.lat = INT32_MAX;
entry->bin.lon = INT32_MAX;
}
buffer->aircraftJsonCount++;
entry->globe_index = a->globe_index;
buffer->len++;
}
static inline void apiGenerateJson(struct apiBuffer *buffer, int64_t now) {
sfree(buffer->json);
buffer->json = NULL;
size_t alloc = buffer->len * 1024 + 4096; // The initial buffer is resized as needed
buffer->json = (char *) cmalloc(alloc);
char *p = buffer->json;
char *end = buffer->json + alloc;
for (int i = 0; i < buffer->len; i++) {
if ((p + 2000) >= end) {
int used = p - buffer->json;
alloc *= 2;
buffer->json = (char *) realloc(buffer->json, alloc);
p = buffer->json + used;
end = buffer->json + alloc;
}
struct apiEntry *entry = &buffer->list[i];
struct aircraft *a = aircraftGet(entry->bin.hex);
if (!a) {
fprintf(stderr, "FATAL: apiGenerateJson: aircraft missing, this shouldn't happen.");
setExit(2);
entry->jsonOffset.offset = 0;
entry->jsonOffset.len = 0;
continue;
}
uint32_t hash;
hash = hexHash(entry->bin.hex);
entry->nextHex = buffer->hexHash[hash];
buffer->hexHash[hash] = entry;
hash = regHash(entry->bin.registration);
entry->nextReg = buffer->regHash[hash];
buffer->regHash[hash] = entry;
hash = callsignHash(entry->bin.callsign);
entry->nextCallsign = buffer->callsignHash[hash];
buffer->callsignHash[hash] = entry;
//fprintf(stderr, "callsign: %8s hash: %u\n", entry->bin.callsign, hash);
char *start = p;
*p++ = '\n';
p = sprintAircraftObject(p, end, a, now, 0, NULL);
*p++ = ',';
entry->jsonOffset.offset = start - buffer->json;
entry->jsonOffset.len = p - start;
}
buffer->jsonLen = p - buffer->json;
if (p >= end) {
fprintf(stderr, "FATAL: buffer full apiAdd\n");
setExit(2);
}
}
static int apiUpdate() {
struct craftArray *ca = &Modes.aircraftActive;
// always clear and update the inactive apiBuffer
int flip = (atomic_load(&Modes.apiFlip[0]) + 1) % 2;
struct apiBuffer *buffer = &Modes.apiBuffer[flip];
// reset buffer lengths
buffer->len = 0;
buffer->len_flag = 0;
int acCount = ca->len;
if (buffer->alloc < acCount) {
if (acCount > 100000) {
fprintf(stderr, "<3> this is strange, too many aircraft!\n");
}
buffer->alloc = acCount + 128;
sfree(buffer->list);
sfree(buffer->list_flag);
buffer->list = cmalloc(buffer->alloc * sizeof(struct apiEntry));
buffer->list_flag = cmalloc(buffer->alloc * sizeof(struct apiEntry));
if (!buffer->list || !buffer->list_flag) {
fprintf(stderr, "apiList alloc: out of memory!\n");
exit(1);
}
}
// reset hashList to NULL
memset(buffer->hexHash, 0x0, API_BUCKETS * sizeof(struct apiEntry*));
memset(buffer->regHash, 0x0, API_BUCKETS * sizeof(struct apiEntry*));
memset(buffer->callsignHash, 0x0, API_BUCKETS * sizeof(struct apiEntry*));
// reset api list, just in case we don't set the entries completely due to oversight
memset(buffer->list, 0x0, buffer->alloc * sizeof(struct apiEntry));
memset(buffer->list_flag, 0x0, buffer->alloc * sizeof(struct apiEntry));
buffer->aircraftJsonCount = 0;
int64_t now = mstime();
ca_lock_read(ca);
for (int i = 0; i < ca->len; i++) {
struct aircraft *a = ca->list[i];
if (a == NULL)
continue;
apiAdd(buffer, a, now);
}
ca_unlock_read(ca);
// sort api lists
qsort(buffer->list, buffer->len, sizeof(struct apiEntry), compareLon);
apiGenerateJson(buffer, now);
for (int i = 0; i < buffer->len; i++) {
struct apiEntry entry = buffer->list[i];
if (entry.bin.dbFlags) {
// copy entry into flags list (only contains aircraft with at least one dbFlag set
buffer->list_flag[buffer->len_flag++] = entry;
}
}
// sort not needed as order is maintained copying from main list
buffer->list_pos_range = findLonRange(-180 * 1E6, 180 * 1E6, buffer->list, buffer->len);
buffer->list_flag_pos_range = findLonRange(-180 * 1E6, 180 * 1E6, buffer->list_flag, buffer->len_flag);
buffer->timestamp = now;
// doesn't matter which of the 2 buffers the api req will use they are both pretty current
for (int i = 0; i < Modes.apiThreadCount; i++) {
atomic_store(&Modes.apiFlip[i], flip);
}
pthread_cond_signal(&Threads.json.cond);
pthread_cond_signal(&Threads.globeJson.cond);
return buffer->len;
}
static int shutClose(int fd) {
if (shutdown(fd, SHUT_RDWR) < 0) { // Secondly, terminate the reliable delivery
if (errno != ENOTCONN && errno != EINVAL) { // SGI causes EINVAL
fprintf(stderr, "API: Shutdown client socket failed.\n");
}
}
return close(fd);
}
static void apiCloseCon(struct apiCon *con, struct apiThread *thread) {
if (!con->open) {
fprintf(stderr, "apiCloseCon double close!\n");
return;
}
int fd = con->fd;
if (con->events && epoll_ctl(thread->epfd, EPOLL_CTL_DEL, fd, NULL)) {
fprintf(stderr, "apiCloseCon: EPOLL_CTL_DEL %d: %s\n", fd, strerror(errno));
}
con->events = 0;
if (shutClose(fd) != 0) {
perror("apiCloseCon: close:");
}
if (Modes.debug_api) {
fprintf(stderr, "%d %d apiCloseCon()\n", thread->index, fd);
}
sfree(con->request.buffer);
con->request.len = 0;
con->request.alloc = 0;
struct char_buffer *reply = &con->reply;
thread->responseBytesBuffered -= reply->len;
sfree(reply->buffer);
reply->len = 0;
reply->alloc = 0;
con->open = 0;
thread->conCount--;
// put it back on the stack of free connection structs
thread->stack[thread->stackCount++] = con;
//fprintf(stderr, "%2d %5d\n", thread->index, thread->conCount);
}
static void apiResetCon(struct apiCon *con, struct apiThread *thread) {
if (!con->open) {
fprintf(stderr, "apiResetCon called on closed connection!\n");
return;
}
if (!con->keepalive) {
apiCloseCon(con, thread);
return;
}
if (Modes.debug_api) {
fprintf(stderr, "%d %d apiResetCon\n", thread->index, con->fd);
}