summaryrefslogtreecommitdiff
path: root/gpsd.c
blob: 94b6ff24c29cc142c6f1ff333bf77c8ac62e2d19 (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
#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 <sys/socket.h>
#include <netinet/in.h>
#include <assert.h>

#include "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_TIME_H)
#include <sys/time.h>
#endif

#include "gpsd.h"

#define DEFAULT_DEVICE_NAME	"/dev/gps"

#define QLEN			5

static fd_set all_fds;
static int debuglevel, in_background = 0;
static jmp_buf restartbuf;

static void onsig(int sig)
{
    longjmp(restartbuf, sig+1);
}

static int daemonize(void)
{
    int fd;
    pid_t pid;

    switch (pid = fork()) {
    case -1:
	return -1;
    case 0:	/* child side */
	break;
    default:	/* parent side */
	exit(0);
    }

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

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

	strcpy(buf, "gpsd: ");
	va_start(ap, fmt) ;
	vsnprintf(buf + strlen(buf), sizeof(buf)-strlen(buf), fmt, ap);
	va_end(ap);

	if (in_background)
	    syslog((errlevel == 0) ? LOG_ERR : LOG_NOTICE, "%s", buf);
	else
	    fputs(buf, stderr);
    }
}

static void usage(void)
{
    printf("usage:  gpsd [options] \n\
  Options include: \n\
  -f string (default %s)  	= set GPS device name \n\
  -S integer (default %s)	= set port for daemon \n\
  -d host[:port]         	= set DGPS server \n\
  -P pidfile              	= set file to record process ID \n\
  -D integer (default 0)  	= set debug level \n\
  -h                     	= help message \n",
	   DEFAULT_DEVICE_NAME, DEFAULT_GPSD_PORT);
}

static int have_fix(struct gps_device_t *device)
{
#define VALIDATION_COMPLAINT(level, legend) \
        gpsd_report(level, legend " (status=%d, mode=%d).\r\n", \
		    device->gpsdata.status, device->gpsdata.fix.mode)
    if ((device->gpsdata.status == STATUS_NO_FIX) != (device->gpsdata.fix.mode == MODE_NO_FIX)) {
	VALIDATION_COMPLAINT(3, "GPS is confused about whether it has a fix");
	return 0;
    }
    else if (device->gpsdata.status > STATUS_NO_FIX && device->gpsdata.fix.mode != MODE_NO_FIX) {
	VALIDATION_COMPLAINT(3, "GPS has a fix");
	return 1;
    }
    VALIDATION_COMPLAINT(3, "GPS has no fix");
    return 0;
#undef VALIDATION_CONSTRAINT
}

static int passivesock(char *service, char *protocol, int qlen)
{
    struct servent *pse;
    struct protoent *ppe;
    struct sockaddr_in sin;
    int s, type, one = 1;

    memset((char *) &sin, '\0', sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = INADDR_ANY;

    if ( (pse = getservbyname(service, protocol)) )
	sin.sin_port = htons(ntohs((u_short) pse->s_port));
    else if ((sin.sin_port = htons((u_short) atoi(service))) == 0) {
	gpsd_report(0, "Can't get \"%s\" service entry.\n", service);
	return -1;
    }
    if ((ppe = getprotobyname(protocol)) == 0) {
	gpsd_report(0, "Can't get \"%s\" protocol entry.\n", protocol);
	return -1;
    }
    if (strcmp(protocol, "udp") == 0)
	type = SOCK_DGRAM;
    else
	type = SOCK_STREAM;
    if ((s = socket(PF_INET, type, ppe->p_proto)) < 0) {
	gpsd_report(0, "Can't create socket\n");
	return -1;
    }
    if (setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof(one)) == -1) {
	gpsd_report(0, "Error: SETSOCKOPT SO_REUSEADDR\n");
	return -1;
    }
    if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
	gpsd_report(0, "Can't bind to port %s\n", service);
	return -1;
    }
    if (type == SOCK_STREAM && listen(s, qlen) < 0) {
	gpsd_report(0, "Can't listen on %s port%s\n", service);
	return -1;
    }
    return s;
}

#define ZERO_WATCHERS()		/* static storage doesn't need to be zeroed */
#define IS_WATCHER(cfd) 	subscribers[cfd].watcher
#define SET_WATCHER(cfd)	subscribers[cfd].watcher = 1
#define CLR_WATCHER(cfd)	subscribers[cfd].watcher = 0
#define ZERO_RAW()		/* static storage doesn't need to be zeroed */
#define IS_RAW(cfd)     	subscribers[cfd].raw
#define SET_RAW(cfd)    	subscribers[cfd].raw = 1
#define CLR_RAW(cfd)    	subscribers[cfd].raw = 0
/*
 * 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.
 *
 * We restrict the scope of these command-state globals as much as possible.
 */
#define MAXDEVICES	FD_SETSIZE

static struct channel_t {
    int nsubscribers;			/* how many subscribers? */
    struct gps_device_t *device;	/* the device data */
    int state;				/* marked for deletion */
#define CHANNEL_AVAILABLE	0
#define CHANNEL_INUSE		1
#define CHANNEL_KILLED		-1
    time_t when;
} channels[MAXDEVICES];

static struct subscriber_t {
    int active;				/* is this a subscriber? */
    int tied;				/* is client tied to device */
    int watcher;			/* is client in watcher mode? */
    int raw;				/* is client in raw mode? */
    struct channel_t *channel;		/* device subscriber listens to */
} subscribers[FD_SETSIZE];		/* indexed by client file descriptor */

static void attach_client_to_device(int cfd, int dfd)
{
    if (subscribers[cfd].channel) {
	subscribers[cfd].channel->nsubscribers--;
    }
    subscribers[cfd].channel = &channels[dfd];
    channels[dfd].nsubscribers++;
    subscribers[cfd].active = 1;
    subscribers[cfd].tied = 0;
}

#define is_client(cfd)	subscribers[cfd].active 

static void detach_client(int cfd)
{
    close(cfd);
    FD_CLR(cfd, &all_fds);
    CLR_RAW(cfd);
    CLR_WATCHER(cfd);
    subscribers[cfd].active = 0;
    if (subscribers[cfd].channel)
	subscribers[cfd].channel->nsubscribers--;
    subscribers[cfd].channel = NULL;
}

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

    gpsd_report(3, "=> client(%d): %s", cfd, buf);
    if ((status = write(cfd, buf, len)) > -1)
	return status;
    if (errno == EBADF)
	gpsd_report(3, "Client on %d has vanished.\n", cfd);
    else if (errno == EWOULDBLOCK)
	gpsd_report(3, "Dropped client on %d to avoid overrun.\n", cfd);
    else
	gpsd_report(3, "Client write to %d: %s\n", cfd, strerror(errno));
    detach_client(cfd);
    return status;
}

static void notify_watchers(char *sentence)
/* notify all watching clients of an event */
{
    int cfd;

    for (cfd = 0; cfd < FD_SETSIZE; cfd++)
	if (IS_WATCHER(cfd))
	    throttled_write(cfd, sentence, strlen(sentence));
}

static void raw_hook(struct gps_data_t *ud UNUSED, char *sentence)
/* hook to be executed on each incoming packet */
{
    int cfd;

    for (cfd = 0; cfd < FD_SETSIZE; cfd++) {
	/* copy raw NMEA sentences from GPS to clients in raw mode */
	if (IS_RAW(cfd))
	    throttled_write(cfd, sentence, strlen(sentence));
    }
}

static struct channel_t *open_device(char *device_name, int nowait)
/* open and initialize a new channel block */
{
    struct gps_device_t *device = gpsd_init(device_name);
    struct channel_t *chp;

    for (chp = channels; chp < channels + MAXDEVICES; chp++)
	if (chp->state == CHANNEL_AVAILABLE) {
	    chp->state = CHANNEL_INUSE;
	    chp->device = device;
	    goto found;
	}
    return NULL;
found:
    device->gpsdata.raw_hook = raw_hook;
    if (nowait) {
	if (gpsd_activate(device) < 0) {
	    return NULL;
	}
	FD_SET(device->gpsdata.gps_fd, &all_fds);
	chp->when = time(NULL);
    }

    return chp;
}

static int handle_request(int cfd, char *buf, int buflen)
/* interpret a client request; cfd is the socket back to the client */
{
    char reply[BUFSIZ], phrase[BUFSIZ], *p, *q;
    int i, j;
    struct subscriber_t *whoami = subscribers + cfd;
    struct channel_t *chp, *channel = whoami->channel;
    struct gps_device_t *device = channel->device;
    struct gps_data_t *ud = &device->gpsdata;

    strcpy(reply, "GPSD");
    p = buf;
    while (*p && p - buf < buflen) {
	phrase[0] = '\0';
	switch (toupper(*p++)) {
	case 'A':
	    if (have_fix(device) && ud->fix.mode == MODE_3D)
		sprintf(phrase, ",A=%.3f", ud->fix.altitude);
	    else
		strcpy(phrase, ",A=?");
	    break;
	case 'B':		/* change baud rate (SiRF only) */
	    if (*p == '=') {
		i = atoi(++p);
		while (isdigit(*p)) p++;
		if (device->device_type->speed_switcher)
		    if (device->device_type->speed_switcher(device, i)) {
			/* 
			 * Allow the control string time to register at the
			 * GPS before we do the baud rate switch, which 
			 * effectively trashes the UART's buffer.
			 *
			 * This definitely fails below 40 milliseconds on a
			 * BU-303b. 50ms is also verified by Chris Kuethe on 
			 *        Pharos iGPS360 + GSW 2.3.1ES + prolific
			 *        Rayming TN-200 + GSW 2.3.1 + ftdi
			 *        Rayming TN-200 + GSW 2.3.2 + ftdi
			 * so it looks pretty solid.
			 *
			 * The minimum delay time is probably constant
			 * across any given type of UART.
			 */
			tcdrain(device->gpsdata.gps_fd);
			usleep(50000);
			gpsd_set_speed(device, (speed_t)i, 1);
		    }
	    }
	    sprintf(phrase, ",B=%d %d N %d", 
		    gpsd_get_speed(&device->ttyset),
		    9 - ud->stopbits, ud->stopbits);
	    break;
	case 'C':
	    sprintf(phrase, ",C=%d", device->device_type->cycle);
	    break;
	case 'D':
	    strcpy(phrase, ",D=");
	    if (ud->fix.time)
		unix_to_iso8601(ud->fix.time, phrase+3);
	    else
		strcat(phrase, "?");
	    break;
	case 'E':
	    if (have_fix(device)) {
		if (device->gpsdata.fix.eph || device->gpsdata.fix.epv)
		    sprintf(phrase, ",E=%.2f %.2f %.2f", 
			    ud->epe, ud->fix.eph, ud->fix.epv);
		else if (ud->pdop || ud->hdop || ud->vdop)
		    sprintf(phrase, ",E=%.2f %.2f %.2f", 
			    ud->pdop * UERE(device), 
			    ud->hdop * UERE(device), 
			    ud->vdop * UERE(device));
	    } else
		strcpy(phrase, ",E=?");
	    break;
	case 'F':
	    if (*p == '=') {
		struct channel_t *newdev;
		char	*stash;
		for (q = ++p; isgraph(*p); p++)
		    continue;
		stash = (char *)malloc(p-q+1); 
		memcpy(stash, q, p-q);
		stash[p-q] = '\0';
		gpsd_report(1,"<= client(%d): switching to %s\n",cfd,stash);
		/* search for the device among active channels */
		for (chp = channels; chp < channels + MAXDEVICES; chp++)
		    if (chp->device&&!strcmp(chp->device->gpsd_device,stash)) {
			whoami->channel = channel = chp;
			device = channel->device;
			whoami->tied = 1;
			goto foundit;
		    }
		/* search failed, must attempt to initialize a new channel */
		newdev = open_device(stash, 1);
		if (newdev) {
		    whoami->tied = 1;
		    whoami->channel = newdev;
		    device = newdev->device;
		}
	    foundit:;
	    }
	    snprintf(phrase, sizeof(phrase), ",F=%s", device->gpsd_device);
	    break;
	case 'I':
	    snprintf(phrase, sizeof(phrase), ",I=%s", device->device_type->typename);
	    break;
	case 'K':
	    /* FIXME: K= form not yet supported */
	    strcpy(phrase, ",K=");
	    for (i = 0; i < MAXDEVICES; i++) 
		if (channels[i].device && strlen(phrase)+strlen(device->gpsd_device)+1 < sizeof(phrase)) {
		    strcat(phrase, device->gpsd_device);
		    strcat(phrase, " ");
		}
	    phrase[strlen(phrase)-1] = '\0';
	    break;
	case 'L':
	    sprintf(phrase, ",L=2 " VERSION " abcdefiklmnpqrstuvwxy");	//ghj
	    break;
	case 'M':
	    if (ud->fix.mode == MODE_NOT_SEEN)
		strcpy(phrase, ",M=?");
	    else
		sprintf(phrase, ",M=%d", ud->fix.mode);
	    break;
	case 'N':
	    if (!device->device_type->mode_switcher)
		strcpy(phrase, ",N=0");
	    else {
		if (*p == '=') ++p;
		if (*p == '1' || *p == '+') {
		    device->device_type->mode_switcher(device, 1);
		    p++;
		} else if (*p == '0' || *p == '-') {
		    device->device_type->mode_switcher(device, 0);
		    p++;
		}
	    }
	    sprintf(phrase, ",N=%d", device->gpsdata.driver_mode);
	    break;
	case 'O':
	    if (!have_fix(device))
		strcpy(phrase, ",O=?");
	    else {
		sprintf(phrase, ",O=%s %.2f %.3f %.6f %.6f",
			ud->tag[0] ? ud->tag : "-",
			ud->fix.time, ud->fix.ept, 
			ud->fix.latitude, ud->fix.longitude);
		if (device->gpsdata.fix.mode == MODE_3D)
		    sprintf(phrase+strlen(phrase), " %7.2f",
			    device->gpsdata.fix.altitude);
		else
		    strcat(phrase, "       ?");
		if (ud->fix.eph)
		    sprintf(phrase+strlen(phrase), " %5.2f",  ud->fix.eph);
		else
		    strcat(phrase, "        ?");
		if (ud->fix.epv)
		    sprintf(phrase+strlen(phrase), " %5.2f",  ud->fix.epv);
		else
		    strcat(phrase, "        ?");
		if (ud->fix.track != TRACK_NOT_VALID)
		    sprintf(phrase+strlen(phrase), " %8.4f %8.3f",
			    ud->fix.track, ud->fix.speed);
		else
		    strcat(phrase, "        ?        ?");
		if (device->gpsdata.fix.mode == MODE_3D)
		    sprintf(phrase+strlen(phrase), " %6.3f", ud->fix.climb);
		else
		    strcat(phrase, "      ?");
		strcat(phrase, " ?");	/* can't yet derive track error */ 
		if (device->gpsdata.valid & SPEEDERR_SET)
		    sprintf(phrase+strlen(phrase), " %5.2f",
			    device->gpsdata.fix.eps);		    
		else
		    strcat(phrase, "      ?");
		if (device->gpsdata.valid & CLIMBERR_SET)
		    sprintf(phrase+strlen(phrase), " %5.2f",
			    device->gpsdata.fix.epc);		    
		else
		    strcat(phrase, "      ?");
	    }
	    break;
	case 'P':
	    if (have_fix(device))
		sprintf(phrase, ",P=%.4f %.4f", 
			ud->fix.latitude, ud->fix.longitude);
	    else
		strcpy(phrase, ",P=?");
	    break;
	case 'Q':
	    if (ud->pdop || ud->hdop || ud->vdop)
		sprintf(phrase, ",Q=%d %.2f %.2f %.2f",
			ud->satellites_used, ud->pdop, ud->hdop, ud->vdop);
	    else
		strcpy(phrase, ",Q=?");
	    break;
	case 'R':
	    if (*p == '=') ++p;
	    if (*p == '1' || *p == '+') {
		SET_RAW(cfd);
		gpsd_report(3, "%d turned on raw mode\n", cfd);
		sprintf(phrase, ",R=1");
		p++;
	    } else if (*p == '0' || *p == '-') {
		CLR_RAW(cfd);
		gpsd_report(3, "%d turned off raw mode\n", cfd);
		sprintf(phrase, ",R=0");
		p++;
	    } else if (IS_RAW(cfd)) {
		CLR_RAW(cfd);
		gpsd_report(3, "%d turned off raw mode\n", cfd);
		sprintf(phrase, ",R=0");
	    } else {
		SET_RAW(cfd);
		gpsd_report(3, "%d turned on raw mode\n", cfd);
		sprintf(phrase, ",R=1");
	    }
	    break;
	case 'S':
	    sprintf(phrase, ",S=%d", ud->status);
	    break;
	case 'T':
	    if (have_fix(device) && ud->fix.track != TRACK_NOT_VALID)
		sprintf(phrase, ",T=%.4f", ud->fix.track);
	    else
		strcpy(phrase, ",T=?");
	    break;
	case 'U':
	    if (have_fix(device) && ud->fix.mode == MODE_3D)
		sprintf(phrase, ",U=%.3f", ud->fix.climb);
	    else
		strcpy(phrase, ",U=?");
	    break;
	case 'V':
	    if (have_fix(device) && ud->fix.track != TRACK_NOT_VALID)
		sprintf(phrase, ",V=%.3f", ud->fix.speed);
	    else
		strcpy(phrase, ",V=?");
	    break;
	case 'W':
	    if (*p == '=') ++p;
	    if (*p == '1' || *p == '+') {
		SET_WATCHER(cfd);
		sprintf(phrase, ",W=1");
		p++;
	    } else if (*p == '0' || *p == '-') {
		CLR_WATCHER(cfd);
		sprintf(phrase, ",W=0");
		p++;
	    } else if (IS_WATCHER(cfd)) {
		CLR_WATCHER(cfd);
		sprintf(phrase, ",W=0");
	    } else {
		SET_WATCHER(cfd);
		gpsd_report(3, "%d turned on watching\n", cfd);
		sprintf(phrase, ",W=1");
	    }
	    break;
        case 'X':
	    sprintf(phrase, ",X=%f", ud->online);
	    break;
	case 'Y':
	    if (ud->satellites) {
		int used, reported = 0;
		strcpy(phrase, ",Y=");
		if (ud->valid & TIME_SET)
		    sprintf(phrase+strlen(phrase), "%f ", ud->sentence_time);
		else
		    strcat(phrase, "? ");
		sprintf(phrase+strlen(phrase), "%d:", ud->satellites);
		for (i = 0; i < ud->satellites; i++) {
		    used = 0;
		    for (j = 0; j < ud->satellites_used; j++)
			if (ud->used[j] == ud->PRN[i]) {
			    used = 1;
			    break;
			}
		    if (ud->PRN[i]) {
			sprintf(phrase+strlen(phrase), "%d %d %d %d %d:", 
				ud->PRN[i], 
				ud->elevation[i],ud->azimuth[i],
				ud->ss[i],
				used);
			reported++;
		    }
		}
		if (ud->satellites != reported)
		    gpsd_report(1,"Satellite count %d != PRN count %d\n",
				ud->satellites, reported);
	    } else
		strcpy(phrase, ",Y=?");
	    break;
	case 'Z':
	    if (*p == '=') ++p;
	    if (*p == '1' || *p == '+') {
		ud->profiling = 1;
		gpsd_report(3, "%d turned on profiling mode\n", cfd);
		sprintf(phrase, ",Z=1");
		p++;
	    } else if (*p == '0' || *p == '-') {
		ud->profiling = 0;
		gpsd_report(3, "%d turned off profiling mode\n", cfd);
		sprintf(phrase, ",Z=0");
		p++;
	    } else {
		ud->profiling = !ud->profiling;
		gpsd_report(3, "%d toggled profiling mode\n", cfd);
		sprintf(phrase, ",Z=%d", ud->profiling);
	    }
	    break;
        case '$':
	    if (ud->sentence_time)
		sprintf(phrase, ",$=%s %d %f %f %f %f %f %f",
			ud->tag,
			ud->sentence_length,
			ud->sentence_time,
			ud->d_xmit_time - ud->sentence_time,
			ud->d_recv_time - ud->sentence_time,
			ud->d_decode_time - ud->sentence_time,
			device->poll_times[cfd] - ud->sentence_time,
			timestamp() - ud->sentence_time);
	    else
		sprintf(phrase, ",$=%s %d 0 %f %f %f %f %f",
			ud->tag,
			ud->sentence_length,
			ud->d_xmit_time,
			ud->d_recv_time - ud->d_xmit_time,
			ud->d_decode_time - ud->d_xmit_time,
			device->poll_times[cfd] - ud->d_xmit_time,
			timestamp() - ud->d_xmit_time);
	    break;
	case '\r': case '\n':
	    goto breakout;
	}
	if (strlen(reply) + strlen(phrase) < sizeof(reply) - 1)
	    strcat(reply, phrase);
	else
	    return -1;	/* Buffer would overflow.  Just return an error */
    }
 breakout:
    strcat(reply, "\r\n");

    return throttled_write(cfd, reply, strlen(reply));
}

int main(int argc, char *argv[])
{
    static char *pid_file = NULL;
    static int st, dsock = -1, changed, nowait = 0;
    static char *dgpsserver = NULL;
    static char *service = NULL; 
    static char *device_name = DEFAULT_DEVICE_NAME;
    static struct channel_t *channel;
    struct gps_device_t *device;
    int dfd;
    struct sockaddr_in fsin;
    fd_set rfds;
    int option, msock, cfd, go_background = 1;
    extern char *optarg;

    debuglevel = 0;
    while ((option = getopt(argc, argv, "D:S:d:f:hNnp:P:v")) != -1) {
	switch (option) {
	case 'D':
	    debuglevel = (int) strtol(optarg, 0, 0);
	    break;
	case 'N':
	    go_background = 0;
	    break;
	case 'S':
	    service = optarg;
	    break;
	case 'd':
	    dgpsserver = optarg;
	    break;
	case 'n':
	    nowait = 1;
	    break;
	case 'f':
	case 'p':
	    device_name = optarg;
	    break;
	case 'P':
	    pid_file = optarg;
	    break;
	case 'v':
	    printf("gpsd %s\n", VERSION);
	    exit(0);
	case 'h': case '?':
	default:
	    usage();
	    exit(0);
	}
    }

    if (!service)
	service = getservbyname("gpsd", "tcp") ? "gpsd" : DEFAULT_GPSD_PORT;

    if (go_background)
	daemonize();

    if (pid_file) {
	FILE *fp;

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

    /* user may want to re-initialize all channels */
    if ((st = setjmp(restartbuf)) > 0) {
	for (dfd = 0; dfd < FD_SETSIZE; dfd++) {
	    if (channels[dfd].device)
		gpsd_wrap(channels[dfd].device);
	}
	if (st == SIGHUP+1)
	    gpsd_report(1, "gpsd restarted by SIGHUP\n");
	else if (st > 0) {
	    gpsd_report(1,"Received terminating signal %d. Exiting...\n",st-1);
	    exit(10 + st);
	}
    }

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

    openlog("gpsd", LOG_PID, LOG_USER);
    gpsd_report(1, "launching (Version %s)\n", VERSION);
    if ((msock = passivesock(service, "tcp", QLEN)) < 0) {
	gpsd_report(0, "startup failed, netlib error %d\n", msock);
	exit(2);
    }
    gpsd_report(1, "listening on port %s\n", service);

    if (dgpsserver) {
	dsock = gpsd_open_dgps(dgpsserver);
	if (dsock >= 0)
	    FD_SET(dsock, &all_fds);
	else
	    gpsd_report(1, "Can't connect to DGPS server, netlib error %d\n",dsock);
    }

    FD_ZERO(&all_fds); ZERO_RAW(); ZERO_WATCHERS();
    FD_SET(msock, &all_fds);

    channel = open_device(device_name, nowait);
    if (!channel) {
	gpsd_report(0, "exiting - GPS device nonexistent or can't be read\n");
	exit(2);
    }
    device = channel->device;
    if (dsock >= 0)
	device->dsock = dsock;

    for (;;) {
	struct timeval tv;

        memcpy((char *)&rfds, (char *)&all_fds, sizeof(rfds));

	/* 
	 * 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. 
	 */
	tv.tv_sec = 1; tv.tv_usec = 0;
	if (select(FD_SETSIZE, &rfds, NULL, NULL, &tv) < 0) {
	    if (errno == EINTR)
		continue;
	    gpsd_report(0, "select: %s\n", strerror(errno));
	    exit(2);
	}

	/* always be open to new client connections */
	if (FD_ISSET(msock, &rfds)) {
	    socklen_t alen = sizeof(fsin);
	    int ssock = accept(msock, (struct sockaddr *) &fsin, &alen);
	    time_t most_recent = 0;
	    int mychannel = -1;

	    if (ssock < 0)
		gpsd_report(0, "accept: %s\n", strerror(errno));
	    else {
		int opts = fcntl(ssock, F_GETFL);

		if (opts >= 0)
		    fcntl(ssock, F_SETFL, opts | O_NONBLOCK);
		gpsd_report(3, "client connect on %d\n", ssock);
		FD_SET(ssock, &all_fds);
		/* pick the most recently opened device */
		for (channel=channels; channel<channels+MAXDEVICES; channel++)
		    if (channel->device && channel->when >= most_recent)
		    {
		       most_recent = channel->when;
		       mychannel = channel - channels;
		    }
		if (mychannel > -1)
		    attach_client_to_device(ssock, mychannel);
	    }
	    FD_CLR(msock, &rfds);
	}

	/* poll all active devices */
	for (channel = channels; channel < channels + MAXDEVICES; channel++) {
	    struct gps_device_t *device = channel->device;

	    if (!device)
		continue;
	    /* we may need to force the GPS open */
	    if (nowait && device->gpsdata.gps_fd == -1) {
		gpsd_deactivate(device);
		if (gpsd_activate(device) >= 0) {
		    FD_SET(device->gpsdata.gps_fd, &all_fds);
		    notify_watchers("GPSD,X=1\r\n");
		}
	    }

	    /* get data from the device */
	    changed = 0;
	    if (device->gpsdata.gps_fd >= 0 && !((changed=gpsd_poll(device)) | ONLINE_SET)) {
		gpsd_report(3, "GPS is offline\n");
		FD_CLR(device->gpsdata.gps_fd, &all_fds);
		gpsd_deactivate(device);
		notify_watchers("GPSD,X=0\r\n");
	    }

	    for (cfd = 0; cfd < FD_SETSIZE; cfd++) {
		/* some listeners may be in watcher mode */
		if (IS_WATCHER(cfd)) {
		    char cmds[4] = ""; 
		    device->poll_times[cfd] = timestamp();
		    if (changed &~ ONLINE_SET) {
			if (changed & LATLON_SET)
			    strcat(cmds, "o");
			if (changed & SATELLITE_SET)
			    strcat(cmds, "y");
		    }
		    if (device->gpsdata.profiling && device->packet_full)
			strcat(cmds, "$");
		    if (cmds[0])
			handle_request(cfd, cmds, strlen(cmds));
		}
	    }

	    /* this simplifies a later test */
	    if (device->dsock > -1)
		FD_CLR(device->dsock, &rfds);
	}

	/* accept and execute commands for all clients */
	for (cfd = 0; cfd < FD_SETSIZE; cfd++) {
	    if (!is_client(cfd))
		continue;
	    device = subscribers[cfd].channel->device;

	    /*
	     * GPS must be opened if commands are waiting or any client is
	     * streaming (raw or watcher mode).
	     */
	    if (FD_ISSET(cfd, &rfds) || IS_RAW(cfd) || IS_WATCHER(cfd)) {
		if (device->gpsdata.gps_fd == -1) {
		    gpsd_deactivate(device);
		    if (gpsd_activate(device) >= 0) {
			FD_SET(device->gpsdata.gps_fd, &all_fds);
			notify_watchers("GPSD,X=1\r\n");
		    }
		}

		if (FD_ISSET(cfd, &rfds)) {
		    char buf[BUFSIZ];
		    int buflen;
		    gpsd_report(3, "checking %d \n", cfd);
		    if ((buflen = read(cfd, buf, sizeof(buf) - 1)) <= 0) {
			detach_client(cfd);
		    } else {
		        buf[buflen] = '\0';
			gpsd_report(1, "<= client: %s", buf);

			device->poll_times[cfd] = timestamp();
			if (handle_request(cfd, buf, buflen) < 0)
			    detach_client(cfd);
		    }
		}
	    }
	}

	/* close devices with no remaining subscribers */
	for (channel = channels; channel < channels + MAXDEVICES; channel++) {
	    if (channel->device) {
		int need_gps = 0;

		for (cfd = 0; cfd < FD_SETSIZE; cfd++)
		    if (subscribers[cfd].active&&subscribers[cfd].channel==channel)
			need_gps++;

		if (!nowait && !need_gps && channel->device->gpsdata.gps_fd > -1) {
		    FD_CLR(channel->device->gpsdata.gps_fd, &all_fds);
		    gpsd_deactivate(channel->device);
		    if (channel->state == CHANNEL_KILLED)
			channel->device = NULL;
		}
	    }
	}
    }

    return 0;
}