Debian Codegraph @

net_io.c

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // Part of dump1090, a Mode S message decoder for RTLSDR devices.
2 //
3 // net_io.c: network handling.
4 //
5 // Copyright (c) 2014-2016 Oliver Jowett <[email protected]>
6 //
7 // This file is free software: you may copy, redistribute and/or modify it
8 // under the terms of the GNU General Public License as published by the
9 // Free Software Foundation, either version 2 of the License, or (at your
10 // option) any later version.
11 //
12 // This file is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20 // This file incorporates work covered by the following copyright and
21 // permission notice:
22 //
23 // Copyright (C) 2012 by Salvatore Sanfilippo <[email protected]>
24 //
25 // All rights reserved.
26 //
27 // Redistribution and use in source and binary forms, with or without
28 // modification, are permitted provided that the following conditions are
29 // met:
30 //
31 // * Redistributions of source code must retain the above copyright
32 // notice, this list of conditions and the following disclaimer.
33 //
34 // * Redistributions in binary form must reproduce the above copyright
35 // notice, this list of conditions and the following disclaimer in the
36 // documentation and/or other materials provided with the distribution.
37 //
38 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
39 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
40 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
41 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
42 // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
43 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
44 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
45 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
46 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
47 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
48 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
49
50 #include "dump1090.h"
51
52 /* for PRIX64 */
53 #include <inttypes.h>
54
55 #include <assert.h>
56
57 //
58 // ============================= Networking =============================
59 //
60 // Note: here we disregard any kind of good coding practice in favor of
61 // extreme simplicity, that is:
62 //
63 // 1) We only rely on the kernel buffers for our I/O without any kind of
64 // user space buffering.
65 // 2) We don't register any kind of event handler, from time to time a
66 // function gets called and we accept new connections. All the rest is
67 // handled via non-blocking I/O and manually polling clients to see if
68 // they have something new to share with us when reading is needed.
69
70 static int decodeBinMessage(struct client *c, char *p);
71 static int decodeHexMessage(struct client *c, char *hex);
72 #ifdef ENABLE_WEBSERVER
73 static int handleHTTPRequest(struct client *c, char *p);
74 #endif
75
76 static void send_raw_heartbeat(struct net_service *service);
77 static void send_beast_heartbeat(struct net_service *service);
78 static void send_sbs_heartbeat(struct net_service *service);
79
80 static void writeFATSVEvent(struct modesMessage *mm, struct aircraft *a);
81
82 //
83 //=========================================================================
84 //
85 // Networking "stack" initialization
86 //
87
88 // Init a service with the given read/write characteristics, return the new service.
89 // Doesn't arrange for the service to listen or connect
90 struct net_service *serviceInit(const char *descr, struct net_writer *writer, heartbeat_fn hb, const char *sep, read_fn handler)
91 {
92 struct net_service *service;
93
94 if (!(service = calloc(sizeof(*service), 1))) {
95 fprintf(stderr, "Out of memory allocating service %s\n", descr);
96 exit(1);
97 }
98
99 service->next = Modes.services;
100 Modes.services = service;
101
102 service->descr = descr;
103 service->listener_count = 0;
104 service->connections = 0;
105 service->writer = writer;
106 service->read_sep = sep;
107 service->read_handler = handler;
108
109 if (service->writer) {
110 if (! (service->writer->data = malloc(MODES_OUT_BUF_SIZE)) ) {
111 fprintf(stderr, "Out of memory allocating output buffer for service %s\n", descr);
112 exit(1);
113 }
114
115 service->writer->service = service;
116 service->writer->dataUsed = 0;
117 service->writer->lastWrite = mstime();
118 service->writer->send_heartbeat = hb;
119 }
120
121 return service;
122 }
123
124 // Create a client attached to the given service using the provided socket FD
125 struct client *createSocketClient(struct net_service *service, int fd)
126 {
127 anetSetSendBuffer(Modes.aneterr, fd, (MODES_NET_SNDBUF_SIZE << Modes.net_sndbuf_size));
128 return createGenericClient(service, fd);
129 }
130
131 // Create a client attached to the given service using the provided FD (might not be a socket!)
132 struct client *createGenericClient(struct net_service *service, int fd)
133 {
134 struct client *c;
135
136 anetNonBlock(Modes.aneterr, fd);
137
138 if (!(c = (struct client *) malloc(sizeof(*c)))) {
139 fprintf(stderr, "Out of memory allocating a new %s network client\n", service->descr);
140 exit(1);
141 }
142
143 c->service = service;
144 c->next = Modes.clients;
145 c->fd = fd;
146 c->buflen = 0;
147 Modes.clients = c;
148
149 ++service->connections;
150 if (service->writer && service->connections == 1) {
151 service->writer->lastWrite = mstime(); // suppress heartbeat initially
152 }
153
154 return c;
155 }
156
157 // Initiate an outgoing connection which will use the given service.
158 // Return the new client or NULL if the connection failed
159 struct client *serviceConnect(struct net_service *service, char *addr, int port)
160 {
161 int s;
162 char buf[20];
163
164 // Bleh.
165 snprintf(buf, 20, "%d", port);
166 s = anetTcpConnect(Modes.aneterr, addr, buf);
167 if (s == ANET_ERR)
168 return NULL;
169
170 return createSocketClient(service, s);
171 }
172
173 // Set up the given service to listen on an address/port.
174 // _exits_ on failure!
175 void serviceListen(struct net_service *service, char *bind_addr, char *bind_ports)
176 {
177 int *fds = NULL;
178 int n = 0;
179 char *p, *end;
180 char buf[128];
181
182 if (service->listener_count > 0) {
183 fprintf(stderr, "Tried to set up the service %s twice!\n", service->descr);
184 exit(1);
185 }
186
187 if (!bind_ports || !strcmp(bind_ports, "") || !strcmp(bind_ports, "0"))
188 return;
189
190 p = bind_ports;
191 while (p && *p) {
192 int newfds[16];
193 int nfds, i;
194
195 end = strpbrk(p, ", ");
196 if (!end) {
197 strncpy(buf, p, sizeof(buf));
198 buf[sizeof(buf)-1] = 0;
199 p = NULL;
200 } else {
201 size_t len = end - p;
202 if (len >= sizeof(buf))
203 len = sizeof(buf) - 1;
204 memcpy(buf, p, len);
205 buf[len] = 0;
206 p = end + 1;
207 }
208
209 nfds = anetTcpServer(Modes.aneterr, buf, bind_addr, newfds, sizeof(newfds));
210 if (nfds == ANET_ERR) {
211 fprintf(stderr, "Error opening the listening port %s (%s): %s\n",
212 buf, service->descr, Modes.aneterr);
213 exit(1);
214 }
215
216 fds = realloc(fds, (n+nfds) * sizeof(int));
217 if (!fds) {
218 fprintf(stderr, "out of memory\n");
219 exit(1);
220 }
221
222 for (i = 0; i < nfds; ++i) {
223 anetNonBlock(Modes.aneterr, newfds[i]);
224 fds[n++] = newfds[i];
225 }
226 }
227
228 service->listener_count = n;
229 service->listener_fds = fds;
230 }
231
232 struct net_service *makeBeastInputService(void)
233 {
234 return serviceInit("Beast TCP input", NULL, NULL, NULL, decodeBinMessage);
235 }
236
237 struct net_service *makeFatsvOutputService(void)
238 {
239 return serviceInit("FATSV TCP output", &Modes.fatsv_out, NULL, NULL, NULL);
240 }
241
242 void modesInitNet(void) {
243 struct net_service *s;
244
245 signal(SIGPIPE, SIG_IGN);
246 Modes.clients = NULL;
247 Modes.services = NULL;
248
249 // set up listeners
250 s = serviceInit("Raw TCP output", &Modes.raw_out, send_raw_heartbeat, NULL, NULL);
251 serviceListen(s, Modes.net_bind_address, Modes.net_output_raw_ports);
252
253 s = serviceInit("Beast TCP output", &Modes.beast_out, send_beast_heartbeat, NULL, NULL);
254 serviceListen(s, Modes.net_bind_address, Modes.net_output_beast_ports);
255
256 s = serviceInit("Basestation TCP output", &Modes.sbs_out, send_sbs_heartbeat, NULL, NULL);
257 serviceListen(s, Modes.net_bind_address, Modes.net_output_sbs_ports);
258
259 s = serviceInit("Raw TCP input", NULL, NULL, "\n", decodeHexMessage);
260 serviceListen(s, Modes.net_bind_address, Modes.net_input_raw_ports);
261
262 s = makeBeastInputService();
263 serviceListen(s, Modes.net_bind_address, Modes.net_input_beast_ports);
264
265 #ifdef ENABLE_WEBSERVER
266 s = serviceInit("HTTP server", NULL, NULL, "\r\n\r\n", handleHTTPRequest);
267 serviceListen(s, Modes.net_bind_address, Modes.net_http_ports);
268 #endif
269 }
270 //
271 //=========================================================================
272 //
273 // This function gets called from time to time when the decoding thread is
274 // awakened by new data arriving. This usually happens a few times every second
275 //
276 static struct client * modesAcceptClients(void) {
277 int fd;
278 struct net_service *s;
279
280 for (s = Modes.services; s; s = s->next) {
281 int i;
282 for (i = 0; i < s->listener_count; ++i) {
283 while ((fd = anetTcpAccept(Modes.aneterr, s->listener_fds[i])) >= 0) {
284 createSocketClient(s, fd);
285 }
286 }
287 }
288
289 return Modes.clients;
290 }
291 //
292 //=========================================================================
293 //
294 // On error free the client, collect the structure, adjust maxfd if needed.
295 //
296 static void modesCloseClient(struct client *c) {
297 if (!c->service) {
298 fprintf(stderr, "warning: double close of net client\n");
299 return;
300 }
301
302 // Clean up, but defer removing from the list until modesNetCleanup().
303 // This is because there may be stackframes still pointing at this
304 // client (unpredictably: reading from client A may cause client B to
305 // be freed)
306
307 close(c->fd);
308 c->service->connections--;
309
310 // mark it as inactive and ready to be freed
311 c->fd = -1;
312 c->service = NULL;
313 }
314 //
315 //=========================================================================
316 //
317 // Send the write buffer for the specified writer to all connected clients
318 //
319 static void flushWrites(struct net_writer *writer) {
320 struct client *c;
321
322 for (c = Modes.clients; c; c = c->next) {
323 if (!c->service)
324 continue;
325 if (c->service == writer->service) {
326 #ifndef _WIN32
327 int nwritten = write(c->fd, writer->data, writer->dataUsed);
328 #else
329 int nwritten = send(c->fd, writer->data, writer->dataUsed, 0 );
330 #endif
331 if (nwritten != writer->dataUsed) {
332 modesCloseClient(c);
333 }
334 }
335 }
336
337 writer->dataUsed = 0;
338 writer->lastWrite = mstime();
339 }
340
341 // Prepare to write up to 'len' bytes to the given net_writer.
342 // Returns a pointer to write to, or NULL to skip this write.
343 static void *prepareWrite(struct net_writer *writer, int len) {
344 if (!writer ||
345 !writer->service ||
346 !writer->service->connections ||
347 !writer->data)
348 return NULL;
349
350 if (len > MODES_OUT_BUF_SIZE)
351 return NULL;
352
353 if (writer->dataUsed + len >= MODES_OUT_BUF_SIZE) {
354 // Flush now to free some space
355 flushWrites(writer);
356 }
357
358 return writer->data + writer->dataUsed;
359 }
360
361 // Complete a write previously begun by prepareWrite.
362 // endptr should point one byte past the last byte written
363 // to the buffer returned from prepareWrite.
364 static void completeWrite(struct net_writer *writer, void *endptr) {
365 writer->dataUsed = endptr - writer->data;
366
367 if (writer->dataUsed >= Modes.net_output_flush_size) {
368 flushWrites(writer);
369 }
370 }
371
372 //
373 //=========================================================================
374 //
375 // Write raw output in Beast Binary format with Timestamp to TCP clients
376 //
377 static void modesSendBeastOutput(struct modesMessage *mm) {
378 int msgLen = mm->msgbits / 8;
379 char *p = prepareWrite(&Modes.beast_out, 2 + 2 * (7 + msgLen));
380 char ch;
381 int j;
382 int sig;
383 unsigned char *msg = (Modes.net_verbatim ? mm->verbatim : mm->msg);
384
385 if (!p)
386 return;
387
388 *p++ = 0x1a;
389 if (msgLen == MODES_SHORT_MSG_BYTES)
390 {*p++ = '2';}
391 else if (msgLen == MODES_LONG_MSG_BYTES)
392 {*p++ = '3';}
393 else if (msgLen == MODEAC_MSG_BYTES)
394 {*p++ = '1';}
395 else
396 {return;}
397
398 /* timestamp, big-endian */
399 *p++ = (ch = (mm->timestampMsg >> 40));
400 if (0x1A == ch) {*p++ = ch; }
401 *p++ = (ch = (mm->timestampMsg >> 32));
402 if (0x1A == ch) {*p++ = ch; }
403 *p++ = (ch = (mm->timestampMsg >> 24));
404 if (0x1A == ch) {*p++ = ch; }
405 *p++ = (ch = (mm->timestampMsg >> 16));
406 if (0x1A == ch) {*p++ = ch; }
407 *p++ = (ch = (mm->timestampMsg >> 8));
408 if (0x1A == ch) {*p++ = ch; }
409 *p++ = (ch = (mm->timestampMsg));
410 if (0x1A == ch) {*p++ = ch; }
411
412 sig = round(sqrt(mm->signalLevel) * 255);
413 if (mm->signalLevel > 0 && sig < 1)
414 sig = 1;
415 if (sig > 255)
416 sig = 255;
417 *p++ = ch = (char)sig;
418 if (0x1A == ch) {*p++ = ch; }
419
420 for (j = 0; j < msgLen; j++) {
421 *p++ = (ch = msg[j]);
422 if (0x1A == ch) {*p++ = ch; }
423 }
424
425 completeWrite(&Modes.beast_out, p);
426 }
427
428 static void send_beast_heartbeat(struct net_service *service)
429 {
430 static char heartbeat_message[] = { 0x1a, '1', 0, 0, 0, 0, 0, 0, 0, 0, 0 };
431 char *data;
432
433 if (!service->writer)
434 return;
435
436 data = prepareWrite(service->writer, sizeof(heartbeat_message));
437 if (!data)
438 return;
439
440 memcpy(data, heartbeat_message, sizeof(heartbeat_message));
441 completeWrite(service->writer, data + sizeof(heartbeat_message));
442 }
443
444 //
445 //=========================================================================
446 //
447 // Write raw output to TCP clients
448 //
449 static void modesSendRawOutput(struct modesMessage *mm) {
450 int msgLen = mm->msgbits / 8;
451 char *p = prepareWrite(&Modes.raw_out, msgLen*2 + 15);
452 int j;
453 unsigned char *msg = (Modes.net_verbatim ? mm->verbatim : mm->msg);
454
455 if (!p)
456 return;
457
458 if (Modes.mlat && mm->timestampMsg) {
459 /* timestamp, big-endian */
460 sprintf(p, "@%012" PRIX64,
461 mm->timestampMsg);
462 p += 13;
463 } else
464 *p++ = '*';
465
466 for (j = 0; j < msgLen; j++) {
467 sprintf(p, "%02X", msg[j]);
468 p += 2;
469 }
470
471 *p++ = ';';
472 *p++ = '\n';
473
474 completeWrite(&Modes.raw_out, p);
475 }
476
477 static void send_raw_heartbeat(struct net_service *service)
478 {
479 static char *heartbeat_message = "*0000;\n";
480 char *data;
481 int len = strlen(heartbeat_message);
482
483 if (!service->writer)
484 return;
485
486 data = prepareWrite(service->writer, len);
487 if (!data)
488 return;
489
490 memcpy(data, heartbeat_message, len);
491 completeWrite(service->writer, data + len);
492 }
493
494 //
495 //=========================================================================
496 //
497 // Write SBS output to TCP clients
498 //
499 static void modesSendSBSOutput(struct modesMessage *mm, struct aircraft *a) {
500 char *p;
501 struct timespec now;
502 struct tm stTime_receive, stTime_now;
503 int msgType;
504
505 // For now, suppress non-ICAO addresses
506 if (mm->addr & MODES_NON_ICAO_ADDRESS)
507 return;
508
509 p = prepareWrite(&Modes.sbs_out, 200);
510 if (!p)
511 return;
512
513 //
514 // SBS BS style output checked against the following reference
515 // http://www.homepages.mcb.net/bones/SBS/Article/Barebones42_Socket_Data.htm - seems comprehensive
516 //
517
518 // Decide on the basic SBS Message Type
519 switch (mm->msgtype) {
520 case 4:
521 case 20:
522 msgType = 5;
523 break;
524 break;
525
526 case 5:
527 case 21:
528 msgType = 6;
529 break;
530
531 case 0:
532 case 16:
533 msgType = 7;
534 break;
535
536 case 11:
537 msgType = 8;
538 break;
539
540 case 17:
541 case 18:
542 if (mm->metype >= 1 && mm->metype <= 4) {
543 msgType = 1;
544 } else if (mm->metype >= 5 && mm->metype <= 8) {
545 msgType = 2;
546 } else if (mm->metype >= 9 && mm->metype <= 18) {
547 msgType = 3;
548 } else if (mm->metype == 19) {
549 msgType = 4;
550 } else {
551 return;
552 }
553 break;
554
555 default:
556 return;
557 }
558
559 // Fields 1 to 6 : SBS message type and ICAO address of the aircraft and some other stuff
560 p += sprintf(p, "MSG,%d,1,1,%06X,1,", msgType, mm->addr);
561
562 // Find current system time
563 clock_gettime(CLOCK_REALTIME, &now);
564 localtime_r(&now.tv_sec, &stTime_now);
565
566 // Find message reception time
567 localtime_r(&mm->sysTimestampMsg.tv_sec, &stTime_receive);
568
569 // Fields 7 & 8 are the message reception time and date
570 p += sprintf(p, "%04d/%02d/%02d,", (stTime_receive.tm_year+1900),(stTime_receive.tm_mon+1), stTime_receive.tm_mday);
571 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));
572
573 // Fields 9 & 10 are the current time and date
574 p += sprintf(p, "%04d/%02d/%02d,", (stTime_now.tm_year+1900),(stTime_now.tm_mon+1), stTime_now.tm_mday);
575 p += sprintf(p, "%02d:%02d:%02d.%03u", stTime_now.tm_hour, stTime_now.tm_min, stTime_now.tm_sec, (unsigned) (now.tv_nsec / 1000000U));
576
577 // Field 11 is the callsign (if we have it)
578 if (mm->callsign_valid) {p += sprintf(p, ",%s", mm->callsign);}
579 else {p += sprintf(p, ",");}
580
581 // Field 12 is the altitude (if we have it)
582 if (mm->altitude_valid) {
583 if (Modes.use_gnss) {
584 if (mm->altitude_source == ALTITUDE_GNSS) {
585 p += sprintf(p, ",%dH", mm->altitude);
586 } else if (trackDataValid(&a->gnss_delta_valid)) {
587 p += sprintf(p, ",%dH", mm->altitude + a->gnss_delta);
588 } else {
589 p += sprintf(p, ",%d", mm->altitude);
590 }
591 } else {
592 if (mm->altitude_source == ALTITUDE_BARO) {
593 p += sprintf(p, ",%d", mm->altitude);
594 } else if (trackDataValid(&a->gnss_delta_valid)) {
595 p += sprintf(p, ",%d", mm->altitude - a->gnss_delta);
596 } else {
597 p += sprintf(p, ",");
598 }
599 }
600 } else {
601 p += sprintf(p, ",");
602 }
603
604 // Field 13 is the ground Speed (if we have it)
605 if (mm->speed_valid && mm->speed_source == SPEED_GROUNDSPEED) {
606 p += sprintf(p, ",%d", mm->speed);
607 } else {
608 p += sprintf(p, ",");
609 }
610
611 // Field 14 is the ground Heading (if we have it)
612 if (mm->heading_valid && mm->heading_source == HEADING_TRUE) {
613 p += sprintf(p, ",%d", mm->heading);
614 } else {
615 p += sprintf(p, ",");
616 }
617
618 // Fields 15 and 16 are the Lat/Lon (if we have it)
619 if (mm->cpr_decoded) {
620 p += sprintf(p, ",%1.5f,%1.5f", mm->decoded_lat, mm->decoded_lon);
621 } else {
622 p += sprintf(p, ",,");
623 }
624
625 // Field 17 is the VerticalRate (if we have it)
626 if (mm->vert_rate_valid) {
627 p += sprintf(p, ",%d", mm->vert_rate);
628 } else {
629 p += sprintf(p, ",");
630 }
631
632 // Field 18 is the Squawk (if we have it)
633 if (mm->squawk_valid) {
634 p += sprintf(p, ",%04x", mm->squawk);
635 } else {
636 p += sprintf(p, ",");
637 }
638
639 // Field 19 is the Squawk Changing Alert flag (if we have it)
640 if (mm->alert_valid) {
641 if (mm->alert) {
642 p += sprintf(p, ",-1");
643 } else {
644 p += sprintf(p, ",0");
645 }
646 } else {
647 p += sprintf(p, ",");
648 }
649
650 // Field 20 is the Squawk Emergency flag (if we have it)
651 if (mm->squawk_valid) {
652 if ((mm->squawk == 0x7500) || (mm->squawk == 0x7600) || (mm->squawk == 0x7700)) {
653 p += sprintf(p, ",-1");
654 } else {
655 p += sprintf(p, ",0");
656 }
657 } else {
658 p += sprintf(p, ",");
659 }
660
661 // Field 21 is the Squawk Ident flag (if we have it)
662 if (mm->spi_valid) {
663 if (mm->spi) {
664 p += sprintf(p, ",-1");
665 } else {
666 p += sprintf(p, ",0");
667 }
668 } else {
669 p += sprintf(p, ",");
670 }
671
672 // Field 22 is the OnTheGround flag (if we have it)
673 switch (mm->airground) {
674 case AG_GROUND:
675 p += sprintf(p, ",-1");
676 break;
677 case AG_AIRBORNE:
678 p += sprintf(p, ",0");
679 break;
680 default:
681 p += sprintf(p, ",");
682 break;
683 }
684
685 p += sprintf(p, "\r\n");
686
687 completeWrite(&Modes.sbs_out, p);
688 }
689
690 static void send_sbs_heartbeat(struct net_service *service)
691 {
692 static char *heartbeat_message = "\r\n"; // is there a better one?
693 char *data;
694 int len = strlen(heartbeat_message);
695
696 if (!service->writer)
697 return;
698
699 data = prepareWrite(service->writer, len);
700 if (!data)
701 return;
702
703 memcpy(data, heartbeat_message, len);
704 completeWrite(service->writer, data + len);
705 }
706
707 //
708 //=========================================================================
709 //
710 void modesQueueOutput(struct modesMessage *mm, struct aircraft *a) {
711 int is_mlat = (mm->source == SOURCE_MLAT);
712
713 if (!is_mlat && mm->correctedbits < 2) {
714 // Don't ever forward 2-bit-corrected messages via SBS output.
715 // Don't ever forward mlat messages via SBS output.
716 modesSendSBSOutput(mm, a);
717 }
718
719 if (!is_mlat && (Modes.net_verbatim || mm->correctedbits < 2)) {
720 // Forward 2-bit-corrected messages via raw output only if --net-verbatim is set
721 // Don't ever forward mlat messages via raw output.
722 modesSendRawOutput(mm);
723 }
724
725 if ((!is_mlat || Modes.forward_mlat) && (Modes.net_verbatim || mm->correctedbits < 2)) {
726 // Forward 2-bit-corrected messages via beast output only if --net-verbatim is set
727 // Forward mlat messages via beast output only if --forward-mlat is set
728 modesSendBeastOutput(mm);
729 }
730
731 if (!is_mlat) {
732 writeFATSVEvent(mm, a);
733 }
734 }
735 //
736 //=========================================================================
737 //
738 // This function decodes a Beast binary format message
739 //
740 // The message is passed to the higher level layers, so it feeds
741 // the selected screen output, the network output and so forth.
742 //
743 // If the message looks invalid it is silently discarded.
744 //
745 // The function always returns 0 (success) to the caller as there is no
746 // case where we want broken messages here to close the client connection.
747 //
748 static int decodeBinMessage(struct client *c, char *p) {
749 int msgLen = 0;
750 int j;
751 char ch;
752 unsigned char msg[MODES_LONG_MSG_BYTES];
753 static struct modesMessage zeroMessage;
754 struct modesMessage mm;
755 MODES_NOTUSED(c);
756 memset(&mm, 0, sizeof(mm));
757
758 ch = *p++; /// Get the message type
759 if (0x1A == ch) {p++;}
760
761 if ((ch == '1') && (Modes.mode_ac)) { // skip ModeA/C unless user enables --modes-ac
762 msgLen = MODEAC_MSG_BYTES;
763 } else if (ch == '2') {
764 msgLen = MODES_SHORT_MSG_BYTES;
765 } else if (ch == '3') {
766 msgLen = MODES_LONG_MSG_BYTES;
767 }
768
769 if (msgLen) {
770 mm = zeroMessage;
771
772 // Mark messages received over the internet as remote so that we don't try to
773 // pass them off as being received by this instance when forwarding them
774 mm.remote = 1;
775
776 // Grab the timestamp (big endian format)
777 mm.timestampMsg = 0;
778 for (j = 0; j < 6; j++) {
779 ch = *p++;
780 mm.timestampMsg = mm.timestampMsg << 8 | (ch & 255);
781 if (0x1A == ch) {p++;}
782 }
783
784 // record reception time as the time we read it.
785 clock_gettime(CLOCK_REALTIME, &mm.sysTimestampMsg);
786
787 ch = *p++; // Grab the signal level
788 mm.signalLevel = ((unsigned char)ch / 255.0);
789 mm.signalLevel = mm.signalLevel * mm.signalLevel;
790 if (0x1A == ch) {p++;}
791
792 for (j = 0; j < msgLen; j++) { // and the data
793 msg[j] = ch = *p++;
794 if (0x1A == ch) {p++;}
795 }
796
797 if (msgLen == MODEAC_MSG_BYTES) { // ModeA or ModeC
798 Modes.stats_current.remote_received_modeac++;
799 decodeModeAMessage(&mm, ((msg[0] << 8) | msg[1]));
800 } else {
801 int result;
802
803 Modes.stats_current.remote_received_modes++;
804 result = decodeModesMessage(&mm, msg);
805 if (result < 0) {
806 if (result == -1)
807 Modes.stats_current.remote_rejected_unknown_icao++;
808 else
809 Modes.stats_current.remote_rejected_bad++;
810 return 0;
811 } else {
812 Modes.stats_current.remote_accepted[mm.correctedbits]++;
813 }
814 }
815
816 useModesMessage(&mm);
817 }
818 return (0);
819 }
820 //
821 //=========================================================================
822 //
823 // Turn an hex digit into its 4 bit decimal value.
824 // Returns -1 if the digit is not in the 0-F range.
825 //
826 static int hexDigitVal(int c) {
827 c = tolower(c);
828 if (c >= '0' && c <= '9') return c-'0';
829 else if (c >= 'a' && c <= 'f') return c-'a'+10;
830 else return -1;
831 }
832 //
833 //=========================================================================
834 //
835 // This function decodes a string representing message in raw hex format
836 // like: *8D4B969699155600E87406F5B69F; The string is null-terminated.
837 //
838 // The message is passed to the higher level layers, so it feeds
839 // the selected screen output, the network output and so forth.
840 //
841 // If the message looks invalid it is silently discarded.
842 //
843 // The function always returns 0 (success) to the caller as there is no
844 // case where we want broken messages here to close the client connection.
845 //
846 static int decodeHexMessage(struct client *c, char *hex) {
847 int l = strlen(hex), j;
848 unsigned char msg[MODES_LONG_MSG_BYTES];
849 struct modesMessage mm;
850 static struct modesMessage zeroMessage;
851
852 MODES_NOTUSED(c);
853 mm = zeroMessage;
854
855 // Mark messages received over the internet as remote so that we don't try to
856 // pass them off as being received by this instance when forwarding them
857 mm.remote = 1;
858 mm.signalLevel = 0;
859
860 // Remove spaces on the left and on the right
861 while(l && isspace(hex[l-1])) {
862 hex[l-1] = '\0'; l--;
863 }
864 while(isspace(*hex)) {
865 hex++; l--;
866 }
867
868 // Turn the message into binary.
869 // Accept *-AVR raw @-AVR/BEAST timeS+raw %-AVR timeS+raw (CRC good) <-BEAST timeS+sigL+raw
870 // and some AVR records that we can understand
871 if (hex[l-1] != ';') {return (0);} // not complete - abort
872
873 switch(hex[0]) {
874 case '<': {
875 mm.signalLevel = ((hexDigitVal(hex[13])<<4) | hexDigitVal(hex[14])) / 255.0;
876 mm.signalLevel = mm.signalLevel * mm.signalLevel;
877 hex += 15; l -= 16; // Skip <, timestamp and siglevel, and ;
878 break;}
879
880 case '@': // No CRC check
881 case '%': { // CRC is OK
882 hex += 13; l -= 14; // Skip @,%, and timestamp, and ;
883 break;}
884
885 case '*':
886 case ':': {
887 hex++; l-=2; // Skip * and ;
888 break;}
889
890 default: {
891 return (0); // We don't know what this is, so abort
892 break;}
893 }
894
895 if ( (l != (MODEAC_MSG_BYTES * 2))
896 && (l != (MODES_SHORT_MSG_BYTES * 2))
897 && (l != (MODES_LONG_MSG_BYTES * 2)) )
898 {return (0);} // Too short or long message... broken
899
900 if ( (0 == Modes.mode_ac)
901 && (l == (MODEAC_MSG_BYTES * 2)) )
902 {return (0);} // Right length for ModeA/C, but not enabled
903
904 for (j = 0; j < l; j += 2) {
905 int high = hexDigitVal(hex[j]);
906 int low = hexDigitVal(hex[j+1]);
907
908 if (high == -1 || low == -1) return 0;
909 msg[j/2] = (high << 4) | low;
910 }
911
912 // record reception time as the time we read it.
913 clock_gettime(CLOCK_REALTIME, &mm.sysTimestampMsg);
914
915 if (l == (MODEAC_MSG_BYTES * 2)) { // ModeA or ModeC
916 Modes.stats_current.remote_received_modeac++;
917 decodeModeAMessage(&mm, ((msg[0] << 8) | msg[1]));
918 } else { // Assume ModeS
919 int result;
920
921 Modes.stats_current.remote_received_modes++;
922 result = decodeModesMessage(&mm, msg);
923 if (result < 0) {
924 if (result == -1)
925 Modes.stats_current.remote_rejected_unknown_icao++;
926 else
927 Modes.stats_current.remote_rejected_bad++;
928 return 0;
929 } else {
930 Modes.stats_current.remote_accepted[mm.correctedbits]++;
931 }
932 }
933
934 useModesMessage(&mm);
935 return (0);
936 }
937 //
938 //=========================================================================
939 //
940 // Return a description of planes in json. No metric conversion
941 //
942
943 // usual caveats about function-returning-pointer-to-static-buffer apply
944 static const char *jsonEscapeString(const char *str) {
945 static char buf[1024];
946 const char *in = str;
947 char *out = buf, *end = buf + sizeof(buf) - 10;
948
949 for (; *in && out < end; ++in) {
950 unsigned char ch = *in;
951 if (ch == '"' || ch == '\\') {
952 *out++ = '\\';
953 *out++ = ch;
954 } else if (ch < 32 || ch > 127) {
955 out += snprintf(out, end - out, "\\u%04x", ch);
956 } else {
957 *out++ = ch;
958 }
959 }
960
961 *out++ = 0;
962 return buf;
963 }
964
965 static char *append_flags(char *p, char *end, struct aircraft *a, datasource_t source)
966 {
967 p += snprintf(p, end-p, "[");
968 if (a->squawk_valid.source == source)
969 p += snprintf(p, end-p, "\"squawk\",");
970 if (a->callsign_valid.source == source)
971 p += snprintf(p, end-p, "\"callsign\",");
972 if (a->position_valid.source == source)
973 p += snprintf(p, end-p, "\"lat\",\"lon\",");
974 if (a->altitude_valid.source == source)
975 p += snprintf(p, end-p, "\"altitude\",");
976 if (a->heading_valid.source == source)
977 p += snprintf(p, end-p, "\"track\",");
978 if (a->speed_valid.source == source)
979 p += snprintf(p, end-p, "\"speed\",");
980 if (a->vert_rate_valid.source == source)
981 p += snprintf(p, end-p, "\"vert_rate\",");
982 if (a->category_valid.source == source)
983 p += snprintf(p, end-p, "\"category\",");
984 if (p[-1] != '[')
985 --p;
986 p += snprintf(p, end-p, "]");
987 return p;
988 }
989
990 static const char *addrtype_short_string(addrtype_t type) {
991 switch (type) {
992 case ADDR_ADSB_ICAO:
993 return "adsb_icao";
994 case ADDR_ADSB_ICAO_NT:
995 return "adsb_icao_nt";
996 case ADDR_ADSR_ICAO:
997 return "adsr_icao";
998 case ADDR_TISB_ICAO:
999 return "tisb_icao";
1000 case ADDR_ADSB_OTHER:
1001 return "adsb_other";
1002 case ADDR_ADSR_OTHER:
1003 return "adsr_other";
1004 case ADDR_TISB_OTHER:
1005 return "tisb_other";
1006 case ADDR_TISB_TRACKFILE:
1007 return "tisb_trackfile";
1008 default:
1009 return "unknown";
1010 }
1011 }
1012
1013 char *generateAircraftJson(const char *url_path, int *len) {
1014 uint64_t now = mstime();
1015 struct aircraft *a;
1016 int buflen = 1024; // The initial buffer is incremented as needed
1017 char *buf = (char *) malloc(buflen), *p = buf, *end = buf+buflen;
1018 int first = 1;
1019
1020 MODES_NOTUSED(url_path);
1021
1022 p += snprintf(p, end-p,
1023 "{ \"now\" : %.1f,\n"
1024 " \"messages\" : %u,\n"
1025 " \"aircraft\" : [",
1026 now / 1000.0,
1027 Modes.stats_current.messages_total + Modes.stats_alltime.messages_total);
1028
1029 for (a = Modes.aircrafts; a; a = a->next) {
1030 if (a->modeACflags & MODEAC_MSG_FLAG) { // skip any fudged ICAO records Mode A/C
1031 continue;
1032 }
1033
1034 if (a->messages < 2) { // basic filter for bad decodes
1035 continue;
1036 }
1037
1038 if (first)
1039 first = 0;
1040 else
1041 *p++ = ',';
1042
1043 p += snprintf(p, end-p, "\n {\"hex\":\"%s%06x\"", (a->addr & MODES_NON_ICAO_ADDRESS) ? "~" : "", a->addr & 0xFFFFFF);
1044 if (a->addrtype != ADDR_ADSB_ICAO)
1045 p += snprintf(p, end-p, ",\"type\":\"%s\"", addrtype_short_string(a->addrtype));
1046 if (trackDataValid(&a->squawk_valid))
1047 p += snprintf(p, end-p, ",\"squawk\":\"%04x\"", a->squawk);
1048 if (trackDataValid(&a->callsign_valid))
1049 p += snprintf(p, end-p, ",\"flight\":\"%s\"", jsonEscapeString(a->callsign));
1050 if (trackDataValid(&a->position_valid))
1051 p += snprintf(p, end-p, ",\"lat\":%f,\"lon\":%f,\"nucp\":%u,\"seen_pos\":%.1f", a->lat, a->lon, a->pos_nuc, (now - a->position_valid.updated)/1000.0);
1052 if (trackDataValid(&a->airground_valid) && a->airground_valid.source >= SOURCE_MODE_S_CHECKED && a->airground == AG_GROUND)
1053 p += snprintf(p, end-p, ",\"altitude\":\"ground\"");
1054 else if (trackDataValid(&a->altitude_valid))
1055 p += snprintf(p, end-p, ",\"altitude\":%d", a->altitude);
1056 if (trackDataValid(&a->vert_rate_valid))
1057 p += snprintf(p, end-p, ",\"vert_rate\":%d", a->vert_rate);
1058 if (trackDataValid(&a->heading_valid))
1059 p += snprintf(p, end-p, ",\"track\":%d", a->heading);
1060 if (trackDataValid(&a->speed_valid))
1061 p += snprintf(p, end-p, ",\"speed\":%d", a->speed);
1062 if (trackDataValid(&a->category_valid))
1063 p += snprintf(p, end-p, ",\"category\":\"%02X\"", a->category);
1064
1065 p += snprintf(p, end-p, ",\"mlat\":");
1066 p = append_flags(p, end, a, SOURCE_MLAT);
1067 p += snprintf(p, end-p, ",\"tisb\":");
1068 p = append_flags(p, end, a, SOURCE_TISB);
1069
1070 p += snprintf(p, end-p, ",\"messages\":%ld,\"seen\":%.1f,\"rssi\":%.1f}",
1071 a->messages, (now - a->seen)/1000.0,
1072 10 * log10((a->signalLevel[0] + a->signalLevel[1] + a->signalLevel[2] + a->signalLevel[3] +
1073 a->signalLevel[4] + a->signalLevel[5] + a->signalLevel[6] + a->signalLevel[7] + 1e-5) / 8));
1074
1075 // If we're getting near the end of the buffer, expand it.
1076 if ((end - p) < 512) {
1077 int used = p - buf;
1078 buflen *= 2;
1079 buf = (char *) realloc(buf, buflen);
1080 p = buf+used;
1081 end = buf + buflen;
1082 }
1083 }
1084
1085 p += snprintf(p, end-p, "\n ]\n}\n");
1086 *len = p-buf;
1087 return buf;
1088 }
1089
1090 static char * appendStatsJson(char *p,
1091 char *end,
1092 struct stats *st,
1093 const char *key)
1094 {
1095 int i;
1096
1097 p += snprintf(p, end-p,
1098 "\"%s\":{\"start\":%.1f,\"end\":%.1f",
1099 key,
1100 st->start / 1000.0,
1101 st->end / 1000.0);
1102
1103 if (!Modes.net_only) {
1104 p += snprintf(p, end-p,
1105 ",\"local\":{\"samples_processed\":%llu"
1106 ",\"samples_dropped\":%llu"
1107 ",\"modeac\":%u"
1108 ",\"modes\":%u"
1109 ",\"bad\":%u"
1110 ",\"unknown_icao\":%u",
1111 (unsigned long long)st->samples_processed,
1112 (unsigned long long)st->samples_dropped,
1113 st->demod_modeac,
1114 st->demod_preambles,
1115 st->demod_rejected_bad,
1116 st->demod_rejected_unknown_icao);
1117
1118 for (i=0; i <= Modes.nfix_crc; ++i) {
1119 if (i == 0) p += snprintf(p, end-p, ",\"accepted\":[%u", st->demod_accepted[i]);
1120 else p += snprintf(p, end-p, ",%u", st->demod_accepted[i]);
1121 }
1122
1123 p += snprintf(p, end-p, "]");
1124
1125 if (st->signal_power_sum > 0 && st->signal_power_count > 0)
1126 p += snprintf(p, end-p,",\"signal\":%.1f", 10 * log10(st->signal_power_sum / st->signal_power_count));
1127 if (st->noise_power_sum > 0 && st->noise_power_count > 0)
1128 p += snprintf(p, end-p,",\"noise\":%.1f", 10 * log10(st->noise_power_sum / st->noise_power_count));
1129 if (st->peak_signal_power > 0)
1130 p += snprintf(p, end-p,",\"peak_signal\":%.1f", 10 * log10(st->peak_signal_power));
1131
1132 p += snprintf(p, end-p,",\"strong_signals\":%d}", st->strong_signal_count);
1133 }
1134
1135 if (Modes.net) {
1136 p += snprintf(p, end-p,
1137 ",\"remote\":{\"modeac\":%u"
1138 ",\"modes\":%u"
1139 ",\"bad\":%u"
1140 ",\"unknown_icao\":%u",
1141 st->remote_received_modeac,
1142 st->remote_received_modes,
1143 st->remote_rejected_bad,
1144 st->remote_rejected_unknown_icao);
1145
1146 for (i=0; i <= Modes.nfix_crc; ++i) {
1147 if (i == 0) p += snprintf(p, end-p, ",\"accepted\":[%u", st->remote_accepted[i]);
1148 else p += snprintf(p, end-p, ",%u", st->remote_accepted[i]);
1149 }
1150
1151 p += snprintf(p, end-p, "]}");
1152
1153 #ifdef ENABLE_WEBSERVER
1154 p += snprintf(p, end-p, ",\"http_requests\":%u", st->http_requests);
1155 #endif
1156 }
1157
1158 {
1159 uint64_t demod_cpu_millis = (uint64_t)st->demod_cpu.tv_sec*1000UL + st->demod_cpu.tv_nsec/1000000UL;
1160 uint64_t reader_cpu_millis = (uint64_t)st->reader_cpu.tv_sec*1000UL + st->reader_cpu.tv_nsec/1000000UL;
1161 uint64_t background_cpu_millis = (uint64_t)st->background_cpu.tv_sec*1000UL + st->background_cpu.tv_nsec/1000000UL;
1162
1163 p += snprintf(p, end-p,
1164 ",\"cpr\":{\"surface\":%u"
1165 ",\"airborne\":%u"
1166 ",\"global_ok\":%u"
1167 ",\"global_bad\":%u"
1168 ",\"global_range\":%u"
1169 ",\"global_speed\":%u"
1170 ",\"global_skipped\":%u"
1171 ",\"local_ok\":%u"
1172 ",\"local_aircraft_relative\":%u"
1173 ",\"local_receiver_relative\":%u"
1174 ",\"local_skipped\":%u"
1175 ",\"local_range\":%u"
1176 ",\"local_speed\":%u"
1177 ",\"filtered\":%u}"
1178 ",\"altitude_suppressed\":%u"
1179 ",\"cpu\":{\"demod\":%llu,\"reader\":%llu,\"background\":%llu}"
1180 ",\"tracks\":{\"all\":%u"
1181 ",\"single_message\":%u}"
1182 ",\"messages\":%u}",
1183 st->cpr_surface,
1184 st->cpr_airborne,
1185 st->cpr_global_ok,
1186 st->cpr_global_bad,
1187 st->cpr_global_range_checks,
1188 st->cpr_global_speed_checks,
1189 st->cpr_global_skipped,
1190 st->cpr_local_ok,
1191 st->cpr_local_aircraft_relative,
1192 st->cpr_local_receiver_relative,
1193 st->cpr_local_skipped,
1194 st->cpr_local_range_checks,
1195 st->cpr_local_speed_checks,
1196 st->cpr_filtered,
1197 st->suppressed_altitude_messages,
1198 (unsigned long long)demod_cpu_millis,
1199 (unsigned long long)reader_cpu_millis,
1200 (unsigned long long)background_cpu_millis,
1201 st->unique_aircraft,
1202 st->single_message_aircraft,
1203 st->messages_total);
1204 }
1205
1206 return p;
1207 }
1208
1209 char *generateStatsJson(const char *url_path, int *len) {
1210 struct stats add;
1211 char *buf = (char *) malloc(4096), *p = buf, *end = buf + 4096;
1212
1213 MODES_NOTUSED(url_path);
1214
1215 p += snprintf(p, end-p, "{\n");
1216 p = appendStatsJson(p, end, &Modes.stats_current, "latest");
1217 p += snprintf(p, end-p, ",\n");
1218
1219 p = appendStatsJson(p, end, &Modes.stats_1min[Modes.stats_latest_1min], "last1min");
1220 p += snprintf(p, end-p, ",\n");
1221
1222 p = appendStatsJson(p, end, &Modes.stats_5min, "last5min");
1223 p += snprintf(p, end-p, ",\n");
1224
1225 p = appendStatsJson(p, end, &Modes.stats_15min, "last15min");
1226 p += snprintf(p, end-p, ",\n");
1227
1228 add_stats(&Modes.stats_alltime, &Modes.stats_current, &add);
1229 p = appendStatsJson(p, end, &add, "total");
1230 p += snprintf(p, end-p, "\n}\n");
1231
1232 assert(p <= end);
1233
1234 *len = p-buf;
1235 return buf;
1236 }
1237
1238 //
1239 // Return a description of the receiver in json.
1240 //
1241 char *generateReceiverJson(const char *url_path, int *len)
1242 {
1243 char *buf = (char *) malloc(1024), *p = buf;
1244 int history_size;
1245
1246 MODES_NOTUSED(url_path);
1247
1248 // work out number of valid history entries
1249 if (Modes.json_aircraft_history[HISTORY_SIZE-1].content == NULL)
1250 history_size = Modes.json_aircraft_history_next;
1251 else
1252 history_size = HISTORY_SIZE;
1253
1254 p += sprintf(p, "{ " \
1255 "\"version\" : \"%s\", "
1256 "\"refresh\" : %.0f, "
1257 "\"history\" : %d",
1258 MODES_DUMP1090_VERSION, 1.0*Modes.json_interval, history_size);
1259
1260 if (Modes.json_location_accuracy && (Modes.fUserLat != 0.0 || Modes.fUserLon != 0.0)) {
1261 if (Modes.json_location_accuracy == 1) {
1262 p += sprintf(p, ", " \
1263 "\"lat\" : %.2f, "
1264 "\"lon\" : %.2f",
1265 Modes.fUserLat, Modes.fUserLon); // round to 2dp - about 0.5-1km accuracy - for privacy reasons
1266 } else {
1267 p += sprintf(p, ", " \
1268 "\"lat\" : %.6f, "
1269 "\"lon\" : %.6f",
1270 Modes.fUserLat, Modes.fUserLon); // exact location
1271 }
1272 }
1273
1274 p += sprintf(p, " }\n");
1275
1276 *len = (p - buf);
1277 return buf;
1278 }
1279
1280 char *generateHistoryJson(const char *url_path, int *len)
1281 {
1282 int history_index = -1;
1283
1284 if (sscanf(url_path, "/data/history_%d.json", &history_index) != 1)
1285 return NULL;
1286
1287 if (history_index < 0 || history_index >= HISTORY_SIZE)
1288 return NULL;
1289
1290 if (!Modes.json_aircraft_history[history_index].content)
1291 return NULL;
1292
1293 *len = Modes.json_aircraft_history[history_index].clen;
1294 return strdup(Modes.json_aircraft_history[history_index].content);
1295 }
1296
1297 // Write JSON to file
1298 void writeJsonToFile(const char *file, char * (*generator) (const char *,int*))
1299 {
1300 #ifndef _WIN32
1301 char pathbuf[PATH_MAX];
1302 char tmppath[PATH_MAX];
1303 int fd;
1304 int len = 0;
1305 mode_t mask;
1306 char *content;
1307
1308 if (!Modes.json_dir)
1309 return;
1310
1311 snprintf(tmppath, PATH_MAX, "%s/%s.XXXXXX", Modes.json_dir, file);
1312 tmppath[PATH_MAX-1] = 0;
1313 fd = mkstemp(tmppath);
1314 if (fd < 0)
1315 return;
1316
1317 mask = umask(0);
1318 umask(mask);
1319 fchmod(fd, 0644 & ~mask);
1320
1321 snprintf(pathbuf, PATH_MAX, "/data/%s", file);
1322 pathbuf[PATH_MAX-1] = 0;
1323 content = generator(pathbuf, &len);
1324
1325 if (write(fd, content, len) != len)
1326 goto error_1;
1327
1328 if (close(fd) < 0)
1329 goto error_2;
1330
1331 snprintf(pathbuf, PATH_MAX, "%s/%s", Modes.json_dir, file);
1332 pathbuf[PATH_MAX-1] = 0;
1333 rename(tmppath, pathbuf);
1334 free(content);
1335 return;
1336
1337 error_1:
1338 close(fd);
1339 error_2:
1340 unlink(tmppath);
1341 free(content);
1342 return;
1343 #endif
1344 }
1345
1346
1347 #ifdef ENABLE_WEBSERVER
1348
1349 //
1350 //=========================================================================
1351 //
1352 #define MODES_CONTENT_TYPE_HTML "text/html;charset=utf-8"
1353 #define MODES_CONTENT_TYPE_CSS "text/css;charset=utf-8"
1354 #define MODES_CONTENT_TYPE_JSON "application/json;charset=utf-8"
1355 #define MODES_CONTENT_TYPE_JS "application/javascript;charset=utf-8"
1356 #define MODES_CONTENT_TYPE_GIF "image/gif"
1357
1358 static struct {
1359 char *path;
1360 char * (*handler)(const char*,int*);
1361 char *content_type;
1362 int prefix;
1363 } url_handlers[] = {
1364 { "/data/aircraft.json", generateAircraftJson, MODES_CONTENT_TYPE_JSON, 0 },
1365 { "/data/receiver.json", generateReceiverJson, MODES_CONTENT_TYPE_JSON, 0 },
1366 { "/data/stats.json", generateStatsJson, MODES_CONTENT_TYPE_JSON, 0 },
1367 { "/data/history_", generateHistoryJson, MODES_CONTENT_TYPE_JSON, 1 },
1368 { NULL, NULL, NULL, 0 }
1369 };
1370
1371 //
1372 // Get an HTTP request header and write the response to the client.
1373 // gain here we assume that the socket buffer is enough without doing
1374 // any kind of userspace buffering.
1375 //
1376 // Returns 1 on error to signal the caller the client connection should
1377 // be closed.
1378 //
1379 static int handleHTTPRequest(struct client *c, char *p) {
1380 char hdr[512];
1381 int clen, hdrlen;
1382 int httpver, keepalive;
1383 int statuscode = 500;
1384 const char *statusmsg = "Internal Server Error";
1385 char *url, *content = NULL;
1386 char *ext;
1387 char *content_type = NULL;
1388 int i;
1389
1390 if (Modes.debug & MODES_DEBUG_NET)
1391 printf("\nHTTP request: %s\n", c->buf);
1392
1393 // Minimally parse the request.
1394 httpver = (strstr(p, "HTTP/1.1") != NULL) ? 11 : 10;
1395 if (httpver == 10) {
1396 // HTTP 1.0 defaults to close, unless otherwise specified.
1397 //keepalive = strstr(p, "Connection: keep-alive") != NULL;
1398 } else if (httpver == 11) {
1399 // HTTP 1.1 defaults to keep-alive, unless close is specified.
1400 //keepalive = strstr(p, "Connection: close") == NULL;
1401 }
1402 keepalive = 0;
1403
1404 // Identify he URL.
1405 p = strchr(p,' ');
1406 if (!p) return 1; // There should be the method and a space
1407 url = ++p; // Now this should point to the requested URL
1408 p = strchr(p, ' ');
1409 if (!p) return 1; // There should be a space before HTTP/
1410 *p = '\0';
1411
1412 if (Modes.debug & MODES_DEBUG_NET) {
1413 printf("\nHTTP keep alive: %d\n", keepalive);
1414 printf("HTTP requested URL: %s\n\n", url);
1415 }
1416
1417 // Ditch any trailing query part (AJAX might add one to avoid caching)
1418 p = strchr(url, '?');
1419 if (p) *p = 0;
1420
1421 statuscode = 404;
1422 statusmsg = "Not Found";
1423 for (i = 0; url_handlers[i].path; ++i) {
1424 if ((url_handlers[i].prefix && !strncmp(url, url_handlers[i].path, strlen(url_handlers[i].path))) ||
1425 (!url_handlers[i].prefix && !strcmp(url, url_handlers[i].path))) {
1426 content_type = url_handlers[i].content_type;
1427 content = url_handlers[i].handler(url, &clen);
1428 if (!content)
1429 continue;
1430
1431 statuscode = 200;
1432 statusmsg = "OK";
1433 if (Modes.debug & MODES_DEBUG_NET) {
1434 printf("HTTP: 200: %s -> internal (%d bytes, %s)\n", url, clen, content_type);
1435 }
1436 break;
1437 }
1438 }
1439
1440 if (!content) {
1441 struct stat sbuf;
1442 int fd = -1;
1443 char rp[PATH_MAX], hrp[PATH_MAX];
1444 char getFile[1024];
1445
1446 if (strlen(url) < 2) {
1447 snprintf(getFile, sizeof getFile, "%s/gmap.html", Modes.html_dir); // Default file
1448 } else {
1449 snprintf(getFile, sizeof getFile, "%s/%s", Modes.html_dir, url);
1450 }
1451
1452 if (!realpath(getFile, rp))
1453 rp[0] = 0;
1454 if (!realpath(Modes.html_dir, hrp))
1455 strcpy(hrp, Modes.html_dir);
1456
1457 clen = -1;
1458 content = strdup("Server error occured");
1459 if (!strncmp(hrp, rp, strlen(hrp))) {
1460 if (stat(getFile, &sbuf) != -1 && (fd = open(getFile, O_RDONLY)) != -1) {
1461 content = (char *) realloc(content, sbuf.st_size);
1462 if (read(fd, content, sbuf.st_size) == sbuf.st_size) {
1463 clen = sbuf.st_size;
1464 statuscode = 200;
1465 statusmsg = "OK";
1466 }
1467 }
1468 } else {
1469 errno = ENOENT;
1470 }
1471
1472 if (clen < 0) {
1473 content = realloc(content, 128);
1474 clen = snprintf(content, 128, "Error opening HTML file: %s", strerror(errno));
1475 statuscode = 404;
1476 statusmsg = "Not Found";
1477 }
1478
1479 if (fd != -1) {
1480 close(fd);
1481 }
1482
1483 // Get file extension and content type
1484 content_type = MODES_CONTENT_TYPE_HTML; // Default content type
1485 ext = strrchr(getFile, '.');
1486
1487 if (ext) {
1488 if (!strcmp(ext, ".json")) {
1489 content_type = MODES_CONTENT_TYPE_JSON;
1490 } else if (!strcmp(ext, ".css")) {
1491 content_type = MODES_CONTENT_TYPE_CSS;
1492 } else if (!strcmp(ext, ".js")) {
1493 content_type = MODES_CONTENT_TYPE_JS;
1494 } else if (!strcmp(ext, ".gif")) {
1495 content_type = MODES_CONTENT_TYPE_GIF;
1496 }
1497 }
1498
1499 if (Modes.debug & MODES_DEBUG_NET) {
1500 printf("HTTP: %d %s: %s -> %s (%d bytes, %s)\n", statuscode, statusmsg, url, rp, clen, content_type);
1501 }
1502 }
1503
1504
1505 // Create the header and send the reply
1506 hdrlen = snprintf(hdr, sizeof(hdr),
1507 "HTTP/1.1 %d %s\r\n"
1508 "Server: Dump1090\r\n"
1509 "Content-Type: %s\r\n"
1510 "Connection: %s\r\n"
1511 "Content-Length: %d\r\n"
1512 "Cache-Control: no-cache, must-revalidate\r\n"
1513 "Expires: Sat, 26 Jul 1997 05:00:00 GMT\r\n"
1514 "\r\n",
1515 statuscode, statusmsg,
1516 content_type,
1517 keepalive ? "keep-alive" : "close",
1518 clen);
1519
1520 if (Modes.debug & MODES_DEBUG_NET) {
1521 printf("HTTP Reply header:\n%s", hdr);
1522 }
1523
1524 /* hack hack hack. try to deal with large content */
1525 anetSetSendBuffer(Modes.aneterr, c->fd, clen + hdrlen);
1526
1527 // Send header and content.
1528 #ifndef _WIN32
1529 if ( (write(c->fd, hdr, hdrlen) != hdrlen)
1530 || (write(c->fd, content, clen) != clen) )
1531 #else
1532 if ( (send(c->fd, hdr, hdrlen, 0) != hdrlen)
1533 || (send(c->fd, content, clen, 0) != clen) )
1534 #endif
1535 {
1536 free(content);
1537 return 1;
1538 }
1539 free(content);
1540 Modes.stats_current.http_requests++;
1541 return !keepalive;
1542 }
1543
1544 #endif
1545
1546 //
1547 //=========================================================================
1548 //
1549 // This function polls the clients using read() in order to receive new
1550 // messages from the net.
1551 //
1552 // The message is supposed to be separated from the next message by the
1553 // separator 'sep', which is a null-terminated C string.
1554 //
1555 // Every full message received is decoded and passed to the higher layers
1556 // calling the function's 'handler'.
1557 //
1558 // The handler returns 0 on success, or 1 to signal this function we should
1559 // close the connection with the client in case of non-recoverable errors.
1560 //
1561 static void modesReadFromClient(struct client *c) {
1562 int left;
1563 int nread;
1564 int fullmsg;
1565 int bContinue = 1;
1566 char *s, *e, *p;
1567
1568 while(bContinue) {
1569
1570 fullmsg = 0;
1571 left = MODES_CLIENT_BUF_SIZE - c->buflen;
1572 // If our buffer is full discard it, this is some badly formatted shit
1573 if (left <= 0) {
1574 c->buflen = 0;
1575 left = MODES_CLIENT_BUF_SIZE;
1576 // If there is garbage, read more to discard it ASAP
1577 }
1578 #ifndef _WIN32
1579 nread = read(c->fd, c->buf+c->buflen, left);
1580 #else
1581 nread = recv(c->fd, c->buf+c->buflen, left, 0);
1582 if (nread < 0) {errno = WSAGetLastError();}
1583 #endif
1584
1585 // If we didn't get all the data we asked for, then return once we've processed what we did get.
1586 if (nread != left) {
1587 bContinue = 0;
1588 }
1589
1590 if (nread == 0) { // End of file
1591 modesCloseClient(c);
1592 return;
1593 }
1594
1595 #ifndef _WIN32
1596 if (nread < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) // No data available (not really an error)
1597 #else
1598 if (nread < 0 && errno == EWOULDBLOCK) // No data available (not really an error)
1599 #endif
1600 {
1601 return;
1602 }
1603
1604 if (nread < 0) { // Other errors
1605 modesCloseClient(c);
1606 return;
1607 }
1608
1609 c->buflen += nread;
1610
1611 // Always null-term so we are free to use strstr() (it won't affect binary case)
1612 c->buf[c->buflen] = '\0';
1613
1614 e = s = c->buf; // Start with the start of buffer, first message
1615
1616 if (c->service->read_sep == NULL) {
1617 // This is the Beast Binary scanning case.
1618 // If there is a complete message still in the buffer, there must be the separator 'sep'
1619 // in the buffer, note that we full-scan the buffer at every read for simplicity.
1620
1621 left = c->buflen; // Length of valid search for memchr()
1622 while (left > 1 && ((s = memchr(e, (char) 0x1a, left)) != NULL)) { // The first byte of buffer 'should' be 0x1a
1623 s++; // skip the 0x1a
1624 if (*s == '1') {
1625 e = s + MODEAC_MSG_BYTES + 8; // point past remainder of message
1626 } else if (*s == '2') {
1627 e = s + MODES_SHORT_MSG_BYTES + 8;
1628 } else if (*s == '3') {
1629 e = s + MODES_LONG_MSG_BYTES + 8;
1630 } else {
1631 e = s; // Not a valid beast message, skip
1632 left = &(c->buf[c->buflen]) - e;
1633 continue;
1634 }
1635 // we need to be careful of double escape characters in the message body
1636 for (p = s; p < e; p++) {
1637 if (0x1A == *p) {
1638 p++; e++;
1639 if (e > &(c->buf[c->buflen])) {
1640 break;
1641 }
1642 }
1643 }
1644 left = &(c->buf[c->buflen]) - e;
1645 if (left < 0) { // Incomplete message in buffer
1646 e = s - 1; // point back at last found 0x1a.
1647 break;
1648 }
1649 // Have a 0x1a followed by 1, 2 or 3 - pass message less 0x1a to handler.
1650 if (c->service->read_handler(c, s)) {
1651 modesCloseClient(c);
1652 return;
1653 }
1654 fullmsg = 1;
1655 }
1656 s = e; // For the buffer remainder below
1657
1658 } else {
1659 //
1660 // This is the ASCII scanning case, AVR RAW or HTTP at present
1661 // If there is a complete message still in the buffer, there must be the separator 'sep'
1662 // in the buffer, note that we full-scan the buffer at every read for simplicity.
1663 //
1664 while ((e = strstr(s, c->service->read_sep)) != NULL) { // end of first message if found
1665 *e = '\0'; // The handler expects null terminated strings
1666 if (c->service->read_handler(c, s)) { // Pass message to handler.
1667 modesCloseClient(c); // Handler returns 1 on error to signal we .
1668 return; // should close the client connection
1669 }
1670 s = e + strlen(c->service->read_sep); // Move to start of next message
1671 fullmsg = 1;
1672 }
1673 }
1674
1675 if (fullmsg) { // We processed something - so
1676 c->buflen = &(c->buf[c->buflen]) - s; // Update the unprocessed buffer length
1677 memmove(c->buf, s, c->buflen); // Move what's remaining to the start of the buffer
1678 } else { // If no message was decoded process the next client
1679 return;
1680 }
1681 }
1682 }
1683
1684 #define TSV_MAX_PACKET_SIZE 275
1685
1686 static void writeFATSVEventMessage(struct modesMessage *mm, const char *datafield, unsigned char *data, size_t len)
1687 {
1688 char *p = prepareWrite(&Modes.fatsv_out, TSV_MAX_PACKET_SIZE);
1689 if (!p)
1690 return;
1691
1692 char *end = p + TSV_MAX_PACKET_SIZE;
1693 # define bufsize(_p,_e) ((_p) >= (_e) ? (size_t)0 : (size_t)((_e) - (_p)))
1694
1695 p += snprintf(p, bufsize(p, end), "clock\t%" PRIu64, mstime() / 1000);
1696
1697 if (mm->addr & MODES_NON_ICAO_ADDRESS) {
1698 p += snprintf(p, bufsize(p, end), "\totherid\t%06X", mm->addr & 0xFFFFFF);
1699 } else {
1700 p += snprintf(p, bufsize(p, end), "\thexid\t%06X", mm->addr);
1701 }
1702
1703 if (mm->addrtype != ADDR_ADSB_ICAO) {
1704 p += snprintf(p, bufsize(p, end), "\taddrtype\t%s", addrtype_short_string(mm->addrtype));
1705 }
1706
1707 p += snprintf(p, bufsize(p, end), "\t%s\t", datafield);
1708 for (size_t i = 0; i < len; ++i) {
1709 p += snprintf(p, bufsize(p, end), "%02X", data[i]);
1710 }
1711
1712 p += snprintf(p, bufsize(p, end), "\n");
1713
1714 if (p <= end)
1715 completeWrite(&Modes.fatsv_out, p);
1716 else
1717 fprintf(stderr, "fatsv: output too large (max %d, overran by %d)\n", TSV_MAX_PACKET_SIZE, (int) (p - end));
1718 # undef bufsize
1719 }
1720
1721 static void writeFATSVEvent(struct modesMessage *mm, struct aircraft *a)
1722 {
1723 // Write event records for a couple of message types.
1724
1725 if (!Modes.fatsv_out.service || !Modes.fatsv_out.service->connections) {
1726 return; // not enabled or no active connections
1727 }
1728
1729 if (a->messages < 2) // basic filter for bad decodes
1730 return;
1731
1732 switch (mm->msgtype) {
1733 case 20:
1734 case 21:
1735 if (mm->correctedbits > 0)
1736 break; // only messages we trust a little more
1737
1738 // DF 20/21: Comm-B: emit if they've changed since we last sent them
1739 //
1740 // BDS 1,0: data link capability report
1741 // BDS 3,0: ACAS RA report
1742 if (mm->MB[0] == 0x10 && memcmp(mm->MB, a->fatsv_emitted_bds_10, 7) != 0) {
1743 memcpy(a->fatsv_emitted_bds_10, mm->MB, 7);
1744 writeFATSVEventMessage(mm, "datalink_caps", mm->MB, 7);
1745 }
1746
1747 else if (mm->MB[0] == 0x30 && memcmp(mm->MB, a->fatsv_emitted_bds_30, 7) != 0) {
1748 memcpy(a->fatsv_emitted_bds_30, mm->MB, 7);
1749 writeFATSVEventMessage(mm, "commb_acas_ra", mm->MB, 7);
1750 }
1751
1752 break;
1753
1754 case 17:
1755 case 18:
1756 // DF 17/18: extended squitter
1757 if (mm->metype == 28 && mm->mesub == 2 && memcmp(mm->ME, &a->fatsv_emitted_es_acas_ra, 7) != 0) {
1758 // type 28 subtype 2: ACAS RA report
1759 // first byte has the type/subtype, remaining bytes match the BDS 3,0 format
1760 memcpy(a->fatsv_emitted_es_acas_ra, mm->ME, 7);
1761 writeFATSVEventMessage(mm, "es_acas_ra", mm->ME, 7);
1762 } else if (mm->metype == 31 && (mm->mesub == 0 || mm->mesub == 1) && memcmp(mm->ME, a->fatsv_emitted_es_status, 7) != 0) {
1763 // aircraft operational status
1764 memcpy(a->fatsv_emitted_es_status, mm->ME, 7);
1765 writeFATSVEventMessage(mm, "es_op_status", mm->ME, 7);
1766 } else if (mm->metype == 29 && (mm->mesub == 0 || mm->mesub == 1) && memcmp(mm->ME, a->fatsv_emitted_es_target, 7) != 0) {
1767 // target state and status
1768 memcpy(a->fatsv_emitted_es_target, mm->ME, 7);
1769 writeFATSVEventMessage(mm, "es_target", mm->ME, 7);
1770 }
1771 break;
1772 }
1773 }
1774
1775 typedef enum {
1776 TISB_IDENT = 1,
1777 TISB_SQUAWK = 2,
1778 TISB_ALTITUDE = 4,
1779 TISB_ALTITUDE_GNSS = 8,
1780 TISB_SPEED = 16,
1781 TISB_SPEED_IAS = 32,
1782 TISB_SPEED_TAS = 64,
1783 TISB_POSITION = 128,
1784 TISB_HEADING = 256,
1785 TISB_HEADING_MAGNETIC = 512,
1786 TISB_AIRGROUND = 1024,
1787 TISB_CATEGORY = 2048
1788 } tisb_flags;
1789
1790 static inline unsigned unsigned_difference(unsigned v1, unsigned v2)
1791 {
1792 return (v1 > v2) ? (v1 - v2) : (v2 - v1);
1793 }
1794
1795 static inline unsigned heading_difference(unsigned h1, unsigned h2)
1796 {
1797 unsigned d = unsigned_difference(h1, h2);
1798 return (d < 180) ? d : (360 - d);
1799 }
1800
1801 static void writeFATSV()
1802 {
1803 struct aircraft *a;
1804 uint64_t now;
1805 static uint64_t next_update;
1806
1807 if (!Modes.fatsv_out.service || !Modes.fatsv_out.service->connections) {
1808 return; // not enabled or no active connections
1809 }
1810
1811 now = mstime();
1812 if (now < next_update) {
1813 return;
1814 }
1815
1816 // scan once a second at most
1817 next_update = now + 1000;
1818
1819 for (a = Modes.aircrafts; a; a = a->next) {
1820 int altValid = 0;
1821 int altGNSSValid = 0;
1822 int positionValid = 0;
1823 int speedValid = 0;
1824 int speedIASValid = 0;
1825 int speedTASValid = 0;
1826 int headingValid = 0;
1827 int headingMagValid = 0;
1828 int airgroundValid = 0;
1829 int categoryValid = 0;
1830
1831 uint64_t minAge;
1832
1833 int useful = 0;
1834 int changed = 0;
1835 tisb_flags tisb = 0;
1836
1837 char *p, *end;
1838
1839 if (a->messages < 2) // basic filter for bad decodes
1840 continue;
1841
1842 // don't emit if it hasn't updated since last time
1843 if (a->seen < a->fatsv_last_emitted) {
1844 continue;
1845 }
1846
1847 altValid = trackDataValidEx(&a->altitude_valid, now, 15000, SOURCE_MODE_S); // for non-ADS-B transponders, DF0/4/16/20 are the only sources of altitude data
1848 altGNSSValid = trackDataValidEx(&a->altitude_gnss_valid, now, 15000, SOURCE_MODE_S_CHECKED);
1849 airgroundValid = trackDataValidEx(&a->airground_valid, now, 15000, SOURCE_MODE_S_CHECKED); // for non-ADS-B transponders, only trust DF11 CA field
1850 positionValid = trackDataValidEx(&a->position_valid, now, 15000, SOURCE_MODE_S_CHECKED);
1851 headingValid = trackDataValidEx(&a->heading_valid, now, 15000, SOURCE_MODE_S_CHECKED);
1852 headingMagValid = trackDataValidEx(&a->heading_magnetic_valid, now, 15000, SOURCE_MODE_S_CHECKED);
1853 speedValid = trackDataValidEx(&a->speed_valid, now, 15000, SOURCE_MODE_S_CHECKED);
1854 speedIASValid = trackDataValidEx(&a->speed_ias_valid, now, 15000, SOURCE_MODE_S_CHECKED);
1855 speedTASValid = trackDataValidEx(&a->speed_tas_valid, now, 15000, SOURCE_MODE_S_CHECKED);
1856 categoryValid = trackDataValidEx(&a->category_valid, now, 15000, SOURCE_MODE_S_CHECKED);
1857
1858 // If we are definitely on the ground, suppress any unreliable altitude info.
1859 // When on the ground, ADS-B transponders don't emit an ADS-B message that includes
1860 // altitude, so a corrupted Mode S altitude response from some other in-the-air AC
1861 // might be taken as the "best available altitude" and produce e.g. "airGround G+ alt 31000".
1862 if (airgroundValid && a->airground == AG_GROUND && a->altitude_valid.source < SOURCE_MODE_S_CHECKED)
1863 altValid = 0;
1864
1865 // if it hasn't changed altitude, heading, or speed much,
1866 // don't update so often
1867 changed = 0;
1868 if (altValid && abs(a->altitude - a->fatsv_emitted_altitude) >= 50) {
1869 changed = 1;
1870 }
1871 if (altGNSSValid && abs(a->altitude_gnss - a->fatsv_emitted_altitude_gnss) >= 50) {
1872 changed = 1;
1873 }
1874 if (headingValid && heading_difference(a->heading, a->fatsv_emitted_heading) >= 2) {
1875 changed = 1;
1876 }
1877 if (headingMagValid && heading_difference(a->heading_magnetic, a->fatsv_emitted_heading_magnetic) >= 2) {
1878 changed = 1;
1879 }
1880 if (speedValid && unsigned_difference(a->speed, a->fatsv_emitted_speed) >= 25) {
1881 changed = 1;
1882 }
1883 if (speedIASValid && unsigned_difference(a->speed_ias, a->fatsv_emitted_speed_ias) >= 25) {
1884 changed = 1;
1885 }
1886 if (speedTASValid && unsigned_difference(a->speed_tas, a->fatsv_emitted_speed_tas) >= 25) {
1887 changed = 1;
1888 }
1889
1890 if (airgroundValid && ((a->airground == AG_AIRBORNE && a->fatsv_emitted_airground == AG_GROUND) ||
1891 (a->airground == AG_GROUND && a->fatsv_emitted_airground == AG_AIRBORNE))) {
1892 // Air-ground transition, handle it immediately.
1893 minAge = 0;
1894 } else if (!positionValid) {
1895 // don't send mode S very often
1896 minAge = 30000;
1897 } else if ((airgroundValid && a->airground == AG_GROUND) ||
1898 (altValid && a->altitude < 500 && (!speedValid || a->speed < 200)) ||
1899 (speedValid && a->speed < 100 && (!altValid || a->altitude < 1000))) {
1900 // we are probably on the ground, increase the update rate
1901 minAge = 1000;
1902 } else if (!altValid || a->altitude < 10000) {
1903 // Below 10000 feet, emit up to every 5s when changing, 10s otherwise
1904 minAge = (changed ? 5000 : 10000);
1905 } else {
1906 // Above 10000 feet, emit up to every 10s when changing, 30s otherwise
1907 minAge = (changed ? 10000 : 30000);
1908 }
1909
1910 if ((now - a->fatsv_last_emitted) < minAge)
1911 continue;
1912
1913 p = prepareWrite(&Modes.fatsv_out, TSV_MAX_PACKET_SIZE);
1914 if (!p)
1915 return;
1916
1917 end = p + TSV_MAX_PACKET_SIZE;
1918 # define bufsize(_p,_e) ((_p) >= (_e) ? (size_t)0 : (size_t)((_e) - (_p)))
1919
1920 p += snprintf(p, bufsize(p, end), "clock\t%" PRIu64, (uint64_t)(a->seen / 1000));
1921
1922 if (a->addr & MODES_NON_ICAO_ADDRESS) {
1923 p += snprintf(p, bufsize(p, end), "\totherid\t%06X", a->addr & 0xFFFFFF);
1924 } else {
1925 p += snprintf(p, bufsize(p, end), "\thexid\t%06X", a->addr);
1926 }
1927
1928 if (a->addrtype != ADDR_ADSB_ICAO) {
1929 p += snprintf(p, bufsize(p, end), "\taddrtype\t%s", addrtype_short_string(a->addrtype));
1930 }
1931
1932 if (trackDataValidEx(&a->callsign_valid, now, 15000, SOURCE_MODE_S_CHECKED) && strcmp(a->callsign, " ") != 0 && a->callsign_valid.updated > a->fatsv_last_emitted) {
1933 p += snprintf(p, bufsize(p,end), "\tident\t%s", a->callsign);
1934 switch (a->callsign_valid.source) {
1935 case SOURCE_MODE_S:
1936 p += snprintf(p, bufsize(p,end), "\tiSource\tmodes");
1937 break;
1938 case SOURCE_ADSB:
1939 p += snprintf(p, bufsize(p,end), "\tiSource\tadsb");
1940 break;
1941 case SOURCE_TISB:
1942 p += snprintf(p, bufsize(p,end), "\tiSource\ttisb");
1943 break;
1944 default:
1945 p += snprintf(p, bufsize(p,end), "\tiSource\tunknown");
1946 break;
1947 }
1948
1949 useful = 1;
1950 tisb |= (a->callsign_valid.source == SOURCE_TISB) ? TISB_IDENT : 0;
1951 }
1952
1953 if (trackDataValidEx(&a->squawk_valid, now, 15000, SOURCE_MODE_S) && a->squawk_valid.updated > a->fatsv_last_emitted) {
1954 p += snprintf(p, bufsize(p,end), "\tsquawk\t%04x", a->squawk);
1955 useful = 1;
1956 tisb |= (a->squawk_valid.source == SOURCE_TISB) ? TISB_SQUAWK : 0;
1957 }
1958
1959 // only emit alt, speed, latlon, track if they have been received since the last time
1960 // and are not stale
1961
1962 if (altValid && a->altitude_valid.updated > a->fatsv_last_emitted) {
1963 p += snprintf(p, bufsize(p,end), "\talt\t%d", a->altitude);
1964 a->fatsv_emitted_altitude = a->altitude;
1965 useful = 1;
1966 tisb |= (a->altitude_valid.source == SOURCE_TISB) ? TISB_ALTITUDE : 0;
1967 }
1968
1969 if (altGNSSValid && a->altitude_gnss_valid.updated > a->fatsv_last_emitted) {
1970 p += snprintf(p, bufsize(p,end), "\talt_gnss\t%d", a->altitude_gnss);
1971 a->fatsv_emitted_altitude_gnss = a->altitude_gnss;
1972 useful = 1;
1973 tisb |= (a->altitude_gnss_valid.source == SOURCE_TISB) ? TISB_ALTITUDE_GNSS : 0;
1974 }
1975
1976 if (speedValid && a->speed_valid.updated > a->fatsv_last_emitted) {
1977 p += snprintf(p, bufsize(p,end), "\tspeed\t%d", a->speed);
1978 a->fatsv_emitted_speed = a->speed;
1979 useful = 1;
1980 tisb |= (a->speed_valid.source == SOURCE_TISB) ? TISB_SPEED : 0;
1981 }
1982
1983 if (speedIASValid && a->speed_ias_valid.updated > a->fatsv_last_emitted) {
1984 p += snprintf(p, bufsize(p,end), "\tspeed_ias\t%d", a->speed_ias);
1985 a->fatsv_emitted_speed_ias = a->speed_ias;
1986 useful = 1;
1987 tisb |= (a->speed_ias_valid.source == SOURCE_TISB) ? TISB_SPEED_IAS : 0;
1988 }
1989
1990 if (speedTASValid && a->speed_tas_valid.updated > a->fatsv_last_emitted) {
1991 p += snprintf(p, bufsize(p,end), "\tspeed_tas\t%d", a->speed_tas);
1992 a->fatsv_emitted_speed_tas = a->speed_tas;
1993 useful = 1;
1994 tisb |= (a->speed_tas_valid.source == SOURCE_TISB) ? TISB_SPEED_TAS : 0;
1995 }
1996
1997 if (positionValid && a->position_valid.updated > a->fatsv_last_emitted) {
1998 p += snprintf(p, bufsize(p,end), "\tlat\t%.5f\tlon\t%.5f", a->lat, a->lon);
1999 useful = 1;
2000 tisb |= (a->position_valid.source == SOURCE_TISB) ? TISB_POSITION : 0;
2001 }
2002
2003 if (headingValid && a->heading_valid.updated > a->fatsv_last_emitted) {
2004 p += snprintf(p, bufsize(p,end), "\theading\t%d", a->heading);
2005 a->fatsv_emitted_heading = a->heading;
2006 useful = 1;
2007 tisb |= (a->heading_valid.source == SOURCE_TISB) ? TISB_HEADING : 0;
2008 }
2009
2010 if (headingMagValid && a->heading_magnetic_valid.updated > a->fatsv_last_emitted) {
2011 p += snprintf(p, bufsize(p,end), "\theading_magnetic\t%d", a->heading);
2012 a->fatsv_emitted_heading_magnetic = a->heading_magnetic;
2013 useful = 1;
2014 tisb |= (a->heading_magnetic_valid.source == SOURCE_TISB) ? TISB_HEADING_MAGNETIC : 0;
2015 }
2016
2017 if (airgroundValid && (a->airground == AG_GROUND || a->airground == AG_AIRBORNE) && a->airground_valid.updated > a->fatsv_last_emitted) {
2018 p += snprintf(p, bufsize(p,end), "\tairGround\t%s", a->airground == AG_GROUND ? "G+" : "A+");
2019 a->fatsv_emitted_airground = a->airground;
2020 useful = 1;
2021 tisb |= (a->airground_valid.source == SOURCE_TISB) ? TISB_AIRGROUND : 0;
2022 }
2023
2024 if (categoryValid && (a->category & 0xF0) != 0xA0 && a->category_valid.updated > a->fatsv_last_emitted) {
2025 // interesting category, not a regular aircraft
2026 p += snprintf(p, bufsize(p,end), "\tcategory\t%02X", a->category);
2027 useful = 1;
2028 tisb |= (a->category_valid.source == SOURCE_TISB) ? TISB_CATEGORY : 0;
2029 }
2030
2031 // if we didn't get anything interesting, bail out.
2032 // We don't need to do anything special to unwind prepareWrite().
2033 if (!useful) {
2034 continue;
2035 }
2036
2037 if (tisb != 0) {
2038 p += snprintf(p, bufsize(p,end), "\ttisb\t%d", (int)tisb);
2039 }
2040
2041 p += snprintf(p, bufsize(p,end), "\n");
2042
2043 if (p <= end)
2044 completeWrite(&Modes.fatsv_out, p);
2045 else
2046 fprintf(stderr, "fatsv: output too large (max %d, overran by %d)\n", TSV_MAX_PACKET_SIZE, (int) (p - end));
2047 # undef bufsize
2048
2049 a->fatsv_last_emitted = now;
2050 }
2051 }
2052
2053 //
2054 // Perform periodic network work
2055 //
2056 void modesNetPeriodicWork(void) {
2057 struct client *c, **prev;
2058 struct net_service *s;
2059 uint64_t now = mstime();
2060 int need_flush = 0;
2061
2062 // Accept new connections
2063 modesAcceptClients();
2064
2065 // Read from clients
2066 for (c = Modes.clients; c; c = c->next) {
2067 if (!c->service)
2068 continue;
2069 if (c->service->read_handler)
2070 modesReadFromClient(c);
2071 }
2072
2073 // Generate FATSV output
2074 writeFATSV();
2075
2076 // If we have generated no messages for a while, send
2077 // a heartbeat
2078 if (Modes.net_heartbeat_interval) {
2079 for (s = Modes.services; s; s = s->next) {
2080 if (s->writer &&
2081 s->connections &&
2082 s->writer->send_heartbeat &&
2083 (s->writer->lastWrite + Modes.net_heartbeat_interval) <= now) {
2084 s->writer->send_heartbeat(s);
2085 }
2086 }
2087 }
2088
2089 // If we have data that has been waiting to be written for a while,
2090 // write it now.
2091 for (s = Modes.services; s; s = s->next) {
2092 if (s->writer &&
2093 s->writer->dataUsed &&
2094 (need_flush || (s->writer->lastWrite + Modes.net_output_flush_interval) <= now)) {
2095 flushWrites(s->writer);
2096 }
2097 }
2098
2099 // Unlink and free closed clients
2100 for (prev = &Modes.clients, c = *prev; c; c = *prev) {
2101 if (c->fd == -1) {
2102 // Recently closed, prune from list
2103 *prev = c->next;
2104 free(c);
2105 } else {
2106 prev = &c->next;
2107 }
2108 }
2109 }
2110
2111 //
2112 // =============================== Network IO ===========================
2113 //