-
Notifications
You must be signed in to change notification settings - Fork 2
/
gpsd.c
2544 lines (2349 loc) · 75.5 KB
/
gpsd.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
/*
* This is the main sequence of the gpsd daemon. The IO dispatcher, main
* select loop, and user command handling lives here.
*
* This file is Copyright (c) 2010 by the GPSD project
* BSD terms apply: see the file COPYING in the distribution root for details.
*/
#ifdef __linux__
/* FreeBSD chokes on this */
/* nice() needs _XOPEN_SOURCE, 500 means X/Open 1995 */
#define _XOPEN_SOURCE 500
/* setgroups() needs _DEFAULT_SOURCE or _BSD_SOURCE (glibc-dependent) */
#define _DEFAULT_SOURCE
#define _BSD_SOURCE
#endif /* __linux__ */
/* vsnprintf() needs __DARWIN_C_LEVEL >= 200112L */
#define __DARWIN_C_LEVEL 200112L
/* strlcpy() needs _DARWIN_C_SOURCE */
#define _DARWIN_C_SOURCE
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h> /* for select() */
#include <sys/select.h>
#include <stdio.h>
#include <stdint.h> /* for uint32_t, etc. */
#include <time.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdarg.h>
#include <setjmp.h>
#include <assert.h>
#include <math.h>
#include <syslog.h>
#include <errno.h>
#include <signal.h>
#include <ctype.h>
#include <pwd.h>
#include <grp.h>
#include <fcntl.h>
#include <pthread.h>
#include <netdb.h>
#ifndef AF_UNSPEC
#include <sys/socket.h>
#endif /* AF_UNSPEC */
#ifndef INADDR_ANY
#include <netinet/in.h>
#endif /* INADDR_ANY */
#include <sys/un.h>
#include <arpa/inet.h> /* for htons() and friends */
#include <unistd.h>
#include "gpsd_config.h"
#include "gpsd.h"
#include "sockaddr.h"
#include "gps_json.h"
#include "revision.h"
#include "strfuncs.h"
#if defined(SYSTEMD_ENABLE)
#include "sd_socket.h"
#endif
/*
* The name of a tty device from which to pick up whatever the local
* owning group for tty devices is. Used when we drop privileges.
*/
#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
#define PROTO_TTY "/dev/tty00" /* correct for *BSD */
#else
#define PROTO_TTY "/dev/ttyS0" /* correct for Linux */
#endif
/*
* Timeout policy. We can't rely on clients closing connections
* correctly, so we need timeouts to tell us when it's OK to
* reclaim client fds. COMMAND_TIMEOUT fends off programs
* that open connections and just sit there, not issuing a WATCH or
* doing anything else that triggers a device assignment. Clients
* in watcher or raw mode that don't read their data will get dropped
* when throttled_write() fills up the outbound buffers and the
* NOREAD_TIMEOUT expires.
*
* RELEASE_TIMEOUT sets the amount of time we hold a device
* open after the last subscriber closes it; this is nonzero so a
* client that does open/query/close will have time to come back and
* do another single-shot query, if it wants to, before the device is
* actually closed. The reason this matters is because some Bluetooth
* GPSes not only shut down the GPS receiver on close to save battery
* power, they actually shut down the Bluetooth RF stage as well and
* only re-wake it periodically to see if an attempt to raise the
* device is in progress. The result is that if you close the device
* when it's powered up, a re-open can fail with EIO and needs to be
* tried repeatedly. Better to avoid this...
*
* DEVICE_REAWAKE says how long to wait before repolling after a zero-length
* read. It's there so we avoid spinning forever on an EOF condition.
*
* DEVICE_RECONNECT sets interval on retries when (re)connecting to
* a device.
*/
#define COMMAND_TIMEOUT 60*15
#define NOREAD_TIMEOUT 60*3
#define RELEASE_TIMEOUT 60
#define DEVICE_REAWAKE 0.01
#define DEVICE_RECONNECT 2
#define QLEN 5
/*
* If ntpshm is enabled, we renice the process to this priority level.
* For precise timekeeping increase priority.
*/
#define NICEVAL -10
#if defined(FIXED_PORT_SPEED) || !defined(SOCKET_EXPORT_ENABLE)
/*
* Force nowait in two circumstances:
*
* (1) If we're running with FIXED_PORT_SPEED we're some sort
* of embedded configuration where we don't want to wait for connect
*
* (2) Socket export has been disabled. In this case we have no
* way to know when client apps are watching the export channels,
* so we need to be running all the time.
*/
#define FORCE_NOWAIT
#endif /* defined(FIXED_PORT_SPEED) || !defined(SOCKET_EXPORT_ENABLE) */
#ifdef SOCKET_EXPORT_ENABLE
/* IP version used by the program */
/* AF_UNSPEC: all
* AF_INET: IPv4 only
* AF_INET6: IPv6 only
*/
#ifdef IPV6_ENABLE
static const int af_allowed = AF_UNSPEC;
#else
static const int af_allowed = AF_INET;
#endif
#endif /* SOCKET_EXPORT_ENABLE */
#define AFCOUNT 2
static fd_set all_fds;
static int maxfd;
static int highwater;
#ifndef FORCE_GLOBAL_ENABLE
static bool listen_global = false;
#endif /* FORCE_GLOBAL_ENABLE */
#ifndef FORCE_NOWAIT
#define NOWAIT nowait
static bool nowait = false;
#else /* FORCE_NOWAIT */
#define NOWAIT true
#endif /* FORCE_NOWAIT */
static jmp_buf restartbuf;
static struct gps_context_t context;
#if defined(SYSTEMD_ENABLE)
static int sd_socket_count = 0;
#endif
/* work around the unfinished ipv6 implementation on hurd and OSX <10.6 */
#ifndef IPV6_TCLASS
# if defined(__GNU__)
# define IPV6_TCLASS 61
# elif defined(__APPLE__)
# define IPV6_TCLASS 36
# endif
#endif
static volatile sig_atomic_t signalled;
static void onsig(int sig)
{
/* just set a variable, and deal with it in the main loop */
signalled = (sig_atomic_t) sig;
}
static void typelist(void)
/* list installed drivers and enabled features */
{
const struct gps_type_t **dp;
for (dp = gpsd_drivers; *dp; dp++) {
if ((*dp)->packet_type == COMMENT_PACKET)
continue;
#ifdef RECONFIGURE_ENABLE
if ((*dp)->mode_switcher != NULL)
(void)fputs("n\t", stdout);
else
(void)fputc('\t', stdout);
if ((*dp)->speed_switcher != NULL)
(void)fputs("b\t", stdout);
else
(void)fputc('\t', stdout);
if ((*dp)->rate_switcher != NULL)
(void)fputs("c\t", stdout);
else
(void)fputc('\t', stdout);
if ((*dp)->packet_type > NMEA_PACKET)
(void)fputs("*\t", stdout);
else
(void)fputc('\t', stdout);
#endif /* RECONFIGURE_ENABLE */
(void)puts((*dp)->type_name);
}
(void)printf("# n: mode switch, b: speed switch, "
"c: rate switch, *: non-NMEA packet type.\n");
#if defined(SOCKET_EXPORT_ENABLE)
(void)printf("# Socket export enabled.\n");
#endif
#if defined(SHM_EXPORT_ENABLE)
(void)printf("# Shared memory export enabled.\n");
#endif
#if defined(DBUS_EXPORT_ENABLE)
(void)printf("# DBUS export enabled\n");
#endif
#if defined(TIMEHINT_ENABLE)
(void)printf("# Time service features enabled.\n");
#endif
#if defined(PPS_ENABLE)
(void)printf("# PPS enabled.\n");
#endif
exit(EXIT_SUCCESS);
}
static void usage(void)
{
(void)printf("usage: gpsd [-b] [-n] [-N] [-D n] [-F sockfile] [-G] [-P pidfile] [-S port] [-h] device...\n\
Options include: \n\
-b = bluetooth-safe: open data sources read-only\n"
#ifndef FORCE_NOWAIT
" -n = don't wait for client connects to poll GPS\n"
#endif /* FORCE_NOWAIT */
" -N = don't go into background\n\
-F sockfile = specify control socket location\n"
#ifndef FORCE_GLOBAL_ENABLE
" -G = make gpsd listen on INADDR_ANY\n"
#endif /* FORCE_GLOBAL_ENABLE */
" -P pidfile = set file to record process ID \n\
-D integer (default 0) = set debug level \n\
-S integer (default %s) = set port for daemon \n\
-h = help message \n\
-V = emit version and exit.\n"
#ifdef NETFEED_ENABLE
"A device may be a local serial device for GPS input, or a URL in one \n\
of the following forms:\n\
tcp://host[:port]\n\
udp://host[:port]\n\
{dgpsip|ntrip}://[user:passwd@]host[:port][/stream]\n\
gpsd://host[:port][/device][?protocol]\n\
in which case it specifies an input source for device, DGPS or ntrip data.\n"
#endif /* NETFEED_ENABLE */
"\n\
The following driver types are compiled into this gpsd instance:\n",
DEFAULT_GPSD_PORT);
typelist();
}
#ifdef CONTROL_SOCKET_ENABLE
static socket_t filesock(char *filename)
{
struct sockaddr_un addr;
socket_t sock;
if (BAD_SOCKET(sock = socket(AF_UNIX, SOCK_STREAM, 0))) {
gpsd_log(&context.errout, LOG_ERROR,
"Can't create device-control socket\n");
return -1;
}
(void)strlcpy(addr.sun_path, filename, sizeof(addr.sun_path));
addr.sun_family = (sa_family_t)AF_UNIX;
if (bind(sock, (struct sockaddr *)&addr, (int)sizeof(addr)) < 0) {
gpsd_log(&context.errout, LOG_ERROR,
"can't bind to local socket %s\n", filename);
(void)close(sock);
return -1;
}
if (listen(sock, QLEN) == -1) {
gpsd_log(&context.errout, LOG_ERROR,
"can't listen on local socket %s\n", filename);
(void)close(sock);
return -1;
}
/* coverity[leaked_handle] This is an intentional allocation */
return sock;
}
#endif /* CONTROL_SOCKET_ENABLE */
#define sub_index(s) (int)((s) - subscribers)
#define allocated_device(devp) ((devp)->gpsdata.dev.path[0] != '\0')
#define free_device(devp) (devp)->gpsdata.dev.path[0] = '\0'
#define initialized_device(devp) ((devp)->context != NULL)
/*
* This array fills from the bottom, so as an extreme case you can
* reduce MAX_DEVICES to 1 in the build recipe.
*/
static struct gps_device_t devices[MAX_DEVICES];
static void adjust_max_fd(int fd, bool on)
/* track the largest fd currently in use */
{
if (on) {
if (fd > maxfd)
maxfd = fd;
}
else {
if (fd == maxfd) {
int tfd;
for (maxfd = tfd = 0; tfd < (int)FD_SETSIZE; tfd++)
if (FD_ISSET(tfd, &all_fds))
maxfd = tfd;
}
}
}
#ifdef SOCKET_EXPORT_ENABLE
#ifndef IPTOS_LOWDELAY
#define IPTOS_LOWDELAY 0x10
#endif
static socket_t passivesock_af(int af, char *service, char *tcp_or_udp, int qlen)
/* bind a passive command socket for the daemon */
{
volatile socket_t s;
/*
* af = address family,
* service = IANA protocol name or number.
* tcp_or_udp = TCP or UDP
* qlen = maximum wait-queue length for connections
*/
struct servent *pse;
struct protoent *ppe;
sockaddr_t sat;
int sin_len = 0;
int type, proto, one = 1;
in_port_t port;
char *af_str = "";
const int dscp = IPTOS_LOWDELAY; /* Prioritize packet */
INVALIDATE_SOCKET(s);
if ((pse = getservbyname(service, tcp_or_udp)))
port = ntohs((in_port_t) pse->s_port);
// cppcheck-suppress unreadVariable
else if ((port = (in_port_t) atoi(service)) == 0) {
gpsd_log(&context.errout, LOG_ERROR,
"can't get \"%s\" service entry.\n", service);
return -1;
}
ppe = getprotobyname(tcp_or_udp);
if (strcmp(tcp_or_udp, "udp") == 0) {
type = SOCK_DGRAM;
proto = (ppe) ? ppe->p_proto : IPPROTO_UDP;
} else {
type = SOCK_STREAM;
proto = (ppe) ? ppe->p_proto : IPPROTO_TCP;
}
switch (af) {
case AF_INET:
sin_len = sizeof(sat.sa_in);
memset((char *)&sat.sa_in, 0, sin_len);
sat.sa_in.sin_family = (sa_family_t) AF_INET;
#ifndef FORCE_GLOBAL_ENABLE
if (!listen_global)
sat.sa_in.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
else
#endif /* FORCE_GLOBAL_ENABLE */
sat.sa_in.sin_addr.s_addr = htonl(INADDR_ANY);
sat.sa_in.sin_port = htons(port);
af_str = "IPv4";
/* see PF_INET6 case below */
s = socket(PF_INET, type, proto);
if (s > -1 ) {
/* Set packet priority */
if (setsockopt(s, IPPROTO_IP, IP_TOS, &dscp, sizeof(dscp)) == -1)
gpsd_log(&context.errout, LOG_WARN,
"Warning: SETSOCKOPT TOS failed\n");
}
break;
#ifdef IPV6_ENABLE
case AF_INET6:
sin_len = sizeof(sat.sa_in6);
memset((char *)&sat.sa_in6, 0, sin_len);
sat.sa_in6.sin6_family = (sa_family_t) AF_INET6;
#ifndef FORCE_GLOBAL_ENABLE
if (!listen_global)
sat.sa_in6.sin6_addr = in6addr_loopback;
else
#endif /* FORCE_GLOBAL_ENABLE */
sat.sa_in6.sin6_addr = in6addr_any;
sat.sa_in6.sin6_port = htons(port);
/*
* Traditionally BSD uses "communication domains", named by
* constants starting with PF_ as the first argument for
* select. In practice PF_INET has the same value as AF_INET
* (on BSD and Linux, and probably everywhere else). POSIX
* leaves much of this unspecified, but requires that AF_INET
* be recognized. We follow tradition here.
*/
af_str = "IPv6";
s = socket(PF_INET6, type, proto);
/*
* On some network stacks, including Linux's, an IPv6 socket
* defaults to listening on IPv4 as well. Unless we disable
* this, trying to listen on in6addr_any will fail with the
* address-in-use error condition.
*/
if (s > -1) {
int on = 1;
if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1) {
gpsd_log(&context.errout, LOG_ERROR,
"Error: SETSOCKOPT IPV6_V6ONLY\n");
(void)close(s);
return -1;
}
#ifdef IPV6_TCLASS
/* Set packet priority */
if (setsockopt(s, IPPROTO_IPV6, IPV6_TCLASS, &dscp, sizeof(dscp)) == -1)
gpsd_log(&context.errout, LOG_WARN,
"Warning: SETSOCKOPT TOS failed\n");
#endif /* IPV6_TCLASS */
}
break;
#endif /* IPV6_ENABLE */
default:
gpsd_log(&context.errout, LOG_ERROR,
"unhandled address family %d\n", af);
return -1;
}
gpsd_log(&context.errout, LOG_IO,
"opening %s socket\n", af_str);
if (BAD_SOCKET(s)) {
gpsd_log(&context.errout, LOG_ERROR,
"can't create %s socket\n", af_str);
return -1;
}
if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&one,
(int)sizeof(one)) == -1) {
gpsd_log(&context.errout, LOG_ERROR,
"Error: SETSOCKOPT SO_REUSEADDR\n");
(void)close(s);
return -1;
}
if (bind(s, &sat.sa, sin_len) < 0) {
gpsd_log(&context.errout, LOG_ERROR,
"can't bind to %s port %s, %s\n", af_str,
service, strerror(errno));
if (errno == EADDRINUSE) {
gpsd_log(&context.errout, LOG_ERROR,
"maybe gpsd is already running!\n");
}
(void)close(s);
return -1;
}
if (type == SOCK_STREAM && listen(s, qlen) == -1) {
gpsd_log(&context.errout, LOG_ERROR,
"can't listen on port %s\n", service);
(void)close(s);
return -1;
}
gpsd_log(&context.errout, LOG_SPIN, "passivesock_af() -> %d\n", s);
return s;
}
/* *INDENT-OFF* */
static int passivesocks(char *service, char *tcp_or_udp,
int qlen, socket_t socks[])
{
int numsocks = AFCOUNT;
int i;
for (i = 0; i < AFCOUNT; i++)
INVALIDATE_SOCKET(socks[i]);
#if defined(SYSTEMD_ENABLE)
if (sd_socket_count > 0) {
for (i = 0; i < AFCOUNT && i < sd_socket_count - 1; i++) {
socks[i] = SD_SOCKET_FDS_START + i + 1;
}
return sd_socket_count - 1;
}
#endif
if (AF_UNSPEC == af_allowed || (AF_INET == af_allowed))
socks[0] = passivesock_af(AF_INET, service, tcp_or_udp, qlen);
if (AF_UNSPEC == af_allowed || (AF_INET6 == af_allowed))
socks[1] = passivesock_af(AF_INET6, service, tcp_or_udp, qlen);
for (i = 0; i < AFCOUNT; i++)
if (socks[i] < 0)
numsocks--;
/* Return the number of succesfully opened sockets
* The failed ones are identified by negative values */
return numsocks;
}
/* *INDENT-ON* */
struct subscriber_t
{
int fd; /* client file descriptor. -1 if unused */
time_t active; /* when subscriber last polled for data */
struct policy_t policy; /* configurable bits */
pthread_mutex_t mutex; /* serialize access to fd */
};
#define subscribed(sub, devp) (sub->policy.watcher && (sub->policy.devpath[0]=='\0' || strcmp(sub->policy.devpath, devp->gpsdata.dev.path)==0))
static struct subscriber_t subscribers[MAX_CLIENTS]; /* indexed by client file descriptor */
static void lock_subscriber(struct subscriber_t *sub)
{
(void)pthread_mutex_lock(&sub->mutex);
}
static void unlock_subscriber(struct subscriber_t *sub)
{
(void)pthread_mutex_unlock(&sub->mutex);
}
static struct subscriber_t *allocate_client(void)
/* return the address of a subscriber structure allocated for a new session */
{
int si;
#if UNALLOCATED_FD == 0
#error client allocation code will fail horribly
#endif
for (si = 0; si < NITEMS(subscribers); si++) {
if (subscribers[si].fd == UNALLOCATED_FD) {
subscribers[si].fd = 0; /* mark subscriber as allocated */
return &subscribers[si];
}
}
return NULL;
}
static void detach_client(struct subscriber_t *sub)
/* detach a client and terminate the session */
{
char *c_ip;
lock_subscriber(sub);
if (sub->fd == UNALLOCATED_FD) {
unlock_subscriber(sub);
return;
}
c_ip = netlib_sock2ip(sub->fd);
(void)shutdown(sub->fd, SHUT_RDWR);
gpsd_log(&context.errout, LOG_SPIN,
"close(%d) in detach_client()\n",
sub->fd);
(void)close(sub->fd);
gpsd_log(&context.errout, LOG_INF,
"detaching %s (sub %d, fd %d) in detach_client\n",
c_ip, sub_index(sub), sub->fd);
FD_CLR(sub->fd, &all_fds);
adjust_max_fd(sub->fd, false);
sub->active = 0;
sub->policy.watcher = false;
sub->policy.json = false;
sub->policy.nmea = false;
sub->policy.raw = 0;
sub->policy.scaled = false;
sub->policy.timing = false;
sub->policy.split24 = false;
sub->policy.devpath[0] = '\0';
sub->fd = UNALLOCATED_FD;
unlock_subscriber(sub);
}
static ssize_t throttled_write(struct subscriber_t *sub, char *buf,
size_t len)
/* write to client -- throttle if it's gone or we're close to buffer overrun */
{
ssize_t status;
if (context.errout.debug >= LOG_CLIENT) {
if (isprint((unsigned char) buf[0]))
gpsd_log(&context.errout, LOG_CLIENT,
"=> client(%d): %s\n", sub_index(sub), buf);
else {
#ifndef __clang_analyzer__
char *cp, buf2[MAX_PACKET_LENGTH * 3];
buf2[0] = '\0';
for (cp = buf; cp < buf + len; cp++)
str_appendf(buf2, sizeof(buf2),
"%02x", (unsigned int)(*cp & 0xff));
gpsd_log(&context.errout, LOG_CLIENT,
"=> client(%d): =%s\n", sub_index(sub), buf2);
#endif /* __clang_analyzer__ */
}
}
#if defined(PPS_ENABLE)
gpsd_acquire_reporting_lock();
#endif /* PPS_ENABLE */
status = send(sub->fd, buf, len, 0);
#if defined(PPS_ENABLE)
gpsd_release_reporting_lock();
#endif /* PPS_ENABLE */
if (status == (ssize_t) len)
return status;
else if (status > -1) {
gpsd_log(&context.errout, LOG_INF,
"short write disconnecting client(%d)\n",
sub_index(sub));
detach_client(sub);
return 0;
} else if (errno == EAGAIN || errno == EINTR)
return 0; /* no data written, and errno says to retry */
else if (errno == EBADF)
gpsd_log(&context.errout, LOG_WARN,
"client(%d) has vanished.\n", sub_index(sub));
else if (errno == EWOULDBLOCK
&& time(NULL) - sub->active > NOREAD_TIMEOUT)
gpsd_log(&context.errout, LOG_INF,
"client(%d) timed out.\n", sub_index(sub));
else
gpsd_log(&context.errout, LOG_INF,
"client(%d) write: %s\n",
sub_index(sub), strerror(errno));
detach_client(sub);
return status;
}
static void notify_watchers(struct gps_device_t *device,
bool onjson, bool onpps,
const char *sentence, ...)
/* notify all JSON-watching clients of a given device about an event */
{
va_list ap;
char buf[BUFSIZ];
struct subscriber_t *sub;
va_start(ap, sentence);
(void)vsnprintf(buf, sizeof(buf), sentence, ap);
va_end(ap);
for (sub = subscribers; sub < subscribers + MAX_CLIENTS; sub++)
if (sub->active != 0 && subscribed(sub, device)) {
if ((onjson && sub->policy.json) || (onpps && sub->policy.pps))
(void)throttled_write(sub, buf, strlen(buf));
}
}
#endif /* SOCKET_EXPORT_ENABLE */
static void deactivate_device(struct gps_device_t *device)
/* deactivate device, but leave it in the pool (do not free it) */
{
#ifdef SOCKET_EXPORT_ENABLE
notify_watchers(device, true, false,
"{\"class\":\"DEVICE\",\"path\":\"%s\",\"activated\":0}\r\n",
device->gpsdata.dev.path);
#endif /* SOCKET_EXPORT_ENABLE */
if (!BAD_SOCKET(device->gpsdata.gps_fd)) {
FD_CLR(device->gpsdata.gps_fd, &all_fds);
adjust_max_fd(device->gpsdata.gps_fd, false);
#ifdef NTPSHM_ENABLE
ntpshm_link_deactivate(device);
#endif /* NTPSHM_ENABLE */
gpsd_deactivate(device);
}
}
#if defined(SOCKET_EXPORT_ENABLE) || defined(CONTROL_SOCKET_ENABLE)
/* *INDENT-OFF* */
static struct gps_device_t *find_device(const char
*device_name)
/* find the device block for an existing device name */
{
struct gps_device_t *devp;
for (devp = devices; devp < devices + MAX_DEVICES; devp++)
{
if (allocated_device(devp) && NULL != device_name &&
strcmp(devp->gpsdata.dev.path, device_name) == 0)
return devp;
}
return NULL;
}
/* *INDENT-ON* */
#endif /* defined(SOCKET_EXPORT_ENABLE) || defined(CONTROL_SOCKET_ENABLE) */
static bool open_device( struct gps_device_t *device)
/* open the input device
* return: false on failure
* true on success
*/
{
int activated = -1;
if (NULL == device ) {
return false;
}
activated = gpsd_activate(device, O_OPTIMIZE);
if ( ( 0 > activated ) && ( PLACEHOLDING_FD != activated ) ) {
/* failed to open device, and it is not a /dev/ppsX */
return false;
}
#ifdef NTPSHM_ENABLE
/*
* Now is the right time to grab the shared memory segment(s)
* to communicate the navigation message derived and (possibly)
* 1PPS derived time data to ntpd/chrony.
*/
ntpshm_link_activate(device);
gpsd_log(&context.errout, LOG_INF,
"PPS:%s ntpshm_link_activate: %d\n",
device->gpsdata.dev.path,
device->shm_clock != NULL);
#endif /* NTPSHM_ENABLE */
gpsd_log(&context.errout, LOG_INF,
"device %s activated\n", device->gpsdata.dev.path);
if ( PLACEHOLDING_FD == activated ) {
/* it is a /dev/ppsX, no need to select() it */
return true;
}
FD_SET(device->gpsdata.gps_fd, &all_fds);
adjust_max_fd(device->gpsdata.gps_fd, true);
++highwater;
return true;
}
bool gpsd_add_device(const char *device_name, bool flag_nowait)
/* add a device to the pool; open it right away if in nowait mode
* return: false on failure
* true on success
*/
{
struct gps_device_t *devp;
bool ret = false;
/* we can't handle paths longer than GPS_PATH_MAX, so don't try */
if (strlen(device_name) >= GPS_PATH_MAX) {
gpsd_log(&context.errout, LOG_ERROR,
"ignoring device %s: path length exceeds maximum %d\n",
device_name, GPS_PATH_MAX);
return false;
}
/* stash devicename away for probing when the first client connects */
for (devp = devices; devp < devices + MAX_DEVICES; devp++)
if (!allocated_device(devp)) {
gpsd_init(devp, &context, device_name);
#ifdef NTPSHM_ENABLE
ntpshm_session_init(devp);
#endif /* NTPSHM_ENABLE */
gpsd_log(&context.errout, LOG_INF,
"stashing device %s at slot %d\n",
device_name, (int)(devp - devices));
if (!flag_nowait) {
devp->gpsdata.gps_fd = UNALLOCATED_FD;
ret = true;
} else {
ret = open_device(devp);
}
#ifdef SOCKET_EXPORT_ENABLE
notify_watchers(devp, true, false,
"{\"class\":\"DEVICE\",\"path\":\"%s\",\"activated\":%lf}\r\n",
devp->gpsdata.dev.path, timestamp());
#endif /* SOCKET_EXPORT_ENABLE */
break;
}
return ret;
}
#ifdef CONTROL_SOCKET_ENABLE
static char *snarfline(char *p, char **out)
/* copy the rest of the command line, before CR-LF */
{
char *q;
static char stash[BUFSIZ];
for (q = p; isprint((unsigned char) *p) && !isspace((unsigned char) *p) && (p - q < (ssize_t) sizeof(stash) - 1);
p++)
continue;
(void)memcpy(stash, q, (size_t) (p - q));
stash[p - q] = '\0';
*out = stash;
return p;
}
static void handle_control(int sfd, char *buf)
/* handle privileged commands coming through the control socket */
{
char *stash;
struct gps_device_t *devp;
/*
* The only other place in the code that knows about the format
* of the + and - commands is the gpsd_control() function in
* gpsdctl.c. Be careful about keeping them in sync, or
* hotplugging will have mysterious failures.
*/
if (buf[0] == '-') {
/* remove device named after - */
(void)snarfline(buf + 1, &stash);
gpsd_log(&context.errout, LOG_INF,
"<= control(%d): removing %s\n", sfd, stash);
if ((devp = find_device(stash))) {
deactivate_device(devp);
free_device(devp);
ignore_return(write(sfd, "OK\n", 3));
} else
ignore_return(write(sfd, "ERROR\n", 6));
} else if (buf[0] == '+') {
/* add device named after + */
(void)snarfline(buf + 1, &stash);
if (find_device(stash)) {
gpsd_log(&context.errout, LOG_INF,
"<= control(%d): %s already active \n", sfd,
stash);
ignore_return(write(sfd, "ERROR\n", 6));
} else {
gpsd_log(&context.errout, LOG_INF,
"<= control(%d): adding %s\n", sfd, stash);
if (gpsd_add_device(stash, NOWAIT))
ignore_return(write(sfd, "OK\n", 3));
else {
ignore_return(write(sfd, "ERROR\n", 6));
gpsd_log(&context.errout, LOG_INF,
"control(%d): adding %s failed, too many devices active\n",
sfd, stash);
}
}
} else if (buf[0] == '!') {
/* split line after ! into device=string, send string to device */
char *eq;
(void)snarfline(buf + 1, &stash);
eq = strchr(stash, '=');
if (eq == NULL) {
gpsd_log(&context.errout, LOG_WARN,
"<= control(%d): ill-formed command \n",
sfd);
ignore_return(write(sfd, "ERROR\n", 6));
} else {
*eq++ = '\0';
if ((devp = find_device(stash))) {
if (devp->context->readonly || (devp->sourcetype <= source_blockdev)) {
gpsd_log(&context.errout, LOG_WARN,
"<= control(%d): attempted to write to a read-only device\n",
sfd);
ignore_return(write(sfd, "ERROR\n", 6));
} else {
gpsd_log(&context.errout, LOG_INF,
"<= control(%d): writing to %s \n", sfd,
stash);
if (write(devp->gpsdata.gps_fd, eq, strlen(eq)) <= 0) {
gpsd_log(&context.errout, LOG_WARN,
"<= control(%d): write to device failed\n",
sfd);
ignore_return(write(sfd, "ERROR\n", 6));
} else {
ignore_return(write(sfd, "OK\n", 3));
}
}
} else {
gpsd_log(&context.errout, LOG_INF,
"<= control(%d): %s not active \n", sfd,
stash);
ignore_return(write(sfd, "ERROR\n", 6));
}
}
} else if (buf[0] == '&') {
/* split line after & into dev=hexdata, send unpacked hexdata to dev */
char *eq;
(void)snarfline(buf + 1, &stash);
eq = strchr(stash, '=');
if (eq == NULL) {
gpsd_log(&context.errout, LOG_WARN,
"<= control(%d): ill-formed command\n",
sfd);
ignore_return(write(sfd, "ERROR\n", 6));
} else {
size_t len;
*eq++ = '\0';
len = strlen(eq) + 5;
if ((devp = find_device(stash)) != NULL) {
if (devp->context->readonly || (devp->sourcetype <= source_blockdev)) {
gpsd_log(&context.errout, LOG_WARN,
"<= control(%d): attempted to write to a read-only device\n",
sfd);
ignore_return(write(sfd, "ERROR\n", 6));
} else {
int st;
/* NOTE: this destroys the original buffer contents */
st = gpsd_hexpack(eq, eq, len);
if (st <= 0) {
gpsd_log(&context.errout, LOG_INF,
"<= control(%d): invalid hex string (error %d).\n",
sfd, st);
ignore_return(write(sfd, "ERROR\n", 6));
} else {
gpsd_log(&context.errout, LOG_INF,
"<= control(%d): writing %d bytes fromhex(%s) to %s\n",
sfd, st, eq, stash);
if (write(devp->gpsdata.gps_fd, eq, (size_t) st) <= 0) {
gpsd_log(&context.errout, LOG_WARN,
"<= control(%d): write to device failed\n",
sfd);
ignore_return(write(sfd, "ERROR\n", 6));
} else {
ignore_return(write(sfd, "OK\n", 3));
}
}
}
} else {
gpsd_log(&context.errout, LOG_INF,
"<= control(%d): %s not active\n", sfd,
stash);
ignore_return(write(sfd, "ERROR\n", 6));
}
}
} else if (strstr(buf, "?devices")==buf) {
/* write back devices list followed by OK */
for (devp = devices; devp < devices + MAX_DEVICES; devp++) {
char *path = devp->gpsdata.dev.path;
ignore_return(write(sfd, path, strlen(path)));
ignore_return(write(sfd, "\n", 1));
}
ignore_return(write(sfd, "OK\n", 3));
} else {
/* unknown command */
ignore_return(write(sfd, "ERROR\n", 6));
}
}
#endif /* CONTROL_SOCKET_ENABLE */
#ifdef SOCKET_EXPORT_ENABLE
static bool awaken(struct gps_device_t *device)
/* awaken a device and notify all watchers*/
{
/* open that device */
if (!initialized_device(device)) {
if (!open_device(device)) {
gpsd_log(&context.errout, LOG_WARN,
"%s: open failed\n",
device->gpsdata.dev.path);
free_device(device);
return false;
}
}
if (!BAD_SOCKET(device->gpsdata.gps_fd)) {
gpsd_log(&context.errout, LOG_PROG,
"device %d (fd=%d, path %s) already active.\n",
(int)(device - devices),
device->gpsdata.gps_fd, device->gpsdata.dev.path);
return true;
} else {
if (gpsd_activate(device, O_OPTIMIZE) < 0) {
gpsd_log(&context.errout, LOG_ERROR,
"%s: device activation failed.\n",
device->gpsdata.dev.path);
gpsd_log(&context.errout, LOG_ERROR,
"%s: activation failed, freeing device\n",
device->gpsdata.dev.path);
/* FIXME: works around a crash bug, but prevents retries */
free_device(device);
return false;
} else {
gpsd_log(&context.errout, LOG_RAW,
"flagging descriptor %d in assign_channel()\n",
device->gpsdata.gps_fd);
FD_SET(device->gpsdata.gps_fd, &all_fds);
adjust_max_fd(device->gpsdata.gps_fd, true);
return true;
}
}
}
#ifdef RECONFIGURE_ENABLE
static bool privileged_user(struct gps_device_t *device)
/* is this channel privileged to change a device's behavior? */
{
/* grant user privilege if he's the only one listening to the device */
struct subscriber_t *sub;
int subcount = 0;
for (sub = subscribers; sub < subscribers + MAX_CLIENTS; sub++) {
if (subscribed(sub, device))
subcount++;
}