summaryrefslogtreecommitdiff
path: root/gpsd.c
blob: ce8ae7d8aa949665dd4a3dbda689598254234698 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
/* $Id$ */
#include <sys/types.h>
#ifndef S_SPLINT_S
#include <sys/socket.h>
#endif /* S_SPLINT_S */
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <syslog.h>
#include <signal.h>
#include <errno.h>
#include <ctype.h>
#include <fcntl.h>
#include <string.h>
#include <netdb.h>
#include <stdarg.h>
#include <setjmp.h>
#include <stdio.h>
#include <assert.h>
#include <pwd.h>
#include <stdbool.h>
#include <math.h>

#include "gpsd_config.h"
#if defined (HAVE_PATH_H)
#include <paths.h>
#else
#if !defined (_PATH_DEVNULL)
#define _PATH_DEVNULL    "/dev/null"
#endif
#endif
#if defined (HAVE_SYS_SELECT_H)
#include <sys/select.h>
#endif
#if defined (HAVE_SYS_STAT_H)
#include <sys/stat.h>
#endif
#if defined(HAVE_SYS_TIME_H)
#include <sys/time.h>
#endif
#ifdef HAVE_SETLOCALE
#include <locale.h>
#endif

#ifdef DBUS_ENABLE
#include <gpsd_dbus.h>
#endif

#include "gpsd.h"
#include "timebase.h"

/*
 * 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

/* Name of (unprivileged) user to change to when we drop privileges. */
#ifndef GPSD_USER
#define GPSD_USER	"nobody"
#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.  ASSIGNMENT_TIMEOUT fends off programs
 * that open connections and just sit there, not issuing a W 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.  Clients in the original polling mode have
 * to be timed out as well.  
 *
 * Finally, 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...
 */
#define ASSIGNMENT_TIMEOUT	60
#define NOREAD_TIMEOUT		60*3
#define POLLER_TIMEOUT  	60*15
#define RELEASE_TIMEOUT		60

#define QLEN			5

/* 
 * If ntpshm is enabled, we renice the process to this priority level.
 * For precise timekeeping increase priority.
 */
#define NICEVAL	-10

/* Needed because 4.x versions of GCC are really annoying */
#define ignore_return(funcall)	assert(funcall != -23)

static fd_set all_fds;
static int maxfd;
static int debuglevel;
static bool in_background = false;
static bool listen_global = false;
static bool nowait = false;
static jmp_buf restartbuf;

/*@ -initallelements -nullassign -nullderef @*/
struct gps_context_t context = {
    .valid	    = 0,
    .readonly	    = false,
    .sentdgps	    = false,
    .netgnss_service  = netgnss_none,
    .fixcnt	    = 0,
    .dsock	    = -1,
    .netgnss_privdata = NULL,
    .rtcmbytes	    = 0,
    .rtcmbuf	    = {'\0'},
    .rtcmtime	    = 0,
    .leap_seconds   = LEAP_SECONDS,
    .century	    = CENTURY_BASE,
#ifdef NTPSHM_ENABLE
    .enable_ntpshm  = false,
    .shmTime	    = {0},
    .shmTimeInuse   = {0},
# ifdef PPS_ENABLE
    .shmTimePPS	    = false,
# endif /* PPS_ENABLE */
#endif /* NTPSHM_ENABLE */
};
/*@ +initallelements +nullassign +nullderef @*/

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 int daemonize(void)
{
    int fd;
    pid_t pid;

    /*@ -type @*/	/* weirdly, splint 3.1.2 is confused by fork() */
    switch (pid = fork()) {
    case -1:
	return -1;
    case 0:	/* child side */
	break;
    default:	/* parent side */
	exit(0);
    }
    /*@ +type @*/

    if (setsid() == -1)
	return -1;
    if (chdir("/") == -1)
	return -1;
    /*@ -nullpass @*/
    if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
	(void)dup2(fd, STDIN_FILENO);
	(void)dup2(fd, STDOUT_FILENO);
	(void)dup2(fd, STDERR_FILENO);
	if (fd > 2)
	    (void)close(fd);
    }
    /*@ +nullpass @*/
    in_background = true;
    return 0;
}

#if defined(PPS_ENABLE)
static pthread_mutex_t report_mutex;
#endif /* PPS_ENABLE */

void gpsd_report(int errlevel, const char *fmt, ... )
/* assemble command in printf(3) style, use stderr or syslog */
{
#ifndef SQUELCH_ENABLE
    if (errlevel <= debuglevel) {
	char buf[BUFSIZ], buf2[BUFSIZ], *sp;
	va_list ap;

#if defined(PPS_ENABLE)
	/*@ -unrecog  (splint has no pthread declarations as yet) @*/
	(void)pthread_mutex_lock(&report_mutex);
	/* +unrecog */
#endif /* PPS_ENABLE */
	(void)strlcpy(buf, "gpsd: ", BUFSIZ);
	va_start(ap, fmt) ;
	(void)vsnprintf(buf + strlen(buf), sizeof(buf)-strlen(buf), fmt, ap);
	va_end(ap);

	buf2[0] = '\0';
	for (sp = buf; *sp != '\0'; sp++)
	    if (isprint(*sp) || (isspace(*sp) && (sp[1]=='\0' || sp[2]=='\0')))
		(void)snprintf(buf2+strlen(buf2), 2, "%c", *sp);
	    else
		(void)snprintf(buf2+strlen(buf2), 6, "\\x%02x", (unsigned)*sp);

	if (in_background)
	    syslog((errlevel == 0) ? LOG_ERR : LOG_NOTICE, "%s", buf2);
	else
	    (void)fputs(buf2, stderr);
#if defined(PPS_ENABLE)
	/*@ -unrecog (splint has no pthread declarations as yet) @*/
	(void)pthread_mutex_unlock(&report_mutex);
	/* +unrecog */
#endif /* PPS_ENABLE */
    }
#endif /* !SQUELCH_ENABLE */
}

static void usage(void)
{
    const struct gps_type_t **dp;

    (void)printf("usage: gpsd [-b] [-n] [-N] [-D n] [-F sockfile] [-P pidfile] [-S port] [-h] device...\n\
  Options include: \n\
  -b		     	    = bluetooth-safe: open data sources read-only\n\
  -n			    = don't wait for client connects to poll GPS\n\
  -N			    = don't go into background\n\
  -F sockfile		    = specify control socket location\n\
  -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\
A device may be a local serial device for GPS input, or a URL of the form:\n\
     {dgpsip|ntrip}://[user:passwd@]host[:port][/stream]\n\
     gpsd://host[:port][/device][?protocol]\n\
in which case it specifies an input source for GPSD, DGPS or ntrip data.\n\
\n\
The following driver types are compiled into this gpsd instance:\n",
	   DEFAULT_GPSD_PORT);
    for (dp = gpsd_drivers; *dp; dp++) {
	(void)printf("    %s\n", (*dp)->type_name);
    }
}

static int passivesock(char *service, char *protocol, int qlen)
{
    struct servent *pse;
    struct protoent *ppe ;	/* splint has a bug here */
    struct sockaddr_in sin;
    int s, type, proto, one = 1;

    /*@ -mustfreefresh +matchanyintegral @*/
    memset((char *) &sin, 0, sizeof(sin));
    sin.sin_family = (sa_family_t)AF_INET;
    if (listen_global)
	sin.sin_addr.s_addr = htonl(INADDR_ANY);
    else
	sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);

    if ((pse = getservbyname(service, protocol)))
	sin.sin_port = htons(ntohs((in_port_t)pse->s_port));
    else if ((sin.sin_port = htons((in_port_t)atoi(service))) == 0) {
	gpsd_report(LOG_ERROR, "Can't get \"%s\" service entry.\n", service);
	return -1;
    }
    ppe = getprotobyname(protocol);
    if (strcmp(protocol, "udp") == 0) {
	type = SOCK_DGRAM;
	/*@i@*/proto = (ppe) ? ppe->p_proto : IPPROTO_UDP;
    } else {
	type = SOCK_STREAM;
	/*@i@*/proto = (ppe) ? ppe->p_proto : IPPROTO_TCP;
    }
    if ((s = socket(PF_INET, type, proto)) == -1) {
	gpsd_report(LOG_ERROR, "Can't create socket\n");
	return -1;
    }
    if (setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&one,(int)sizeof(one)) == -1) {
	gpsd_report(LOG_ERROR, "Error: SETSOCKOPT SO_REUSEADDR\n");
	return -1;
    }
    if (bind(s, (struct sockaddr *) &sin, (int)sizeof(sin)) == -1) {
	gpsd_report(LOG_ERROR, "Can't bind to port %s\n", service);
	if (errno == EADDRINUSE) {
		gpsd_report(LOG_ERROR, "Maybe gpsd is already running!\n");
	}
	return -1;
    }
    if (type == SOCK_STREAM && listen(s, qlen) == -1) {
	gpsd_report(LOG_ERROR, "Can't listen on port %s\n", service);
	return -1;
    }
    return s;
    /*@ +mustfreefresh -matchanyintegral @*/
}

static int filesock(char *filename)
{
    struct sockaddr_un addr;
    int sock;

    /*@ -mayaliasunique @*/
    if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
	gpsd_report(LOG_ERROR, "Can't create device-control socket\n");
	return -1;
    }
    (void)strlcpy(addr.sun_path, filename, 104); /* from sys/un.h */
    /*@i1@*/addr.sun_family = AF_UNIX;
    (void)bind(sock, (struct sockaddr *) &addr,  (socklen_t)sizeof(addr));
    if (listen(sock, QLEN) == -1) {
	gpsd_report(LOG_ERROR, "can't listen on local socket %s\n", filename);
	return -1;
    }
    /*@ +mayaliasunique @*/
    return sock;
}

/*
 * Multi-session support requires us to have two arrays, one of GPS
 * devices currently available and one of client sessions.  The number
 * of slots in each array is limited by the maximum number of client
 * sessions we can have open.
 */

struct gps_device_t channels[MAXDEVICES];
struct subscriber_t subscribers[MAXSUBSCRIBERS];		/* indexed by client file descriptor */

static void adjust_max_fd(int fd, bool on)
/* track the largest fd currently in use */
{
    if (on) {
	if (fd > maxfd)
	    maxfd = fd;
    }
#if !defined(LIMITED_MAX_DEVICES) && !defined(LIMITED_MAX_CLIENT_FD)
    /*
     * I suspect there could be some weird interactions here if
     * either of these were set lower than FD_SETSIZE.  We'll avoid
     * potential bugs by not scavenging in this case at all -- should
     * be OK, as the use case for limiting is SBCs where the limits
     * will be very low (typically 1) and the maximum size of fd
     * set to scan through correspondingly small.
     */
    else {
	if (fd == maxfd) {
	    int tfd;

	    for (maxfd = tfd = 0; tfd < FD_SETSIZE; tfd++)
		if (FD_ISSET(tfd, &all_fds))
		    maxfd = tfd;
	}
    }
#endif /* !defined(LIMITED_MAX_DEVICES) && !defined(LIMITED_MAX_CLIENT_FD) */
}

bool have_fix(struct subscriber_t *whoami)
{
    if (!whoami->device) {
	gpsd_report(LOG_PROG, "Client has no device\n");
	return false;
    }
#define VALIDATION_COMPLAINT(level, legend) \
	gpsd_report(level, legend " (status=%d, mode=%d).\n", \
		    whoami->device->gpsdata.status, whoami->fixbuffer.mode)
    if ((whoami->device->gpsdata.status == STATUS_NO_FIX) != (whoami->fixbuffer.mode == MODE_NO_FIX)) {
	VALIDATION_COMPLAINT(3, "GPS is confused about whether it has a fix");
	return false;
    }
    else if (whoami->device->gpsdata.status > STATUS_NO_FIX && whoami->fixbuffer.mode > MODE_NO_FIX) {
	VALIDATION_COMPLAINT(3, "GPS has a fix");
	return true;
    }
    VALIDATION_COMPLAINT(3, "GPS has no fix");
    return false;
#undef VALIDATION_COMPLAINT
}

static /*@null@*/ /*@observer@*/ struct subscriber_t* allocate_client(void)
{
    int cfd;
    for (cfd = 0; cfd < MAXSUBSCRIBERS; cfd++) {
	if (subscribers[cfd].fd <= 0 ) {
	    gps_clear_fix(&subscribers[cfd].fixbuffer);
	    gps_clear_fix(&subscribers[cfd].oldfix);
	    subscribers[cfd].fd = cfd; /* mark subscriber as allocated */
	    return &subscribers[cfd];
	}
    }
    return NULL;
}

static void detach_client(struct subscriber_t *sub)
{
    char *c_ip;
    if (-1 == sub->fd)
	return;
    c_ip = sock2ip(sub->fd);
    (void)shutdown(sub->fd, SHUT_RDWR);
    (void)close(sub->fd);
    gpsd_report(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->raw = 0;
    sub->watcher = false;
    sub->active = 0;
    /*@i1@*/sub->device = NULL;
    sub->buffer_policy = casoc;
    sub->fd = -1;
}

ssize_t throttled_write(struct subscriber_t *sub, char *buf, ssize_t len)
/* write to client -- throttle if it's gone or we're close to buffer overrun */
{
    ssize_t status;

    if (debuglevel >= 3) {
	if (isprint(buf[0]))
	    gpsd_report(LOG_IO, "=> client(%d): %s", sub_index(sub), buf);
	else {
	    char *cp, buf2[MAX_PACKET_LENGTH*3];
	    buf2[0] = '\0';
	    for (cp = buf; cp < buf + len; cp++)
		(void)snprintf(buf2 + strlen(buf2),
			       sizeof(buf2)-strlen(buf2),
			      "%02x", (unsigned int)(*cp & 0xff));
	    gpsd_report(LOG_IO, "=> client(%d): =%s\r\n", sub_index(sub), buf2);
	}
    }

    status = write(sub->fd, buf, (size_t)len);
    if (status == len )
	return status;
    else if (status > -1) {
	gpsd_report(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_report(LOG_WARN, "client(%d) has vanished.\n", sub_index(sub));
    else if (errno == EWOULDBLOCK && timestamp() - sub->active > NOREAD_TIMEOUT)
	gpsd_report(LOG_INF, "client(%d) timed out.\n", sub_index(sub));
    else
	gpsd_report(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, char *sentence, ...)
/* notify all clients watching a given device of an event */
{
    struct subscriber_t *sub;
    va_list ap;
    char buf[BUFSIZ];

    va_start(ap, sentence) ;
    (void)vsnprintf(buf, sizeof(buf), sentence, ap);
    va_end(ap);

    for (sub = subscribers; sub < subscribers + MAXSUBSCRIBERS; sub++)
	if (sub->watcher != 0 && sub->device == device)
	    (void)throttled_write(sub, buf, (ssize_t)strlen(buf));
}

static void raw_hook(struct gps_data_t *ud,
		     char *sentence, size_t len, int level)
/* hook to be executed on each incoming packet */
{
    struct subscriber_t *sub;

    for (sub = subscribers; sub < subscribers + MAXSUBSCRIBERS; sub++) {
	/* copy raw NMEA sentences from GPS to clients in raw mode */
	if (sub->raw == level &&
	    sub->device!=NULL &&
	    strcmp(ud->gps_device, sub->device->gpsdata.gps_device)==0)
	    (void)throttled_write(sub, sentence, (ssize_t)len);
    }
}

/*@ -globstate @*/
/*@null@*/ /*@observer@*/struct gps_device_t *find_device(char *device_name)
/* find the channel block for an existing device name */
{
    struct gps_device_t *chp;

    for (chp = channels; chp < channels + MAXDEVICES; chp++)
	if (allocated_channel(chp) && strcmp(chp->gpsdata.gps_device, device_name)==0)
	    return chp;
    return NULL;
}

/*@ -nullret @*/
/*@ -statictrans @*/
static /*@null@*/ struct gps_device_t *open_device(char *device_name)
/* open and initialize a new channel block */
{
    struct gps_device_t *chp;

    /* special case: source may be a URI to a remote GNSS or DGPS service */
    if (netgnss_uri_check(device_name)) {
	int dsock = netgnss_uri_open(&context, device_name);
	if (dsock >= 0) {
	    FD_SET(dsock, &all_fds);
	    adjust_max_fd(dsock, true);
	}
	if (context.netgnss_service != netgnss_remotegpsd)
	    return &channels[0]; /* shaky, but only 0 versus nonzero is tested */
    }

    /* normal case: set up GPS service */
    for (chp = channels; chp < channels + MAXDEVICES; chp++)
	if (!allocated_channel(chp) || (strcmp(chp->gpsdata.gps_device, device_name)==0 && !initialized_channel(chp))){
	    goto found;
	}
    return NULL;
found:
    gpsd_init(chp, &context, device_name);
    chp->gpsdata.raw_hook = raw_hook;
    /*
     * Bring the device all the way so we'll sniff packets from it and
     * discover up front whether it's a GPS source or an RTCM source.
     * Otherwise clients trying to bind to a specific type won't know
     * what source types are actually available.  If we're in nowait mode
     * the device has to be configured now; otherwise, it can wait.
     */
    if (gpsd_activate(chp, nowait) < 0)
	return NULL;
    FD_SET(chp->gpsdata.gps_fd, &all_fds);
    adjust_max_fd(chp->gpsdata.gps_fd, true);
    return chp;
}

static /*@null@*/ struct gps_device_t *add_device(char *device_name)
/* add a device to the pool; open it right away if in nowait mode */
{
    if (nowait)
	return open_device(device_name);
    else {
	struct gps_device_t *chp;
	/* 
	 * Stash the devicename away for probing when the first client connects.
	 * Zero the context pointer so we know gpsd_init() hasn't been called.
	 */
	for (chp = channels; chp < channels + MAXDEVICES; chp++)
	    if (!allocated_channel(chp)) {
		(void)strlcpy(chp->gpsdata.gps_device, device_name, PATH_MAX);
		/*@ -mustfreeonly @*/
		chp->context = NULL;
		/*@ +mustfreeonly @*/
		return chp;
	    }
	return NULL;
    }
}

/*@ +nullret @*/
/*@ +statictrans @*/
/*@ +globstate @*/

static bool allocation_filter(struct gps_device_t *channel,
			      struct subscriber_t *user)
/* does specified channel match the user's type criteria? */
{
    /*
     * Might be we don't know the device type attached to this yet.
     * If we don't, open it and sniff packets until we do. 
     */
    if (allocated_channel(channel) && !initialized_channel(channel)) {
	if (open_device(channel->gpsdata.gps_device) == NULL) {
	    free_channel(channel);
	    return false;
	}
    }

    gpsd_report(LOG_PROG, 
		"User requires %d, channel %d type is %d\n", 
		user->requires, (int)(channel - channels), channel->packet.type);
    /* we might have type constraints */
    if (user->requires == ANY)
	return true;
    else if (user->requires==RTCM104v2 && (channel->packet.type==RTCM2_PACKET))
	return true;
    else if (user->requires == GPS
	     && (channel->packet.type!=RTCM2_PACKET) && (channel->packet.type!=BAD_PACKET))
	return true;
    else
	return false;	/* BAD_PACKET case will fall through to here */
}

#define USER_INDEX (int)(user - subscribers)
/*@ -branchstate -usedef -globstate @*/
bool assign_channel(struct subscriber_t *user)
{
    bool was_unassigned = (user->device == NULL);
    /* if subscriber has no device... */
    if (was_unassigned) {
	double most_recent = 0;
	int fix_quality = 0;
	struct gps_device_t *channel;

	gpsd_report(LOG_PROG, "client(%d): assigning channel...\n", USER_INDEX);
	/* ...connect him to the most recently active device */
	/*@ -mustfreeonly @*/
	for(channel = channels; channel<channels+MAXDEVICES; channel++)
	    if (allocated_channel(channel)) {
		if (allocation_filter(channel, user)) {
		    /*
		     * Grab device if it's:
		     * (1) The first we've seen,
		     * (2) Has a better quality fix than we've seen yet,
		     * (3) Fix of same quality we've seen but more recent.
		     */
		    if (user->device == NULL) {
			user->device = channel;
			most_recent = channel->gpsdata.sentence_time;
		    } else if (channel->gpsdata.status > fix_quality) {
			user->device = channel;
			fix_quality = channel->gpsdata.status;
		    } else if (channel->gpsdata.status == fix_quality && 
			       channel->gpsdata.sentence_time >= most_recent) {
			user->device = channel;
			most_recent = channel->gpsdata.sentence_time;
		    }
		}
	    }
	/*@ +mustfreeonly @*/
    }

    if (user->device == NULL) {
	gpsd_report(LOG_ERROR, "client(%d): channel assignment failed.\n",
		    USER_INDEX);
	return false;
    }

    /* and open that device */
    if (user->device->gpsdata.gps_fd != -1)
	gpsd_report(LOG_PROG,"client(%d): channel %d already active.\n",
		    USER_INDEX, user->device->gpsdata.gps_fd);
    else {
	if (gpsd_activate(user->device, true) < 0) {

	    gpsd_report(LOG_ERROR, "client(%d): channel activation failed.\n",
			USER_INDEX);
	    return false;
	} else {
	    gpsd_report(LOG_RAW, "flagging descriptor %d in assign_channel\n",
			user->device->gpsdata.gps_fd);
	    FD_SET(user->device->gpsdata.gps_fd, &all_fds);
	    adjust_max_fd(user->device->gpsdata.gps_fd, true);
	    if (user->watcher && !user->tied) {
		/*@ -sefparams @*/
		ignore_return(write(user->fd, "GPSD,F=", 7));
		ignore_return(write(user->fd,
			     user->device->gpsdata.gps_device,
				    strlen(user->device->gpsdata.gps_device)));
		ignore_return(write(user->fd, "\r\n", 2));
		/*@ +sefparams @*/
	    }
	}
    }

    if (user->watcher && was_unassigned) {
	char buf[NMEA_MAX];
	(void)snprintf(buf, sizeof(buf), "GPSD,X=%f,I=%s\r\n",
		       timestamp(), gpsd_id(user->device));
	/*@ -sefparams +matchanyintegral @*/
	ignore_return(write(user->fd, buf, strlen(buf)));
	/*@ +sefparams -matchanyintegral @*/

    }
    return true;
}
/*@ +branchstate +usedef +globstate @*/

#ifdef RTCM104_SERVICE
static int handle_rtcm_request(struct subscriber_t* sub UNUSED, char *buf UNUSED, int buflen UNUSED)
/* interpret a client request; cfd is the socket back to the client */
{
    return 0;	/* not actually interpreting these yet */
}
#endif /* RTCM104_SERVICE */

/*@ observer @*/ char *snarfline(char *p, /*@out@*/char **out)
/* copy the rest of the command line, before CR-LF */
{
    char *q;
    static char	stash[BUFSIZ];

    /*@ -temptrans -mayaliasunique @*/
    for (q = p; isprint(*p) && !isspace(*p) && /*@i@*/(p-q < BUFSIZ-1); p++)
	continue;
    (void)memcpy(stash, q, (size_t)(p-q));
    stash[p-q] = '\0';
    *out = stash;
    return p;
    /*@ +temptrans +mayaliasunique @*/
}

#ifdef ALLOW_RECONFIGURE
bool privileged_user(struct subscriber_t *who)
/* is this user privileged to change the GPS's behavior? */
{
    struct subscriber_t *sub;
    int subscribercount = 0;

    /* grant user privilege if he's the only one listening to the device */
    for (sub = subscribers; sub < subscribers + MAXSUBSCRIBERS; sub++)
	if (sub->device == who->device)
	    subscribercount++;
    return (subscribercount == 1);
}
#endif /* ALLOW_CONFIGURE */

static void handle_control(int sfd, char *buf)
/* handle privileged commands coming through the control socket */
{
    char	*p, *stash, *eq;
    struct gps_device_t	*chp;
    int cfd;

    /*@ -sefparams @*/
    if (buf[0] == '-') {
	p = snarfline(buf+1, &stash);
	gpsd_report(LOG_INF, "<= control(%d): removing %s\n", sfd, stash);
	if ((chp = find_device(stash))) {
	    if (chp->gpsdata.gps_fd > 0) {
		FD_CLR(chp->gpsdata.gps_fd, &all_fds);
		adjust_max_fd(chp->gpsdata.gps_fd, false);
	    }
	    notify_watchers(chp, "X=0\r\n");
	    for (cfd = 0; cfd < MAXSUBSCRIBERS; cfd++)
		if (subscribers[cfd].device == chp)
		    subscribers[cfd].device = NULL;
	    gpsd_wrap(chp);
	    chp->gpsdata.gps_fd = -1;	/* device is already disconnected */
	    /*@i@*/free_channel(chp);	/* modifying observer storage */
	    ignore_return(write(sfd, "OK\n", 3));
	} else
	    ignore_return(write(sfd, "ERROR\n", 6));
    } else if (buf[0] == '+') {
	p = snarfline(buf+1, &stash);
	if (find_device(stash)) {
	    gpsd_report(LOG_INF,"<= control(%d): %s already active \n", sfd, stash);
	    ignore_return(write(sfd, "ERROR\n", 6));
	} else {
	    gpsd_report(LOG_INF,"<= control(%d): adding %s \n", sfd, stash);
	    if (add_device(stash))
		ignore_return(write(sfd, "OK\n", 3));
	    else
		ignore_return(write(sfd, "ERROR\n", 6));
	}
    } else if (buf[0] == '!') {
	p = snarfline(buf+1, &stash);
	eq = strchr(stash, '=');
	if (eq == NULL) {
	    gpsd_report(LOG_WARN,"<= control(%d): ill-formed command \n", sfd);
	    ignore_return(write(sfd, "ERROR\n", 6));
	} else {
	    *eq++ = '\0';
	    if ((chp = find_device(stash))) {
		gpsd_report(LOG_INF,"<= control(%d): writing to %s \n", sfd, stash);
		ignore_return(write(chp->gpsdata.gps_fd, eq, strlen(eq)));
		ignore_return(write(sfd, "OK\n", 3));
	    } else {
		gpsd_report(LOG_INF,"<= control(%d): %s not active \n", sfd, stash);
		ignore_return(write(sfd, "ERROR\n", 6));
	    }
	}
    } else if (buf[0] == '&') {
	p = snarfline(buf+1, &stash);
	eq = strchr(stash, '=');
	if (eq == NULL) {
	    gpsd_report(LOG_WARN,"<= control(%d): ill-formed command \n", sfd);
	    ignore_return(write(sfd, "ERROR\n", 6));
	} else {
	    size_t len;
	    int st;
	    *eq++ = '\0';
	    len = strlen(eq)+5;
	    if ((chp = find_device(stash)) != NULL) {
		/* NOTE: this destroys the original buffer contents */
		st = gpsd_hexpack(eq, eq, len);
		if (st <= 0) {
		    gpsd_report(LOG_INF,"<= control(%d): invalid hex string (error %d).\n", sfd, st);
		    ignore_return(write(sfd, "ERROR\n", 6));
		}
		else
		{
		    gpsd_report(LOG_INF,"<= control(%d): writing %d bytes fromhex(%s) to %s\n", sfd, st, eq, stash);
		    ignore_return(write(chp->gpsdata.gps_fd, eq, (size_t)st));
		    ignore_return(write(sfd, "OK\n", 3));
		}
	    } else {
		gpsd_report(LOG_INF,"<= control(%d): %s not active\n", sfd, stash);
		ignore_return(write(sfd, "ERROR\n", 6));
	    }
	}
    }
    /*@ +sefparams @*/
}

/*@ -mustfreefresh @*/
int main(int argc, char *argv[])
{
    static char *pid_file = NULL;
    static int st, csock = -1;
    static gps_mask_t changed;
    static char *gpsd_service = NULL;
#ifdef RTCM104_SERVICE
    static char *rtcm_service = NULL;
    static int nsock;
#endif /* RTCM104_SERVICE */
    static char *control_socket = NULL;
    struct gps_device_t *channel;
    struct sockaddr_in fsin;
    fd_set rfds, control_fds;
    int i, option, msock, cfd, dfd;
    bool go_background = true;
    struct timeval tv;
#ifdef RTCM104_SERVICE
    struct gps_device_t *gps;
#endif /* RTCM104_SERVICE */
    struct subscriber_t *sub;
    const struct gps_type_t **dp;

#ifdef PPS_ENABLE
    pthread_mutex_init(&report_mutex, NULL);
#endif /* PPS_ENABLE */

#ifdef HAVE_SETLOCALE
    (void)setlocale(LC_NUMERIC, "C");
#endif
    debuglevel = 0;
    gpsd_hexdump_level = 0;
    while ((option = getopt(argc, argv, "F:D:S:bGhlNnP:V"
#ifdef RTCM104_SERVICE
			    "R:"
#endif /* RTCM104_SERVICE */
		)) != -1) {
	switch (option) {
	case 'D':
	    debuglevel = (int) strtol(optarg, 0, 0);
	    gpsd_hexdump_level = debuglevel;
	    break;
	case 'F':
	    control_socket = optarg;
	    break;
	case 'N':
	    go_background = false;
	    break;
	case 'b':
	    context.readonly = true;
	    break;
	case 'G':
	    listen_global = true;
	    break;
	case 'l':		/* list known device types and exit */
	    for (dp = gpsd_drivers; *dp; dp++) {
#ifdef ALLOW_RECONFIGURE
		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);
#endif /* ALLOW_RECONFIGURE */
		(void)puts((*dp)->type_name);
	    }
	    exit(0);
#ifdef RTCM104_SERVICE
	case 'R':
	    rtcm_service = optarg;
	    break;
#endif /* RTCM104_SERVICE */
	case 'S':
	    gpsd_service = optarg;
	    break;
	case 'n':
	    nowait = true;
	    break;
	case 'P':
	    pid_file = optarg;
	    break;
	case 'V':
	    (void)printf("gpsd %s\n", VERSION);
	    exit(0);
	case 'h': case '?':
	default:
	    usage();
	    exit(0);
	}
    }

#ifdef FIXED_PORT_SPEED
    /* Assume that if we're running with FIXED_PORT_SPEED we're some sort
     * of embedded configuration where we don't want to wait for connect */
    nowait = true;
#endif

    if (!control_socket && optind >= argc) {
	gpsd_report(LOG_ERROR, "can't run with neither control socket nor devices\n");
	exit(1);
    }

    /*
     * Control socket has to be created before we go background in order to
     * avoid a race condition in which hotplug scripts can try opening
     * the socket before it's created.
     */
    if (control_socket) {
	(void)unlink(control_socket);
	if ((csock = filesock(control_socket)) == -1) {
	    gpsd_report(LOG_ERROR,"control socket create failed, netlib error %d\n",csock);
	    exit(2);
	}
	FD_SET(csock, &all_fds);
	adjust_max_fd(csock, true);
	gpsd_report(LOG_PROG, "control socket opened at %s\n", control_socket);
    }

    if (go_background)
	(void)daemonize();

    if (pid_file) {
	FILE *fp;

	if ((fp = fopen(pid_file, "w")) != NULL) {
	    (void)fprintf(fp, "%u\n", (unsigned int)getpid());
	    (void)fclose(fp);
	} else {
	    gpsd_report(LOG_ERROR, "Cannot create PID file: %s.\n", pid_file);
	}
    }

    openlog("gpsd", LOG_PID, LOG_USER);
    gpsd_report(LOG_INF, "launching (Version %s)\n", VERSION);
    /*@ -observertrans @*/
    if (!gpsd_service)
	gpsd_service = getservbyname("gpsd", "tcp") ? "gpsd" : DEFAULT_GPSD_PORT;
    /*@ +observertrans @*/
    if ((msock = passivesock(gpsd_service, "tcp", QLEN)) == -1) {
	gpsd_report(LOG_ERR,"command socket create failed, netlib error %d\n",msock);
	exit(2);
    }
    gpsd_report(LOG_INF, "listening on port %s\n", gpsd_service);
#ifdef RTCM104_SERVICE
    /*@ -observertrans @*/
    if (!rtcm_service)
	rtcm_service = getservbyname("rtcm", "tcp") ? "rtcm" : DEFAULT_RTCM_PORT;
    /*@ +observertrans @*/
    if ((nsock = passivesock(rtcm_service, "tcp", QLEN)) == -1) {
	gpsd_report(LOG_ERROR,"RTCM104 socket create failed, netlib error %d\n",nsock);
	exit(2);
    }
    gpsd_report(LOG_INF, "listening on port %s\n", rtcm_service);
#endif /* RTCM104_SERVICE */

#ifdef NTPSHM_ENABLE
    if (getuid() == 0) {
	errno = 0;
	if (nice(NICEVAL) != -1 || errno == 0)
	    gpsd_report (2, "Priority setting failed.\n");
	(void)ntpshm_init(&context, nowait);
    } else {
	gpsd_report (LOG_INF, "Unable to start ntpshm.  gpsd must run as root.\n");
    }
#endif /* NTPSHM_ENABLE */

#ifdef DBUS_ENABLE
    /* we need to connect to dbus as root */
    if (initialize_dbus_connection()) {
	/* the connection could not be started */
	gpsd_report (LOG_ERROR, "unable to connect to the DBUS system bus\n");
    } else
	gpsd_report (LOG_PROG, "successfully connected to the DBUS system bus\n");
#endif /* DBUS_ENABLE */

    if (getuid() == 0 && go_background) {
	struct passwd *pw;
	struct stat stb;

	/* make default devices accessible even after we drop privileges */
	for (i = optind; i < argc; i++)
	    if (stat(argv[i], &stb) == 0)
		(void)chmod(argv[i], stb.st_mode|S_IRGRP|S_IWGRP);
	/*
	 * Drop privileges.  Up to now we've been running as root.  Instead,
	 * set the user ID to 'nobody' (or whatever the --enable-gpsd-user
	 * is) and the group ID to the owning group of a prototypical TTY
	 * device. This limits the scope of any compromises in the code.
	 * It requires that all GPS devices have their group read/write
	 * permissions set.
	 */
	if ((optind<argc&&stat(argv[optind], &stb)==0)||stat(PROTO_TTY,&stb)==0) {
	    gpsd_report(LOG_PROG, "changing to group %d\n", stb.st_gid);
	    if (setgid(stb.st_gid) != 0)
		gpsd_report(LOG_ERROR, "setgid() failed, errno %s\n", strerror(errno));
	}
	pw = getpwnam(GPSD_USER);
	if (pw)
	    (void)seteuid(pw->pw_uid);
    }
    gpsd_report(LOG_INF, "running with effective group ID %d\n", getegid());
    gpsd_report(LOG_INF, "running with effective user ID %d\n", geteuid());

    for (sub = subscribers; sub < subscribers + MAXSUBSCRIBERS; sub++) {
	gps_clear_fix(&sub->fixbuffer);
	gps_clear_fix(&sub->oldfix);
    }

    /* daemon got termination or interrupt signal */
    if ((st = setjmp(restartbuf)) > 0) {
	/* try to undo all device configurations */
	for (dfd = 0; dfd < MAXDEVICES; dfd++) {
	    if (allocated_channel(&channels[dfd]))
		(void)gpsd_wrap(&channels[dfd]);
	}
	gpsd_report(LOG_WARN, "gpsd restarted by SIGHUP\n");
    }

    /* Handle some signals */
    signalled = 0;
    (void)signal(SIGHUP, onsig);
    (void)signal(SIGINT, onsig);
    (void)signal(SIGTERM, onsig);
    (void)signal(SIGQUIT, onsig);
    (void)signal(SIGPIPE, SIG_IGN);

    FD_SET(msock, &all_fds);
    adjust_max_fd(msock, true);
#ifdef RTCM104_SERVICE
    FD_SET(nsock, &all_fds);
    adjust_max_fd(nsock, true);
#endif /* RTCM104_SERVICE */
    FD_ZERO(&control_fds);

    /* optimization hack to defer having to read subframe data */
    if (time(NULL) < START_SUBFRAME)
	context.valid |= LEAP_SECOND_VALID;

    for (i = optind; i < argc; i++) {
	struct gps_device_t *device = add_device(argv[i]);
	if (!device) {
	    gpsd_report(LOG_ERROR, "GPS device %s nonexistent or can't be read\n", argv[i]);
	}
    }

    while (0 == signalled) {
	(void)memcpy((char *)&rfds, (char *)&all_fds, sizeof(rfds));

	gpsd_report(LOG_RAW+2, "select waits\n");
	/*
	 * Poll for user commands or GPS data.  The timeout doesn't
	 * actually matter here since select returns whenever one of
	 * the file descriptors in the set goes ready.  The point
	 * of tracking maxfd is to keep the set of descriptors that
	 * select(2) has to poll here as small as possible (for
	 * low-clock-rate SBCs and the like).
	 */
	/*@ -usedef @*/
	tv.tv_sec = 1; tv.tv_usec = 0;
	if (select(maxfd+1, &rfds, NULL, NULL, &tv) == -1) {
	    if (errno == EINTR)
		continue;
	    gpsd_report(LOG_ERROR, "select: %s\n", strerror(errno));
	    exit(2);
	}
	/*@ +usedef @*/

#ifdef __UNUSED__
	{
	    char dbuf[BUFSIZ];
	    dbuf[0] = '\0';
	    for (sub = subscribers; sub < subscribers + MAXSUBSCRIBERS; sub++)
		if (FD_ISSET(sub->fd, &all_fds))
		    (void)snprintf(dbuf + strlen(dbuf),
				   sizeof(dbuf)-strlen(dbuf),
				   " %d", sub->fd);
	    strlcat(dbuf, "} -> {", BUFSIZ);
	    for (sub = subscribers; sub < subscribers + MAXSUBSCRIBERS; sub++)
		if (FD_ISSET(sub->fd, &rfds))
		    (void)snprintf(dbuf + strlen(dbuf),
				   sizeof(dbuf)-strlen(dbuf),
				   " %d", sub->fd);
	    gpsd_report(LOG_RAW, "Polling descriptor set: {%s}\n", dbuf);
	}
#endif /* UNUSED */

	/* always be open to new client connections */
	if (FD_ISSET(msock, &rfds)) {
	    socklen_t alen = (socklen_t)sizeof(fsin);
	    char *c_ip;
	    /*@i1@*/int ssock = accept(msock, (struct sockaddr *) &fsin, &alen);

	    if (ssock == -1)
		gpsd_report(LOG_ERROR, "accept: %s\n", strerror(errno));
	    else {
		struct subscriber_t *client = NULL;
		int opts = fcntl(ssock, F_GETFL);

		if (opts >= 0)
		    (void)fcntl(ssock, F_SETFL, opts | O_NONBLOCK);

		c_ip = sock2ip(ssock);
		client = allocate_client();
		if (client == NULL) {
		    gpsd_report(LOG_ERROR, "Client %s connect on fd %d -"
			"no subscriber slots available\n", c_ip, ssock);
		    (void)close(ssock);
		} else {
		    FD_SET(ssock, &all_fds);
		    adjust_max_fd(ssock, true);
		    client->fd = ssock;
		    client->active = timestamp();
		    client->tied = false;
		    client->requires = ANY;
		    gpsd_report(LOG_INF, "client %s (%d) connect on fd %d\n",
			c_ip, sub_index(client), ssock);
		}
	    }
	    FD_CLR(msock, &rfds);
	}

#ifdef RTCM104_SERVICE
	/* also to RTCM client connections */
	if (FD_ISSET(nsock, &rfds)) {
	    char *c_ip;
	    socklen_t alen = (socklen_t)sizeof(fsin);
	    /*@i1@*/int ssock = accept(nsock, (struct sockaddr *)&fsin, &alen);

	    if (ssock == -1)
		gpsd_report(LOG_ERROR, "accept: %s\n", strerror(errno));
	    else {
		struct subscriber_t *client = NULL;
		int opts = fcntl(ssock, F_GETFL);

		if (opts >= 0)
		    (void)fcntl(ssock, F_SETFL, opts | O_NONBLOCK);
		c_ip = sock2ip(ssock);
		client = allocate_client();
		if (client == NULL) {
		    gpsd_report(LOG_ERROR, "Client %s connect on fd %d -"
			"no subscriber slots available\n", c_ip, ssock);
		    close(ssock);
		} else {
		    FD_SET(ssock, &all_fds);
		    adjust_max_fd(ssock, true);
		    client->active = true;
		    client->tied = false;
		    client->requires = RTCM104;
		    client->fd = ssock;
		    gpsd_report(LOG_INF, "client %s (%d) connect on fd %d\n",
			c_ip, sub_index(client), ssock);
		}
	    }
	    FD_CLR(nsock, &rfds);
	}
#endif /* RTCM104_SERVICE */

	/* also be open to new control-socket connections */
	if (csock > -1 && FD_ISSET(csock, &rfds)) {
	    socklen_t alen = (socklen_t)sizeof(fsin);
	    /*@i1@*/int ssock = accept(csock, (struct sockaddr *) &fsin, &alen);

	    if (ssock == -1)
		gpsd_report(LOG_ERROR, "accept: %s\n", strerror(errno));
	    else {
		gpsd_report(LOG_INF, "control socket connect on %d\n", ssock);
		FD_SET(ssock, &all_fds);
		FD_SET(ssock, &control_fds);
		adjust_max_fd(ssock, true);
	    }
	    FD_CLR(csock, &rfds);
	}

	if (context.dsock >= 0 && FD_ISSET(context.dsock, &rfds)) {
	    /* be ready for DGPS reports */
	    if (netgnss_poll(&context) == -1){
		FD_CLR(context.dsock, &all_fds);
		FD_CLR(context.dsock, &rfds);
		context.dsock = -1;
	    }
	}
	/* read any commands that came in over control sockets */
	for (cfd = 0; cfd < FD_SETSIZE; cfd++)
	    if (FD_ISSET(cfd, &control_fds)) {
		char buf[BUFSIZ];

		while (read(cfd, buf, sizeof(buf)-1) > 0) {
		    gpsd_report(LOG_IO, "<= control(%d): %s\n", cfd, buf);
		    handle_control(cfd, buf);
		}
		(void)close(cfd);
		FD_CLR(cfd, &all_fds);
		FD_CLR(cfd, &control_fds);
		adjust_max_fd(cfd, false);
	    }

	/* poll all active devices */
	for (channel = channels; channel < channels + MAXDEVICES; channel++) {
	    if (!allocated_channel(channel))
		continue;

	    /* pass the current RTCM correction to the GPS if new */
	    if (channel->device_type && channel->context->netgnss_service != netgnss_remotegpsd)
		rtcm_relay(channel);

	    /* get data from the device */
	    changed = 0;
	    if (channel->gpsdata.gps_fd >= 0 && FD_ISSET(channel->gpsdata.gps_fd, &rfds))
	    {
		gpsd_report(LOG_RAW+1, "polling %d\n", channel->gpsdata.gps_fd);
		changed = gpsd_poll(channel);
		if (changed == ERROR_SET) {
		    gpsd_report(LOG_WARN, "packet sniffer failed to sync up\n");
		    FD_CLR(channel->gpsdata.gps_fd, &all_fds);
		    adjust_max_fd(channel->gpsdata.gps_fd, false);
		    gpsd_deactivate(channel);
		} else if ((changed & ONLINE_SET) == 0) {
		    FD_CLR(channel->gpsdata.gps_fd, &all_fds);
		    adjust_max_fd(channel->gpsdata.gps_fd, false);
		    gpsd_deactivate(channel);
		    notify_watchers(channel, "GPSD,X=0\r\n");
		}
		else {
		    /* handle laggy response to a firmware version query*/
		    if ((changed & DEVICEID_SET) != 0) {
			char id[NMEA_MAX];
			assert(channel->device_type != NULL);
			(void)snprintf(id, sizeof(id), "GPSD,I=%s",
				       channel->device_type->type_name);
			if (channel->subtype[0] != '\0') {
			    (void)strlcat(id, " ", sizeof(id));
			    (void)strlcat(id,channel->subtype,sizeof(id));
			}
			(void)strlcat(id, "\r\n", sizeof(id));
			notify_watchers(channel, id);
		    }
		    /* copy/merge channel data into subscriber fix buffers */
		    for (sub = subscribers;
			 sub < subscribers + MAXSUBSCRIBERS;
			 sub++) {
			if (sub->device == channel) {
			    if (sub->buffer_policy == casoc && (changed & CYCLE_START_SET)!=0)
				gps_clear_fix(&sub->fixbuffer);
			    /* don't downgrade mode if holding previous fix */
			    if (sub->fixbuffer.mode > sub->device->gpsdata.fix.mode)
				changed &=~ MODE_SET;
			    //gpsd_report(LOG_PROG,
			    //		"transfer mask on %s: %02x\n", sub->device->gpsdata.tag, changed);
			    gps_merge_fix(&sub->fixbuffer,
					  changed,
					  &sub->device->gpsdata.fix);
			    gpsd_error_model(sub->device,
					     &sub->fixbuffer, &sub->oldfix);
			}
		    }
		}
		/* copy each RTCM-104 correction to all GPSes */
		if ((changed & RTCM2_SET) != 0 || (changed & RTCM3_SET) != 0) {
		    struct gps_device_t *gps;
		    for (gps = channels; gps < channels + MAXDEVICES; gps++)
			if (gps->device_type != NULL && gps->device_type->rtcm_writer != NULL)
			    (void)gps->device_type->rtcm_writer(gps, (char *)gps->packet.outbuffer, gps->packet.outbuflen);
		}
	    }

	    for (sub = subscribers; sub < subscribers + MAXSUBSCRIBERS; sub++) {
		/* some listeners may be in watcher mode */
		if (sub->watcher) {
		    char cmds[4] = "";
		    channel->poll_times[sub - subscribers] = timestamp();
		    if (changed &~ ONLINE_SET) {
			if (changed & (LATLON_SET | MODE_SET))
			    (void)strlcat(cmds, "o", 4);
			if (changed & SATELLITE_SET)
			    (void)strlcat(cmds, "y", 4);
			if (channel->gpsdata.profiling!=0)
			    (void)strlcat(cmds, "$", 4);
		    }
		    if (cmds[0] != '\0')
			(void)handle_gpsd_request(sub, cmds, (int)strlen(cmds));
		}
	    }
#ifdef DBUS_ENABLE
	    if (changed &~ ONLINE_SET) {
		if (changed & (LATLON_SET | MODE_SET)) {
		    send_dbus_fix (channel);
		}
	    }
#endif
	}

#ifdef NOT_FIXED
	if (context.fixcnt > 0 && context.dsock == -1) {
	    for (channel=channels; channel < channels+MAXDEVICES; channel++) {
		if (channel->gpsdata.fix.mode > MODE_NO_FIX) {
		    netgnss_autoconnect(&context,
				      channel->gpsdata.fix.latitude,
				      channel->gpsdata.fix.longitude);
		    break;
		}
	    }
	}
#endif

	/* accept and execute commands for all clients */
	for (sub = subscribers; sub < subscribers + MAXSUBSCRIBERS; sub++) {
	    if (sub->active == 0)
		continue;

	    if (FD_ISSET(sub->fd, &rfds)) {
		char buf[BUFSIZ];
		int buflen;

		gpsd_report(LOG_PROG, "checking client(%d)\n", sub_index(sub));
		if ((buflen = (int)read(sub->fd, buf, sizeof(buf) - 1)) <= 0) {
		    detach_client(sub);
		} else {
		    if (buf[buflen-1] != '\n')
			buf[buflen++] = '\n';
		    buf[buflen] = '\0';
		    gpsd_report(LOG_IO, "<= client(%d): %s", sub_index(sub), buf);

#ifdef RTCM104_SERVICE
		    if (sub->requires==RTCM104
			|| sub->requires==ANY) {
			if (handle_rtcm_request(sub, buf, buflen) < 0)
			    detach_client(sub);
		    } else
#endif /* RTCM104_SERVICE */
		    {
			if (sub->device){
			    /*
			     * when a command comes in, to update .active to
			     * timestamp() so we don't close the connection
			     * after POLLER_TIMEOUT seconds. This makes
			     * POLLER_TIMEOUT useful.
			     */
			    sub->active = sub->device->poll_times[sub_index(sub)] = timestamp();
			}
			if (handle_gpsd_request(sub, buf, buflen) < 0)
			    detach_client(sub);
		    }
		}
	    } else if (sub->device == NULL && timestamp() - sub->active > ASSIGNMENT_TIMEOUT) {
		gpsd_report(LOG_WARN, "client(%d) timed out before assignment request.\n", sub_index(sub));
		detach_client(sub);
	    } else if (sub->device != NULL && !(sub->watcher || sub->raw>0) && timestamp() - sub->active > POLLER_TIMEOUT) {
		gpsd_report(LOG_WARN, "client(%d) timed out on command wait.\n", cfd);
		detach_client(sub);
	    }
	}

	/*
	 * Mark devices with an identified packet type but no
	 * remaining subscribers to be closed.  The reason the test
	 * has this particular form is so that, immediately after
	 * device open, we'll keep reading packets until a type is
	 * identified even though there are no subscribers yet.  We
	 * need this to happen so that subscribers can later choose a
	 * device by packet type.
	 */
	if (!nowait)
	    for (channel=channels; channel < channels+MAXDEVICES; channel++) {
		if (allocated_channel(channel)) {
		    if (channel->packet.type != BAD_PACKET) {
			bool device_needed = false;

			for (cfd = 0; cfd < MAXSUBSCRIBERS; cfd++)
			    if (subscribers[cfd].device == channel)
				device_needed = true;

			if (!device_needed && channel->gpsdata.gps_fd > -1) {
			    if (channel->releasetime == 0) {
				channel->releasetime = timestamp();
				gpsd_report(LOG_PROG, "channel %d released\n", (int)(channel-channels));
			    } else if (timestamp() - channel->releasetime > RELEASE_TIMEOUT) {
				gpsd_report(LOG_PROG, "channel %d closed\n", (int)(channel-channels));
				gpsd_report(LOG_RAW, "unflagging descriptor %d\n", channel->gpsdata.gps_fd);
				FD_CLR(channel->gpsdata.gps_fd, &all_fds);
				adjust_max_fd(channel->gpsdata.gps_fd, false);
				gpsd_deactivate(channel);
			    }
			}
		    }
		}
	    }
    }
    /* if we make it here, we got a signal... deal with it */
    /* restart on SIGHUP, clean up and exit otherwise */
    if (SIGHUP == (int)signalled)
	longjmp(restartbuf, 1);

    gpsd_report(LOG_WARN, "Received terminating signal %d. Exiting...\n",signalled);
    /* try to undo all device configurations */
    for (dfd = 0; dfd < MAXDEVICES; dfd++) {
	if (allocated_channel(&channels[dfd]))
	    (void)gpsd_wrap(&channels[dfd]);
    }

    if (control_socket)
	(void)unlink(control_socket);
    if (pid_file)
	(void)unlink(pid_file);
    return 0;
}
/*@ +mustfreefresh @*/