You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2610 lines
78KB

  1. /*
  2. * This is the main sequence of the gpsd daemon. The IO dispatcher, main
  3. * select loop, and user command handling lives here.
  4. *
  5. * This file is Copyright (c) 2010-2018 by the GPSD project
  6. * SPDX-License-Identifier: BSD-2-clause
  7. */
  8. #include "gpsd_config.h" /* must be before all includes */
  9. #include <arpa/inet.h> /* for htons() and friends */
  10. #include <assert.h>
  11. #include <ctype.h>
  12. #include <errno.h>
  13. #include <fcntl.h>
  14. #include <grp.h> /* for setgroups() */
  15. #include <math.h>
  16. #include <netdb.h>
  17. #include <pthread.h>
  18. #include <pwd.h>
  19. #include <setjmp.h>
  20. #include <signal.h>
  21. #include <stdarg.h>
  22. #include <stdbool.h>
  23. #include <stdint.h> /* for uint32_t, etc. */
  24. #include <stdio.h>
  25. #include <stdlib.h>
  26. #include <string.h> /* for strlcat(), strcpy(), etc. */
  27. #include <syslog.h>
  28. #include <sys/param.h> /* for setgroups() */
  29. #include <sys/stat.h>
  30. #include <sys/types.h>
  31. #include <sys/un.h>
  32. #include <time.h>
  33. #include <unistd.h> /* for setgroups() */
  34. #ifndef AF_UNSPEC
  35. #include <sys/socket.h>
  36. #endif /* AF_UNSPEC */
  37. #ifndef INADDR_ANY
  38. #include <netinet/in.h>
  39. #endif /* INADDR_ANY */
  40. #include "gpsd.h"
  41. #include "gps_json.h" /* needs gpsd.h */
  42. #include "revision.h"
  43. #include "sockaddr.h"
  44. #include "strfuncs.h"
  45. #if defined(SYSTEMD_ENABLE)
  46. #include "sd_socket.h"
  47. #endif
  48. /*
  49. * The name of a tty device from which to pick up whatever the local
  50. * owning group for tty devices is. Used when we drop privileges.
  51. */
  52. #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
  53. #define PROTO_TTY "/dev/tty00" /* correct for *BSD */
  54. #else
  55. #define PROTO_TTY "/dev/ttyS0" /* correct for Linux */
  56. #endif
  57. /*
  58. * Timeout policy. We can't rely on clients closing connections
  59. * correctly, so we need timeouts to tell us when it's OK to
  60. * reclaim client fds. COMMAND_TIMEOUT fends off programs
  61. * that open connections and just sit there, not issuing a WATCH or
  62. * doing anything else that triggers a device assignment. Clients
  63. * in watcher or raw mode that don't read their data will get dropped
  64. * when throttled_write() fills up the outbound buffers and the
  65. * NOREAD_TIMEOUT expires.
  66. *
  67. * RELEASE_TIMEOUT sets the amount of time we hold a device
  68. * open after the last subscriber closes it; this is nonzero so a
  69. * client that does open/query/close will have time to come back and
  70. * do another single-shot query, if it wants to, before the device is
  71. * actually closed. The reason this matters is because some Bluetooth
  72. * GPSes not only shut down the GPS receiver on close to save battery
  73. * power, they actually shut down the Bluetooth RF stage as well and
  74. * only re-wake it periodically to see if an attempt to raise the
  75. * device is in progress. The result is that if you close the device
  76. * when it's powered up, a re-open can fail with EIO and needs to be
  77. * tried repeatedly. Better to avoid this...
  78. *
  79. * DEVICE_REAWAKE says how long to wait before repolling after a zero-length
  80. * read. It's there so we avoid spinning forever on an EOF condition.
  81. *
  82. * DEVICE_RECONNECT sets interval on retries when (re)connecting to
  83. * a device.
  84. */
  85. #define COMMAND_TIMEOUT 60*15
  86. #define NOREAD_TIMEOUT 60*3
  87. #define RELEASE_TIMEOUT 60
  88. #define DEVICE_REAWAKE 0.01
  89. #define DEVICE_RECONNECT 2
  90. #define QLEN 5
  91. /*
  92. * If ntpshm is enabled, we renice the process to this priority level.
  93. * For precise timekeeping increase priority.
  94. */
  95. #define NICEVAL -10
  96. #if (defined(TIMESERVICE_ENABLE) || \
  97. !defined(SOCKET_EXPORT_ENABLE))
  98. /*
  99. * Force nowait in two circumstances:
  100. *
  101. * (1) Socket export has been disabled. In this case we have no
  102. * way to know when client apps are watching the export channels,
  103. * so we need to be running all the time.
  104. *
  105. * (2) timeservice mode where we want the GPS always on for timing.
  106. */
  107. #define FORCE_NOWAIT
  108. #endif /* defined(TIMESERVICE_ENABLE) || !defined(SOCKET_EXPORT_ENABLE) */
  109. #ifdef SOCKET_EXPORT_ENABLE
  110. /* IP version used by the program */
  111. /* AF_UNSPEC: all
  112. * AF_INET: IPv4 only
  113. * AF_INET6: IPv6 only
  114. */
  115. static const int af_allowed = AF_UNSPEC;
  116. #endif /* SOCKET_EXPORT_ENABLE */
  117. #define AFCOUNT 2
  118. static fd_set all_fds;
  119. static int maxfd;
  120. static int highwater;
  121. #ifndef FORCE_GLOBAL_ENABLE
  122. static bool listen_global = false;
  123. #endif /* FORCE_GLOBAL_ENABLE */
  124. #ifdef FORCE_NOWAIT
  125. static bool nowait = true;
  126. #else /* FORCE_NOWAIT */
  127. static bool nowait = false;
  128. #endif /* FORCE_NOWAIT */
  129. static bool batteryRTC = false;
  130. static jmp_buf restartbuf;
  131. static struct gps_context_t context;
  132. #if defined(SYSTEMD_ENABLE)
  133. static int sd_socket_count = 0;
  134. #endif
  135. /* work around the unfinished ipv6 implementation on hurd and OSX <10.6 */
  136. #ifndef IPV6_TCLASS
  137. # if defined(__GNU__)
  138. # define IPV6_TCLASS 61
  139. # elif defined(__APPLE__)
  140. # define IPV6_TCLASS 36
  141. # endif
  142. #endif
  143. static volatile sig_atomic_t signalled;
  144. static void onsig(int sig)
  145. {
  146. /* just set a variable, and deal with it in the main loop */
  147. signalled = (sig_atomic_t) sig;
  148. }
  149. static void typelist(void)
  150. /* list installed drivers and enabled features */
  151. {
  152. const struct gps_type_t **dp;
  153. for (dp = gpsd_drivers; *dp; dp++) {
  154. if ((*dp)->packet_type == COMMENT_PACKET)
  155. continue;
  156. #ifdef RECONFIGURE_ENABLE
  157. if ((*dp)->mode_switcher != NULL)
  158. (void)fputs("n\t", stdout);
  159. else
  160. (void)fputc('\t', stdout);
  161. if ((*dp)->speed_switcher != NULL)
  162. (void)fputs("b\t", stdout);
  163. else
  164. (void)fputc('\t', stdout);
  165. if ((*dp)->rate_switcher != NULL)
  166. (void)fputs("c\t", stdout);
  167. else
  168. (void)fputc('\t', stdout);
  169. if ((*dp)->packet_type > NMEA_PACKET)
  170. (void)fputs("*\t", stdout);
  171. else
  172. (void)fputc('\t', stdout);
  173. #endif /* RECONFIGURE_ENABLE */
  174. (void)puts((*dp)->type_name);
  175. }
  176. (void)printf("# n: mode switch, b: speed switch, "
  177. "c: rate switch, *: non-NMEA packet type.\n");
  178. #if defined(SOCKET_EXPORT_ENABLE)
  179. (void)printf("# Socket export enabled.\n");
  180. #endif
  181. #if defined(SHM_EXPORT_ENABLE)
  182. (void)printf("# Shared memory export enabled.\n");
  183. #endif
  184. #if defined(DBUS_EXPORT_ENABLE)
  185. (void)printf("# DBUS export enabled\n");
  186. #endif
  187. exit(EXIT_SUCCESS);
  188. }
  189. static void usage(void)
  190. {
  191. (void)printf("usage: gpsd [OPTIONS] device...\n\n\
  192. Options include: \n\
  193. -b = bluetooth-safe: open data sources read-only\n\
  194. -D integer (default 0) = set debug level \n\
  195. -F sockfile = specify control socket location\n\
  196. -f FRAMING = fix device framing to FRAMING (8N1, 8O1, etc.)\n\
  197. -G = make gpsd listen on INADDR_ANY\n"
  198. #ifndef FORCE_GLOBAL_ENABLE
  199. " forced on in this binary\n"
  200. #endif /* FORCE_GLOBAL_ENABLE */
  201. " -h = help message \n\
  202. -n = don't wait for client connects to poll GPS\n"
  203. #ifdef FORCE_NOWAIT
  204. " forced on in this binary\n"
  205. #endif /* FORCE_NOWAIT */
  206. " -N = don't go into background\n\
  207. -P pidfile = set file to record process ID\n\
  208. -r = use GPS time even if no fix\n\
  209. -S PORT (default %s) = set port for daemon \n\
  210. -s SPEED = fix device speed to SPEED\n\
  211. -V = emit version and exit.\n"
  212. #ifdef NETFEED_ENABLE
  213. "\nA device may be a local serial device for GNSS input, plus an optional\n\
  214. PPS device, or a URL in one of the following forms:\n\
  215. tcp://host[:port]\n\
  216. udp://host[:port]\n\
  217. {dgpsip|ntrip}://[user:passwd@]host[:port][/stream]\n\
  218. gpsd://host[:port][/device][?protocol]\n\
  219. in which case it specifies an input source for device, DGPS or ntrip data.\n"
  220. #endif /* NETFEED_ENABLE */
  221. "\n\
  222. The following driver types are compiled into this gpsd instance:\n",
  223. DEFAULT_GPSD_PORT);
  224. typelist();
  225. if (8 > sizeof(time_t)) {
  226. (void)printf("\nWARNING: This system has a 32-bit time_t.\n"
  227. "WARNING: This gpsd will fail at 2038-01-19T03:14:07Z.\n");
  228. }
  229. }
  230. #ifdef CONTROL_SOCKET_ENABLE
  231. static socket_t filesock(char *filename)
  232. {
  233. struct sockaddr_un addr;
  234. socket_t sock;
  235. if (BAD_SOCKET(sock = socket(AF_UNIX, SOCK_STREAM, 0))) {
  236. GPSD_LOG(LOG_ERROR, &context.errout,
  237. "Can't create device-control socket\n");
  238. return -1;
  239. }
  240. (void)strlcpy(addr.sun_path, filename, sizeof(addr.sun_path));
  241. addr.sun_family = (sa_family_t)AF_UNIX;
  242. if (bind(sock, (struct sockaddr *)&addr, (socklen_t)sizeof(addr)) < 0) {
  243. GPSD_LOG(LOG_ERROR, &context.errout,
  244. "can't bind to local socket %s\n", filename);
  245. (void)close(sock);
  246. return -1;
  247. }
  248. if (listen(sock, QLEN) == -1) {
  249. GPSD_LOG(LOG_ERROR, &context.errout,
  250. "can't listen on local socket %s\n", filename);
  251. (void)close(sock);
  252. return -1;
  253. }
  254. /* coverity[leaked_handle] This is an intentional allocation */
  255. return sock;
  256. }
  257. #endif /* CONTROL_SOCKET_ENABLE */
  258. #define sub_index(s) (int)((s) - subscribers)
  259. #define allocated_device(devp) ((devp)->gpsdata.dev.path[0] != '\0')
  260. #define free_device(devp) (devp)->gpsdata.dev.path[0] = '\0'
  261. #define initialized_device(devp) ((devp)->context != NULL)
  262. /*
  263. * This array fills from the bottom, so as an extreme case you can
  264. * reduce MAX_DEVICES to 1 in the build recipe.
  265. */
  266. static struct gps_device_t devices[MAX_DEVICES];
  267. static void adjust_max_fd(int fd, bool on)
  268. /* track the largest fd currently in use */
  269. {
  270. if (on) {
  271. if (fd > maxfd)
  272. maxfd = fd;
  273. } else if (fd == maxfd) {
  274. int tfd;
  275. for (maxfd = tfd = 0; tfd < (int)FD_SETSIZE; tfd++)
  276. if (FD_ISSET(tfd, &all_fds))
  277. maxfd = tfd;
  278. }
  279. }
  280. #ifdef SOCKET_EXPORT_ENABLE
  281. #ifndef IPTOS_LOWDELAY
  282. #define IPTOS_LOWDELAY 0x10
  283. #endif
  284. static socket_t passivesock_af(int af, char *service, char *tcp_or_udp, int qlen)
  285. /* bind a passive command socket for the daemon */
  286. {
  287. volatile socket_t s;
  288. /*
  289. * af = address family,
  290. * service = IANA protocol name or number.
  291. * tcp_or_udp = TCP or UDP
  292. * qlen = maximum wait-queue length for connections
  293. */
  294. struct servent *pse;
  295. struct protoent *ppe;
  296. sockaddr_t sat;
  297. size_t sin_len = 0;
  298. int type, proto, one = 1;
  299. in_port_t port;
  300. char *af_str = "";
  301. const int dscp = IPTOS_LOWDELAY; /* Prioritize packet */
  302. INVALIDATE_SOCKET(s);
  303. if ((pse = getservbyname(service, tcp_or_udp)))
  304. port = ntohs((in_port_t) pse->s_port);
  305. // cppcheck-suppress unreadVariable
  306. else if ((port = (in_port_t) atoi(service)) == 0) {
  307. GPSD_LOG(LOG_ERROR, &context.errout,
  308. "can't get \"%s\" service entry.\n", service);
  309. return -1;
  310. }
  311. ppe = getprotobyname(tcp_or_udp);
  312. if (strcmp(tcp_or_udp, "udp") == 0) {
  313. type = SOCK_DGRAM;
  314. proto = (ppe) ? ppe->p_proto : IPPROTO_UDP;
  315. } else {
  316. type = SOCK_STREAM;
  317. proto = (ppe) ? ppe->p_proto : IPPROTO_TCP;
  318. }
  319. switch (af) {
  320. case AF_INET:
  321. sin_len = sizeof(sat.sa_in);
  322. memset((char *)&sat.sa_in, 0, sin_len);
  323. sat.sa_in.sin_family = (sa_family_t) AF_INET;
  324. #ifndef FORCE_GLOBAL_ENABLE
  325. if (!listen_global)
  326. sat.sa_in.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  327. else
  328. #endif /* FORCE_GLOBAL_ENABLE */
  329. sat.sa_in.sin_addr.s_addr = htonl(INADDR_ANY);
  330. sat.sa_in.sin_port = htons(port);
  331. af_str = "IPv4";
  332. /* see PF_INET6 case below */
  333. s = socket(PF_INET, type, proto);
  334. if (s > -1 ) {
  335. /* Set packet priority */
  336. if (setsockopt(s, IPPROTO_IP, IP_TOS, &dscp,
  337. (socklen_t)sizeof(dscp)) == -1)
  338. GPSD_LOG(LOG_WARN, &context.errout,
  339. "Warning: SETSOCKOPT TOS failed\n");
  340. }
  341. break;
  342. case AF_INET6:
  343. sin_len = sizeof(sat.sa_in6);
  344. memset((char *)&sat.sa_in6, 0, sin_len);
  345. sat.sa_in6.sin6_family = (sa_family_t) AF_INET6;
  346. #ifndef FORCE_GLOBAL_ENABLE
  347. if (!listen_global)
  348. sat.sa_in6.sin6_addr = in6addr_loopback;
  349. else
  350. #endif /* FORCE_GLOBAL_ENABLE */
  351. sat.sa_in6.sin6_addr = in6addr_any;
  352. sat.sa_in6.sin6_port = htons(port);
  353. /*
  354. * Traditionally BSD uses "communication domains", named by
  355. * constants starting with PF_ as the first argument for
  356. * select. In practice PF_INET has the same value as AF_INET
  357. * (on BSD and Linux, and probably everywhere else). POSIX
  358. * leaves much of this unspecified, but requires that AF_INET
  359. * be recognized. We follow tradition here.
  360. */
  361. af_str = "IPv6";
  362. s = socket(PF_INET6, type, proto);
  363. /*
  364. * On some network stacks, including Linux's, an IPv6 socket
  365. * defaults to listening on IPv4 as well. Unless we disable
  366. * this, trying to listen on in6addr_any will fail with the
  367. * address-in-use error condition.
  368. */
  369. if (s > -1) {
  370. int on = 1;
  371. if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on,
  372. (socklen_t)sizeof(on)) == -1) {
  373. GPSD_LOG(LOG_ERROR, &context.errout,
  374. "Error: SETSOCKOPT IPV6_V6ONLY\n");
  375. (void)close(s);
  376. return -1;
  377. }
  378. #ifdef IPV6_TCLASS
  379. /* Set packet priority */
  380. if (setsockopt(s, IPPROTO_IPV6, IPV6_TCLASS, &dscp,
  381. (socklen_t)sizeof(dscp)) == -1)
  382. GPSD_LOG(LOG_WARN, &context.errout,
  383. "Warning: SETSOCKOPT TOS failed\n");
  384. #endif /* IPV6_TCLASS */
  385. }
  386. break;
  387. default:
  388. GPSD_LOG(LOG_ERROR, &context.errout,
  389. "unhandled address family %d\n", af);
  390. return -1;
  391. }
  392. GPSD_LOG(LOG_IO, &context.errout,
  393. "opening %s socket\n", af_str);
  394. if (BAD_SOCKET(s)) {
  395. GPSD_LOG(LOG_ERROR, &context.errout,
  396. "can't create %s socket\n", af_str);
  397. return -1;
  398. }
  399. if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&one,
  400. (socklen_t)sizeof(one)) == -1) {
  401. GPSD_LOG(LOG_ERROR, &context.errout,
  402. "Error: SETSOCKOPT SO_REUSEADDR\n");
  403. (void)close(s);
  404. return -1;
  405. }
  406. if (bind(s, &sat.sa, (socklen_t)sin_len) < 0) {
  407. GPSD_LOG(LOG_ERROR, &context.errout,
  408. "can't bind to %s port %s, %s\n", af_str,
  409. service, strerror(errno));
  410. if (errno == EADDRINUSE) {
  411. GPSD_LOG(LOG_ERROR, &context.errout,
  412. "maybe gpsd is already running!\n");
  413. }
  414. (void)close(s);
  415. return -1;
  416. }
  417. if (type == SOCK_STREAM && listen(s, qlen) == -1) {
  418. GPSD_LOG(LOG_ERROR, &context.errout,
  419. "can't listen on port %s\n", service);
  420. (void)close(s);
  421. return -1;
  422. }
  423. GPSD_LOG(LOG_SPIN, &context.errout, "passivesock_af() -> %d\n", s);
  424. return s;
  425. }
  426. /* *INDENT-OFF* */
  427. static int passivesocks(char *service, char *tcp_or_udp,
  428. int qlen, socket_t socks[])
  429. {
  430. int numsocks = AFCOUNT;
  431. int i;
  432. for (i = 0; i < AFCOUNT; i++)
  433. INVALIDATE_SOCKET(socks[i]);
  434. #if defined(SYSTEMD_ENABLE)
  435. if (sd_socket_count > 0) {
  436. for (i = 0; i < AFCOUNT && i < sd_socket_count - 1; i++) {
  437. socks[i] = SD_SOCKET_FDS_START + i + 1;
  438. }
  439. return sd_socket_count - 1;
  440. }
  441. #endif
  442. if (AF_UNSPEC == af_allowed || (AF_INET == af_allowed))
  443. socks[0] = passivesock_af(AF_INET, service, tcp_or_udp, qlen);
  444. if (AF_UNSPEC == af_allowed || (AF_INET6 == af_allowed))
  445. socks[1] = passivesock_af(AF_INET6, service, tcp_or_udp, qlen);
  446. for (i = 0; i < AFCOUNT; i++)
  447. if (socks[i] < 0)
  448. numsocks--;
  449. /* Return the number of succesfully opened sockets
  450. * The failed ones are identified by negative values */
  451. return numsocks;
  452. }
  453. /* *INDENT-ON* */
  454. struct subscriber_t
  455. {
  456. int fd; /* client file descriptor. -1 if unused */
  457. time_t active; /* when subscriber last polled for data */
  458. struct gps_policy_t policy; /* configurable bits */
  459. pthread_mutex_t mutex; /* serialize access to fd */
  460. };
  461. #define subscribed(sub, devp) (sub->policy.watcher && (sub->policy.devpath[0]=='\0' || strcmp(sub->policy.devpath, devp->gpsdata.dev.path)==0))
  462. static struct subscriber_t subscribers[MAX_CLIENTS]; /* indexed by client file descriptor */
  463. static void lock_subscriber(struct subscriber_t *sub)
  464. {
  465. (void)pthread_mutex_lock(&sub->mutex);
  466. }
  467. static void unlock_subscriber(struct subscriber_t *sub)
  468. {
  469. (void)pthread_mutex_unlock(&sub->mutex);
  470. }
  471. static struct subscriber_t *allocate_client(void)
  472. /* return the address of a subscriber structure allocated for a new session */
  473. {
  474. int si;
  475. #if UNALLOCATED_FD == 0
  476. #error client allocation code will fail horribly
  477. #endif
  478. for (si = 0; si < NITEMS(subscribers); si++) {
  479. if (subscribers[si].fd == UNALLOCATED_FD) {
  480. subscribers[si].fd = 0; /* mark subscriber as allocated */
  481. return &subscribers[si];
  482. }
  483. }
  484. return NULL;
  485. }
  486. static void detach_client(struct subscriber_t *sub)
  487. /* detach a client and terminate the session */
  488. {
  489. char *c_ip;
  490. lock_subscriber(sub);
  491. if (sub->fd == UNALLOCATED_FD) {
  492. unlock_subscriber(sub);
  493. return;
  494. }
  495. c_ip = netlib_sock2ip(sub->fd);
  496. (void)shutdown(sub->fd, SHUT_RDWR);
  497. GPSD_LOG(LOG_SPIN, &context.errout,
  498. "close(%d) in detach_client()\n",
  499. sub->fd);
  500. (void)close(sub->fd);
  501. GPSD_LOG(LOG_INF, &context.errout,
  502. "detaching %s (sub %d, fd %d) in detach_client\n",
  503. c_ip, sub_index(sub), sub->fd);
  504. FD_CLR(sub->fd, &all_fds);
  505. adjust_max_fd(sub->fd, false);
  506. sub->active = 0;
  507. sub->policy.watcher = false;
  508. sub->policy.json = false;
  509. sub->policy.nmea = false;
  510. sub->policy.raw = 0;
  511. sub->policy.scaled = false;
  512. sub->policy.timing = false;
  513. sub->policy.split24 = false;
  514. sub->policy.devpath[0] = '\0';
  515. sub->fd = UNALLOCATED_FD;
  516. unlock_subscriber(sub);
  517. }
  518. static ssize_t throttled_write(struct subscriber_t *sub, char *buf,
  519. size_t len)
  520. /* write to client -- throttle if it's gone or we're close to buffer overrun */
  521. {
  522. ssize_t status;
  523. if (context.errout.debug >= LOG_CLIENT) {
  524. if (isprint((unsigned char) buf[0]))
  525. GPSD_LOG(LOG_CLIENT, &context.errout,
  526. "=> client(%d): %s\n", sub_index(sub), buf);
  527. else {
  528. #ifndef __clang_analyzer__
  529. char *cp, buf2[MAX_PACKET_LENGTH * 3];
  530. buf2[0] = '\0';
  531. for (cp = buf; cp < buf + len; cp++)
  532. str_appendf(buf2, sizeof(buf2),
  533. "%02x", (unsigned int)(*cp & 0xff));
  534. GPSD_LOG(LOG_CLIENT, &context.errout,
  535. "=> client(%d): =%s\n", sub_index(sub), buf2);
  536. #endif /* __clang_analyzer__ */
  537. }
  538. }
  539. gpsd_acquire_reporting_lock();
  540. status = send(sub->fd, buf, len, 0);
  541. gpsd_release_reporting_lock();
  542. if (status == (ssize_t) len)
  543. return status;
  544. else if (status > -1) {
  545. GPSD_LOG(LOG_INF, &context.errout,
  546. "short write disconnecting client(%d)\n",
  547. sub_index(sub));
  548. detach_client(sub);
  549. return 0;
  550. } else if (errno == EAGAIN || errno == EINTR)
  551. return 0; /* no data written, and errno says to retry */
  552. else if (errno == EBADF)
  553. GPSD_LOG(LOG_WARN, &context.errout,
  554. "client(%d) has vanished.\n", sub_index(sub));
  555. else if (errno == EWOULDBLOCK
  556. && time(NULL) - sub->active > NOREAD_TIMEOUT)
  557. GPSD_LOG(LOG_INF, &context.errout,
  558. "client(%d) timed out.\n", sub_index(sub));
  559. else
  560. GPSD_LOG(LOG_INF, &context.errout,
  561. "client(%d) write: %s\n",
  562. sub_index(sub), strerror(errno));
  563. detach_client(sub);
  564. return status;
  565. }
  566. static void notify_watchers(struct gps_device_t *device,
  567. bool onjson, bool onpps,
  568. const char *sentence, ...)
  569. /* notify all JSON-watching clients of a given device about an event */
  570. {
  571. va_list ap;
  572. char buf[BUFSIZ];
  573. struct subscriber_t *sub;
  574. va_start(ap, sentence);
  575. (void)vsnprintf(buf, sizeof(buf), sentence, ap);
  576. va_end(ap);
  577. for (sub = subscribers; sub < subscribers + MAX_CLIENTS; sub++)
  578. if (sub->active != 0 && subscribed(sub, device)) {
  579. if ((onjson && sub->policy.json) || (onpps && sub->policy.pps))
  580. (void)throttled_write(sub, buf, strlen(buf));
  581. }
  582. }
  583. #endif /* SOCKET_EXPORT_ENABLE */
  584. static void deactivate_device(struct gps_device_t *device)
  585. /* deactivate device, but leave it in the pool (do not free it) */
  586. {
  587. #ifdef SOCKET_EXPORT_ENABLE
  588. notify_watchers(device, true, false,
  589. "{\"class\":\"DEVICE\",\"path\":\"%s\",\"activated\":0}\r\n",
  590. device->gpsdata.dev.path);
  591. #endif /* SOCKET_EXPORT_ENABLE */
  592. if (!BAD_SOCKET(device->gpsdata.gps_fd)) {
  593. FD_CLR(device->gpsdata.gps_fd, &all_fds);
  594. adjust_max_fd(device->gpsdata.gps_fd, false);
  595. ntpshm_link_deactivate(device);
  596. gpsd_deactivate(device);
  597. }
  598. }
  599. /* find the device block for an existing device name */
  600. static struct gps_device_t *find_device(const char *device_name)
  601. {
  602. struct gps_device_t *devp;
  603. for (devp = devices; devp < devices + MAX_DEVICES; devp++) {
  604. if (allocated_device(devp) && NULL != device_name &&
  605. strcmp(devp->gpsdata.dev.path, device_name) == 0) {
  606. return devp;
  607. }
  608. }
  609. return NULL;
  610. }
  611. static bool open_device( struct gps_device_t *device)
  612. /* open the input device
  613. * return: false on failure
  614. * true on success
  615. */
  616. {
  617. int activated = -1;
  618. if (NULL == device ) {
  619. return false;
  620. }
  621. activated = gpsd_activate(device, O_OPTIMIZE);
  622. if ( ( 0 > activated ) && ( PLACEHOLDING_FD != activated ) ) {
  623. /* failed to open device, and it is not a /dev/ppsX */
  624. return false;
  625. }
  626. /*
  627. * Now is the right time to grab the shared memory segment(s)
  628. * to communicate the navigation message derived and (possibly)
  629. * 1PPS derived time data to ntpd/chrony.
  630. */
  631. ntpshm_link_activate(device);
  632. GPSD_LOG(LOG_INF, &context.errout,
  633. "PPS:%s ntpshm_link_activate: %d\n",
  634. device->gpsdata.dev.path,
  635. device->shm_clock != NULL);
  636. GPSD_LOG(LOG_INF, &context.errout,
  637. "device %s activated\n", device->gpsdata.dev.path);
  638. if ( PLACEHOLDING_FD == activated ) {
  639. /* it is a /dev/ppsX, no need to wait on it */
  640. return true;
  641. }
  642. FD_SET(device->gpsdata.gps_fd, &all_fds);
  643. adjust_max_fd(device->gpsdata.gps_fd, true);
  644. ++highwater;
  645. return true;
  646. }
  647. bool gpsd_add_device(const char *device_name, bool flag_nowait)
  648. /* add a device to the pool; open it right away if in nowait mode
  649. * return: false on failure
  650. * true on success
  651. */
  652. {
  653. struct gps_device_t *devp;
  654. bool ret = false;
  655. #ifdef SOCKET_EXPORT_ENABLE
  656. char tbuf[JSON_DATE_MAX+1];
  657. #endif /* SOCKET_EXPORT_ENABLE */
  658. /* we can't handle paths longer than GPS_PATH_MAX, so don't try */
  659. if (strlen(device_name) >= GPS_PATH_MAX) {
  660. GPSD_LOG(LOG_ERROR, &context.errout,
  661. "ignoring device %s: path length exceeds maximum %d\n",
  662. device_name, GPS_PATH_MAX);
  663. return false;
  664. }
  665. /* stash devicename away for probing when the first client connects */
  666. for (devp = devices; devp < devices + MAX_DEVICES; devp++)
  667. if (!allocated_device(devp)) {
  668. gpsd_init(devp, &context, device_name);
  669. ntpshm_session_init(devp);
  670. GPSD_LOG(LOG_INF, &context.errout,
  671. "stashing device %s at slot %d\n",
  672. device_name, (int)(devp - devices));
  673. if (!flag_nowait) {
  674. devp->gpsdata.gps_fd = UNALLOCATED_FD;
  675. ret = true;
  676. } else {
  677. ret = open_device(devp);
  678. }
  679. #ifdef SOCKET_EXPORT_ENABLE
  680. notify_watchers(devp, true, false,
  681. "{\"class\":\"DEVICE\",\"path\":\"%s\","
  682. "\"activated\":%s}\r\n",
  683. devp->gpsdata.dev.path,
  684. now_to_iso8601(tbuf, sizeof(tbuf)));
  685. #endif /* SOCKET_EXPORT_ENABLE */
  686. break;
  687. }
  688. return ret;
  689. }
  690. /* convert hex to binary, write it, unchanged, to GPS */
  691. static int write_gps(char *device, char *hex) {
  692. struct gps_device_t *devp;
  693. size_t len;
  694. int st;
  695. if ((devp = find_device(device)) == NULL) {
  696. GPSD_LOG(LOG_INF, &context.errout, "GPS <=: %s not active\n", device);
  697. return 1;
  698. }
  699. if (devp->context->readonly || (devp->sourcetype <= source_blockdev)) {
  700. GPSD_LOG(LOG_WARN, &context.errout,
  701. "GPS <=: attempted to write to a read-only device\n");
  702. return 1;
  703. }
  704. len = strlen(hex);
  705. /* NOTE: this destroys the original buffer contents */
  706. st = gpsd_hexpack(hex, hex, len);
  707. if (st <= 0) {
  708. GPSD_LOG(LOG_INF, &context.errout,
  709. "GPS <=: invalid hex string (error %d).\n", st);
  710. return 1;
  711. }
  712. GPSD_LOG(LOG_INF, &context.errout,
  713. "GPS <=: writing %d bytes fromhex(%s) to %s\n",
  714. st, hex, device);
  715. if (write(devp->gpsdata.gps_fd, hex, (size_t) st) <= 0) {
  716. GPSD_LOG(LOG_WARN, &context.errout,
  717. "GPS <=: write to device failed\n");
  718. return 1;
  719. }
  720. return 0;
  721. }
  722. #ifdef CONTROL_SOCKET_ENABLE
  723. static char *snarfline(char *p, char **out)
  724. /* copy the rest of the command line, before CR-LF */
  725. {
  726. char *q;
  727. static char stash[BUFSIZ];
  728. for (q = p;
  729. isprint((unsigned char) *p) &&
  730. !isspace((unsigned char) *p) &&
  731. (p - q < (ssize_t)(sizeof(stash) - 1));
  732. p++)
  733. continue;
  734. (void)memcpy(stash, q, (size_t) (p - q));
  735. stash[p - q] = '\0';
  736. *out = stash;
  737. return p;
  738. }
  739. static void handle_control(int sfd, char *buf)
  740. /* handle privileged commands coming through the control socket */
  741. {
  742. char *stash;
  743. struct gps_device_t *devp;
  744. /*
  745. * The only other place in the code that knows about the format
  746. * of the + and - commands is the gpsd_control() function in
  747. * gpsdctl.c. Be careful about keeping them in sync, or
  748. * hotplugging will have mysterious failures.
  749. */
  750. if (buf[0] == '-') {
  751. /* remove device named after - */
  752. (void)snarfline(buf + 1, &stash);
  753. GPSD_LOG(LOG_INF, &context.errout,
  754. "<= control(%d): removing %s\n", sfd, stash);
  755. if ((devp = find_device(stash))) {
  756. deactivate_device(devp);
  757. free_device(devp);
  758. ignore_return(write(sfd, "OK\n", 3));
  759. } else
  760. ignore_return(write(sfd, "ERROR\n", 6));
  761. } else if (buf[0] == '+') {
  762. /* add device named after + */
  763. (void)snarfline(buf + 1, &stash);
  764. if (find_device(stash)) {
  765. GPSD_LOG(LOG_INF, &context.errout,
  766. "<= control(%d): %s already active \n", sfd,
  767. stash);
  768. ignore_return(write(sfd, "ERROR\n", 6));
  769. } else {
  770. GPSD_LOG(LOG_INF, &context.errout,
  771. "<= control(%d): adding %s\n", sfd, stash);
  772. if (gpsd_add_device(stash, nowait))
  773. ignore_return(write(sfd, "OK\n", 3));
  774. else {
  775. ignore_return(write(sfd, "ERROR\n", 6));
  776. GPSD_LOG(LOG_INF, &context.errout,
  777. "control(%d): adding %s failed, too many "
  778. "devices active\n",
  779. sfd, stash);
  780. }
  781. }
  782. } else if (buf[0] == '!') {
  783. /* split line after ! into device=string, send string to device */
  784. char *eq;
  785. (void)snarfline(buf + 1, &stash);
  786. eq = strchr(stash, '=');
  787. if (eq == NULL) {
  788. GPSD_LOG(LOG_WARN, &context.errout,
  789. "<= control(%d): ill-formed command \n",
  790. sfd);
  791. ignore_return(write(sfd, "ERROR\n", 6));
  792. } else {
  793. *eq++ = '\0';
  794. if ((devp = find_device(stash))) {
  795. if (devp->context->readonly ||
  796. (devp->sourcetype <= source_blockdev)) {
  797. GPSD_LOG(LOG_WARN, &context.errout,
  798. "<= control(%d): attempted to write to a "
  799. "read-only device\n",
  800. sfd);
  801. ignore_return(write(sfd, "ERROR\n", 6));
  802. } else {
  803. GPSD_LOG(LOG_INF, &context.errout,
  804. "<= control(%d): writing to %s \n", sfd,
  805. stash);
  806. if (write(devp->gpsdata.gps_fd, eq, strlen(eq)) <= 0) {
  807. GPSD_LOG(LOG_WARN, &context.errout,
  808. "<= control(%d): write to device failed\n",
  809. sfd);
  810. ignore_return(write(sfd, "ERROR\n", 6));
  811. } else {
  812. ignore_return(write(sfd, "OK\n", 3));
  813. }
  814. }
  815. } else {
  816. GPSD_LOG(LOG_INF, &context.errout,
  817. "<= control(%d): %s not active \n", sfd,
  818. stash);
  819. ignore_return(write(sfd, "ERROR\n", 6));
  820. }
  821. }
  822. } else if (buf[0] == '&') {
  823. /* split line after & into dev=hexdata, send unpacked hexdata to dev */
  824. char *eq;
  825. (void)snarfline(buf + 1, &stash);
  826. eq = strchr(stash, '=');
  827. if (eq == NULL) {
  828. GPSD_LOG(LOG_WARN, &context.errout,
  829. "<= control(%d): ill-formed command\n",
  830. sfd);
  831. ignore_return(write(sfd, "ERROR\n", 6));
  832. } else {
  833. *eq++ = '\0';
  834. if (0 == write_gps(stash, eq)) {
  835. ignore_return(write(sfd, "OK\n", 3));
  836. } else {
  837. ignore_return(write(sfd, "ERROR\n", 6));
  838. }
  839. }
  840. } else if (strstr(buf, "?devices")==buf) {
  841. /* write back devices list followed by OK */
  842. for (devp = devices; devp < devices + MAX_DEVICES; devp++) {
  843. char *path = devp->gpsdata.dev.path;
  844. ignore_return(write(sfd, path, strlen(path)));
  845. ignore_return(write(sfd, "\n", 1));
  846. }
  847. ignore_return(write(sfd, "OK\n", 3));
  848. } else {
  849. /* unknown command */
  850. ignore_return(write(sfd, "ERROR\n", 6));
  851. }
  852. }
  853. #endif /* CONTROL_SOCKET_ENABLE */
  854. #ifdef SOCKET_EXPORT_ENABLE
  855. static bool awaken(struct gps_device_t *device)
  856. /* awaken a device and notify all watchers*/
  857. {
  858. /* open that device */
  859. if (!initialized_device(device)) {
  860. if (!open_device(device)) {
  861. GPSD_LOG(LOG_WARN, &context.errout,
  862. "%s: open failed\n",
  863. device->gpsdata.dev.path);
  864. free_device(device);
  865. return false;
  866. }
  867. }
  868. if (!BAD_SOCKET(device->gpsdata.gps_fd)) {
  869. GPSD_LOG(LOG_PROG, &context.errout,
  870. "device %d (fd=%d, path %s) already active.\n",
  871. (int)(device - devices),
  872. device->gpsdata.gps_fd, device->gpsdata.dev.path);
  873. return true;
  874. } else {
  875. if (gpsd_activate(device, O_OPTIMIZE) < 0) {
  876. GPSD_LOG(LOG_ERROR, &context.errout,
  877. "%s: device activation failed.\n",
  878. device->gpsdata.dev.path);
  879. GPSD_LOG(LOG_ERROR, &context.errout,
  880. "%s: activation failed, freeing device\n",
  881. device->gpsdata.dev.path);
  882. /* FIXME: works around a crash bug, but prevents retries */
  883. free_device(device);
  884. return false;
  885. } else {
  886. GPSD_LOG(LOG_RAW, &context.errout,
  887. "flagging descriptor %d in assign_channel()\n",
  888. device->gpsdata.gps_fd);
  889. FD_SET(device->gpsdata.gps_fd, &all_fds);
  890. adjust_max_fd(device->gpsdata.gps_fd, true);
  891. return true;
  892. }
  893. }
  894. }
  895. #ifdef RECONFIGURE_ENABLE
  896. #if __UNUSED_RECONFIGURE__
  897. static bool privileged_user(struct gps_device_t *device)
  898. /* is this channel privileged to change a device's behavior? */
  899. {
  900. /* grant user privilege if he's the only one listening to the device */
  901. struct subscriber_t *sub;
  902. int subcount = 0;
  903. for (sub = subscribers; sub < subscribers + MAX_CLIENTS; sub++) {
  904. if (subscribed(sub, device))
  905. subcount++;
  906. }
  907. /*
  908. * Yes, zero subscribers is possible. For example, gpsctl talking
  909. * to the daemon connects but doesn't necessarily issue a ?WATCH
  910. * before shipping a request, which means it isn't marked as a
  911. * subscriber.
  912. */
  913. return subcount <= 1;
  914. }
  915. #endif /* __UNUSED_RECONFIGURE__ */
  916. static void set_serial(struct gps_device_t *device,
  917. speed_t speed, char *modestring)
  918. /* set serial parameters for a device from a speed and modestring */
  919. {
  920. unsigned int stopbits = device->gpsdata.dev.stopbits;
  921. char parity = device->gpsdata.dev.parity;
  922. int wordsize = 8;
  923. struct timespec delay;
  924. #ifndef __clang_analyzer__
  925. while (isspace((unsigned char) *modestring))
  926. modestring++;
  927. if (*modestring && (NULL != strchr("78", *modestring))) {
  928. wordsize = (int)(*modestring++ - '0');
  929. if (*modestring && (NULL != strchr("NOE", *modestring))) {
  930. parity = *modestring++;
  931. while (isspace((unsigned char) *modestring))
  932. modestring++;
  933. if (*modestring && (NULL != strchr("12", *modestring))) {
  934. stopbits = (unsigned int)(*modestring - '0');
  935. }
  936. }
  937. }
  938. #endif /* __clang_analyzer__ */
  939. GPSD_LOG(LOG_PROG, &context.errout,
  940. "set_serial(%s,%u,%s) %c%d\n",
  941. device->gpsdata.dev.path,
  942. (unsigned int)speed, modestring, parity, stopbits);
  943. /* no support for other word sizes yet */
  944. /* *INDENT-OFF* */
  945. if (wordsize == (int)(9 - stopbits)
  946. && device->device_type->speed_switcher != NULL) {
  947. if (device->device_type->speed_switcher(device, speed, parity, (int)stopbits)) {
  948. /*
  949. * Deep black magic is required here. We have to
  950. * allow the control string time to register at the
  951. * GPS before we do the baud rate switch, which
  952. * effectively trashes the UART's buffer.
  953. *
  954. * This definitely fails below 40 milliseconds on a
  955. * BU-303b. 50ms is also verified by Chris Kuethe on
  956. * Pharos iGPS360 + GSW 2.3.1ES + prolific
  957. * Rayming TN-200 + GSW 2.3.1 + ftdi
  958. * Rayming TN-200 + GSW 2.3.2 + ftdi
  959. * so it looks pretty solid.
  960. *
  961. * The minimum delay time is probably constant
  962. * across any given type of UART.
  963. */
  964. (void)tcdrain(device->gpsdata.gps_fd);
  965. /* wait 50,000 uSec */
  966. delay.tv_sec = 0;
  967. delay.tv_nsec = 50000000L;
  968. nanosleep(&delay, NULL);
  969. gpsd_set_speed(device, speed, parity, stopbits);
  970. }
  971. }
  972. /* *INDENT-ON* */
  973. }
  974. #endif /* RECONFIGURE_ENABLE */
  975. #ifdef SOCKET_EXPORT_ENABLE
  976. static void json_devicelist_dump(char *reply, size_t replylen)
  977. {
  978. struct gps_device_t *devp;
  979. (void)strlcpy(reply, "{\"class\":\"DEVICES\",\"devices\":[", replylen);
  980. for (devp = devices; devp < devices + MAX_DEVICES; devp++)
  981. if (allocated_device(devp)
  982. && strlen(reply) + strlen(devp->gpsdata.dev.path) + 3 <
  983. replylen - 1) {
  984. char *cp;
  985. json_device_dump(devp,
  986. reply + strlen(reply), replylen - strlen(reply));
  987. cp = reply + strlen(reply);
  988. *--cp = '\0';
  989. *--cp = '\0';
  990. (void)strlcat(reply, ",", replylen);
  991. }
  992. str_rstrip_char(reply, ',');
  993. (void)strlcat(reply, "]}\r\n", replylen);
  994. }
  995. #endif /* SOCKET_EXPORT_ENABLE */
  996. static void rstrip(char *str)
  997. /* strip trailing \r\n\t\SP from a string */
  998. {
  999. char *strend;
  1000. strend = str + strlen(str) - 1;
  1001. while (isspace((unsigned char) *strend)) {
  1002. *strend = '\0';
  1003. --strend;
  1004. }
  1005. }
  1006. static void handle_request(struct subscriber_t *sub,
  1007. const char *buf, const char **after,
  1008. char *reply, size_t replylen)
  1009. {
  1010. struct gps_device_t *devp;
  1011. const char *end = NULL;
  1012. if (str_starts_with(buf, "?DEVICES;")) {
  1013. buf += 9;
  1014. json_devicelist_dump(reply, replylen);
  1015. } else if (str_starts_with(buf, "?WATCH")
  1016. && (buf[6] == ';' || buf[6] == '=')) {
  1017. const char *start = buf;
  1018. buf += 6;
  1019. if (*buf == ';') {
  1020. ++buf;
  1021. } else {
  1022. int status = json_watch_read(buf + 1, &sub->policy, &end);
  1023. sub->policy.timing = false;
  1024. if (end == NULL)
  1025. buf += strlen(buf);
  1026. else {
  1027. if (*end == ';')
  1028. ++end;
  1029. buf = end;
  1030. }
  1031. if (status != 0) {
  1032. (void)snprintf(reply, replylen,
  1033. "{\"class\":\"ERROR\",\"message\":"
  1034. "\"Invalid WATCH: %s\"}\r\n",
  1035. json_error_string(status));
  1036. GPSD_LOG(LOG_ERROR, &context.errout, "response: %s\n", reply);
  1037. } else if (sub->policy.watcher) {
  1038. if (sub->policy.devpath[0] == '\0') {
  1039. /* awaken all devices */
  1040. for (devp = devices; devp < devices + MAX_DEVICES; devp++)
  1041. if (allocated_device(devp)) {
  1042. (void)awaken(devp);
  1043. if (devp->sourcetype == source_gpsd) {
  1044. /* forward to master gpsd */
  1045. (void)gpsd_write(devp, start,
  1046. (size_t)(end-start));
  1047. }
  1048. }
  1049. } else {
  1050. devp = find_device(sub->policy.devpath);
  1051. if (devp == NULL) {
  1052. (void)snprintf(reply, replylen,
  1053. "{\"class\":\"ERROR\",\"message\":"
  1054. "\"No such device as %s\"}\r\n",
  1055. sub->policy.devpath);
  1056. GPSD_LOG(LOG_ERROR, &context.errout,
  1057. "response: %s\n", reply);
  1058. goto bailout;
  1059. } else if (awaken(devp)) {
  1060. if (devp->sourcetype == source_gpsd) {
  1061. (void)gpsd_write(devp, start, (size_t)(end-start));
  1062. }
  1063. } else {
  1064. (void)snprintf(reply, replylen,
  1065. "{\"class\":\"ERROR\",\"message\":\"Can't assign %s\"}\r\n",
  1066. sub->policy.devpath);
  1067. GPSD_LOG(LOG_ERROR, &context.errout,
  1068. "response: %s\n", reply);
  1069. goto bailout;
  1070. }
  1071. }
  1072. }
  1073. }
  1074. /* display a device list and the user's policy */
  1075. json_devicelist_dump(reply + strlen(reply), replylen - strlen(reply));
  1076. json_watch_dump(&sub->policy,
  1077. reply + strlen(reply), replylen - strlen(reply));
  1078. } else if (str_starts_with(buf, "?DEVICE")
  1079. && (buf[7] == ';' || buf[7] == '=')) {
  1080. struct devconfig_t devconf;
  1081. buf += 7;
  1082. devconf.path[0] = '\0'; /* initially, no device selection */
  1083. if (*buf == ';') {
  1084. ++buf;
  1085. } else {
  1086. #ifdef RECONFIGURE_ENABLE
  1087. struct gps_device_t *device;
  1088. /* first, select a device to operate on */
  1089. int status = json_device_read(buf + 1, &devconf, &end);
  1090. if (end == NULL)
  1091. buf += strlen(buf);
  1092. else {
  1093. if (*end == ';')
  1094. ++end;
  1095. buf = end;
  1096. }
  1097. device = NULL;
  1098. if (status != 0) {
  1099. (void)snprintf(reply, replylen,
  1100. "{\"class\":\"ERROR\",\"message\":\"Invalid DEVICE: \"%s\"}\r\n",
  1101. json_error_string(status));
  1102. GPSD_LOG(LOG_ERROR, &context.errout, "response: %s\n", reply);
  1103. goto bailout;
  1104. } else {
  1105. if (devconf.path[0] != '\0') {
  1106. /* user specified a path, try to assign it */
  1107. device = find_device(devconf.path);
  1108. /* do not optimize away, we need 'device' later on! */
  1109. if (device == NULL || !awaken(device)) {
  1110. (void)snprintf(reply, replylen,
  1111. "{\"class\":\"ERROR\",\"message\":\"Can't open %s.\"}\r\n",
  1112. devconf.path);
  1113. GPSD_LOG(LOG_ERROR, &context.errout,
  1114. "response: %s\n", reply);
  1115. goto bailout;
  1116. }
  1117. } else {
  1118. /* no path specified */
  1119. int devcount = 0;
  1120. for (devp = devices; devp < devices + MAX_DEVICES; devp++)
  1121. if (allocated_device(devp)) {
  1122. device = devp;
  1123. devcount++;
  1124. }
  1125. if (devcount == 0) {
  1126. (void)strlcat(reply,
  1127. "{\"class\":\"ERROR\",\"message\":"
  1128. "\"Can't perform DEVICE configuration, "
  1129. "no devices attached.\"}\r\n",
  1130. replylen);
  1131. GPSD_LOG(LOG_ERROR, &context.errout,
  1132. "response: %s\n", reply);
  1133. goto bailout;
  1134. } else if (devcount > 1) {
  1135. str_appendf(reply, replylen,
  1136. "{\"class\":\"ERROR\",\"message\":"
  1137. "\"No path specified in DEVICE, but "
  1138. "multiple devices are attached.\"}\r\n");
  1139. GPSD_LOG(LOG_ERROR, &context.errout,
  1140. "response: %s\n", reply);
  1141. goto bailout;
  1142. }
  1143. /* we should have exactly one device now */
  1144. }
  1145. if (device->device_type == NULL)
  1146. str_appendf(reply, replylen,
  1147. "{\"class\":\"ERROR\",\"message\":\"Type of %s is unknown.\"}\r\n",
  1148. device->gpsdata.dev.path);
  1149. else {
  1150. timespec_t delta1, delta2;
  1151. const struct gps_type_t *dt = device->device_type;
  1152. bool no_serial_change =
  1153. (devconf.baudrate == DEVDEFAULT_BPS)
  1154. && (devconf.parity == DEVDEFAULT_PARITY)
  1155. && (devconf.stopbits == DEVDEFAULT_STOPBITS);
  1156. /* interpret defaults */
  1157. if (devconf.baudrate == DEVDEFAULT_BPS)
  1158. devconf.baudrate =
  1159. (unsigned int) gpsd_get_speed(device);
  1160. if (devconf.parity == DEVDEFAULT_PARITY)
  1161. devconf.stopbits = device->gpsdata.dev.stopbits;
  1162. if (devconf.stopbits == DEVDEFAULT_STOPBITS)
  1163. devconf.stopbits = device->gpsdata.dev.stopbits;
  1164. if (0 < devconf.cycle.tv_sec ||
  1165. 0 < devconf.cycle.tv_nsec) {
  1166. devconf.cycle = device->gpsdata.dev.cycle;
  1167. }
  1168. /* now that channel is selected, apply changes */
  1169. if (devconf.driver_mode != device->gpsdata.dev.driver_mode
  1170. && devconf.driver_mode != DEVDEFAULT_NATIVE
  1171. && dt->mode_switcher != NULL)
  1172. dt->mode_switcher(device, devconf.driver_mode);
  1173. if (!no_serial_change) {
  1174. char serialmode[3];
  1175. serialmode[0] = devconf.parity;
  1176. serialmode[1] = '0' + devconf.stopbits;
  1177. serialmode[2] = '\0';
  1178. set_serial(device,
  1179. (speed_t) devconf.baudrate, serialmode);
  1180. }
  1181. TS_SUB(&delta1, &devconf.cycle, &device->gpsdata.dev.cycle);
  1182. if (TS_NZ(&delta1)) {
  1183. /* different cycle time than before */
  1184. TS_SUB(&delta2, &devconf.cycle, &dt->min_cycle);
  1185. if (TS_GZ(&delta2) &&
  1186. dt->rate_switcher != NULL) {
  1187. /* longer than minimum cycle time */
  1188. if (dt->rate_switcher(device,
  1189. TSTONS(&devconf.cycle))) {
  1190. device->gpsdata.dev.cycle = devconf.cycle;
  1191. }
  1192. }
  1193. }
  1194. if ('\0' != devconf.hexdata[0]) {
  1195. write_gps(device->gpsdata.dev.path, devconf.hexdata);
  1196. }
  1197. }
  1198. }
  1199. #else /* RECONFIGURE_ENABLE */
  1200. str_appendf(reply, replylen,
  1201. "{\"class\":\"ERROR\",\"message\":\"Device configuration support not compiled.\"}\r\n");
  1202. #endif /* RECONFIGURE_ENABLE */
  1203. }
  1204. /* dump a response for each selected channel */
  1205. for (devp = devices; devp < devices + MAX_DEVICES; devp++) {
  1206. if (!allocated_device(devp))
  1207. continue;
  1208. else if (devconf.path[0] != '\0'
  1209. && strcmp(devp->gpsdata.dev.path, devconf.path) != 0)
  1210. continue;
  1211. else {
  1212. json_device_dump(devp,
  1213. reply + strlen(reply),
  1214. replylen - strlen(reply));
  1215. }
  1216. }
  1217. } else if (str_starts_with(buf, "?POLL;")) {
  1218. char tbuf[JSON_DATE_MAX+1];
  1219. int active = 0;
  1220. buf += 6;
  1221. for (devp = devices; devp < devices + MAX_DEVICES; devp++) {
  1222. if (allocated_device(devp) && subscribed(sub, devp))
  1223. if ((devp->observed & GPS_TYPEMASK) != 0)
  1224. active++;
  1225. }
  1226. (void)snprintf(reply, replylen,
  1227. "{\"class\":\"POLL\",\"time\":\"%s\",\"active\":%d, "
  1228. "\"tpv\":[",
  1229. now_to_iso8601(tbuf, sizeof(tbuf)), active);
  1230. for (devp = devices; devp < devices + MAX_DEVICES; devp++) {
  1231. if (allocated_device(devp) && subscribed(sub, devp)) {
  1232. if ((devp->observed & GPS_TYPEMASK) != 0) {
  1233. json_tpv_dump(devp, &sub->policy,
  1234. reply + strlen(reply),
  1235. replylen - strlen(reply));
  1236. rstrip(reply);
  1237. (void)strlcat(reply, ",", replylen);
  1238. }
  1239. }
  1240. }
  1241. str_rstrip_char(reply, ',');
  1242. (void)strlcat(reply, "],\"gst\":[", replylen);
  1243. for (devp = devices; devp < devices + MAX_DEVICES; devp++) {
  1244. if (allocated_device(devp) && subscribed(sub, devp)) {
  1245. if ((devp->observed & GPS_TYPEMASK) != 0) {
  1246. json_noise_dump(&devp->gpsdata,
  1247. reply + strlen(reply),
  1248. replylen - strlen(reply));
  1249. rstrip(reply);
  1250. (void)strlcat(reply, ",", replylen);
  1251. }
  1252. }
  1253. }
  1254. str_rstrip_char(reply, ',');
  1255. (void)strlcat(reply, "],\"sky\":[", replylen);
  1256. for (devp = devices; devp < devices + MAX_DEVICES; devp++) {
  1257. if (allocated_device(devp) && subscribed(sub, devp)) {
  1258. if ((devp->observed & GPS_TYPEMASK) != 0) {
  1259. json_sky_dump(&devp->gpsdata,
  1260. reply + strlen(reply),
  1261. replylen - strlen(reply));
  1262. rstrip(reply);
  1263. (void)strlcat(reply, ",", replylen);
  1264. }
  1265. }
  1266. }
  1267. str_rstrip_char(reply, ',');
  1268. (void)strlcat(reply, "]}\r\n", replylen);
  1269. } else if (str_starts_with(buf, "?VERSION;")) {
  1270. buf += 9;
  1271. json_version_dump(reply, replylen);
  1272. } else {
  1273. const char *errend;
  1274. errend = buf + strlen(buf) - 1;
  1275. while (isspace((unsigned char) *errend) && errend > buf)
  1276. --errend;
  1277. (void)snprintf(reply, replylen,
  1278. "{\"class\":\"ERROR\",\"message\":"
  1279. "\"Unrecognized request '%.*s'\"}\r\n",
  1280. (int)(errend - buf), buf);
  1281. GPSD_LOG(LOG_ERROR, &context.errout, "ERROR response: %s\n", reply);
  1282. buf += strlen(buf);
  1283. }
  1284. bailout:
  1285. *after = buf;
  1286. }
  1287. static void raw_report(struct subscriber_t *sub, struct gps_device_t *device)
  1288. /* report a raw packet to a subscriber */
  1289. {
  1290. /* *INDENT-OFF* */
  1291. /*
  1292. * NMEA and other textual sentences are simply
  1293. * copied to all clients that are in raw or nmea
  1294. * mode.
  1295. */
  1296. if (TEXTUAL_PACKET_TYPE(device->lexer.type)
  1297. && (sub->policy.raw > 0 || sub->policy.nmea)) {
  1298. (void)throttled_write(sub,
  1299. (char *)device->lexer.outbuffer,
  1300. device->lexer.outbuflen);
  1301. return;
  1302. }
  1303. /*
  1304. * Also, simply copy if user has specified
  1305. * super-raw mode.
  1306. */
  1307. if (sub->policy.raw > 1) {
  1308. (void)throttled_write(sub,
  1309. (char *)device->lexer.outbuffer,
  1310. device->lexer.outbuflen);
  1311. return;
  1312. }
  1313. #ifdef BINARY_ENABLE
  1314. /*
  1315. * Maybe the user wants a binary packet hexdumped.
  1316. */
  1317. if (sub->policy.raw == 1) {
  1318. const char *hd =
  1319. gpsd_hexdump(device->msgbuf, sizeof(device->msgbuf),
  1320. (char *)device->lexer.outbuffer,
  1321. device->lexer.outbuflen);
  1322. (void)strlcat((char *)hd, "\r\n", sizeof(device->msgbuf));
  1323. (void)throttled_write(sub, (char *)hd, strlen(hd));
  1324. }
  1325. #endif /* BINARY_ENABLE */
  1326. }
  1327. static void pseudonmea_report(struct subscriber_t *sub,
  1328. gps_mask_t changed,
  1329. struct gps_device_t *device)
  1330. /* report pseudo-NMEA in appropriate circumstances */
  1331. {
  1332. if (GPS_PACKET_TYPE(device->lexer.type)
  1333. && !TEXTUAL_PACKET_TYPE(device->lexer.type)) {
  1334. char buf[MAX_PACKET_LENGTH * 3 + 2];
  1335. if ((changed & REPORT_IS) != 0) {
  1336. nmea_tpv_dump(device, buf, sizeof(buf));
  1337. GPSD_LOG(LOG_IO, &context.errout,
  1338. "<= GPS (binary tpv) %s: %s\n",
  1339. device->gpsdata.dev.path, buf);
  1340. (void)throttled_write(sub, buf, strlen(buf));
  1341. }
  1342. if ((changed & (SATELLITE_SET|USED_IS)) != 0) {
  1343. nmea_sky_dump(device, buf, sizeof(buf));
  1344. GPSD_LOG(LOG_IO, &context.errout,
  1345. "<= GPS (binary sky) %s: %s\n",
  1346. device->gpsdata.dev.path, buf);
  1347. (void)throttled_write(sub, buf, strlen(buf));
  1348. }
  1349. if ((changed & SUBFRAME_SET) != 0) {
  1350. nmea_subframe_dump(device, buf, sizeof(buf));
  1351. GPSD_LOG(LOG_IO, &context.errout,
  1352. "<= GPS (binary subframe) %s: %s\n",
  1353. device->gpsdata.dev.path, buf);
  1354. (void)throttled_write(sub, buf, strlen(buf));
  1355. }
  1356. #ifdef AIVDM_ENABLE
  1357. if ((changed & AIS_SET) != 0) {
  1358. nmea_ais_dump(device, buf, sizeof(buf));
  1359. GPSD_LOG(LOG_IO, &context.errout,
  1360. "<= AIS (binary ais) %s: %s\n",
  1361. device->gpsdata.dev.path, buf);
  1362. (void)throttled_write(sub, buf, strlen(buf));
  1363. }
  1364. #endif /* AIVDM_ENABLE */
  1365. }
  1366. }
  1367. #endif /* SOCKET_EXPORT_ENABLE */
  1368. static void all_reports(struct gps_device_t *device, gps_mask_t changed)
  1369. /* report on the current packet from a specified device */
  1370. {
  1371. #ifdef SOCKET_EXPORT_ENABLE
  1372. struct subscriber_t *sub;
  1373. /* add any just-identified device to watcher lists */
  1374. if ((changed & DRIVER_IS) != 0) {
  1375. bool listeners = false;
  1376. for (sub = subscribers;
  1377. sub < subscribers + MAX_CLIENTS; sub++)
  1378. if (sub->active != 0
  1379. && sub->policy.watcher
  1380. && subscribed(sub, device))
  1381. listeners = true;
  1382. if (listeners) {
  1383. (void)awaken(device);
  1384. }
  1385. }
  1386. /* handle laggy response to a firmware version query */
  1387. if ((changed & (DEVICEID_SET | DRIVER_IS)) != 0) {
  1388. if (device->device_type == NULL)
  1389. GPSD_LOG(LOG_ERROR, &context.errout,
  1390. "internal error - device type of %s not set "
  1391. "when expected\n",
  1392. device->gpsdata.dev.path);
  1393. else
  1394. {
  1395. char id2[GPS_JSON_RESPONSE_MAX];
  1396. json_device_dump(device, id2, sizeof(id2));
  1397. notify_watchers(device, true, false, id2);
  1398. }
  1399. }
  1400. #endif /* SOCKET_EXPORT_ENABLE */
  1401. /*
  1402. * If the device provided an RTCM packet, repeat it to all devices.
  1403. */
  1404. if ((changed & RTCM2_SET) != 0 || (changed & RTCM3_SET) != 0) {
  1405. if ((changed & RTCM2_SET) != 0
  1406. && device->lexer.outbuflen > RTCM_MAX) {
  1407. GPSD_LOG(LOG_ERROR, &context.errout,
  1408. "overlong RTCM packet (%zd bytes)\n",
  1409. device->lexer.outbuflen);
  1410. } else if ((changed & RTCM3_SET) != 0
  1411. && device->lexer.outbuflen > RTCM3_MAX) {
  1412. GPSD_LOG(LOG_ERROR, &context.errout,
  1413. "overlong RTCM3 packet (%zd bytes)\n",
  1414. device->lexer.outbuflen);
  1415. } else {
  1416. struct gps_device_t *dp;
  1417. for (dp = devices; dp < devices+MAX_DEVICES; dp++) {
  1418. if (allocated_device(dp)) {
  1419. /* *INDENT-OFF* */
  1420. if (NULL != dp->device_type &&
  1421. NULL != dp->device_type->rtcm_writer) {
  1422. // FIXME: don't write back to source
  1423. ssize_t ret = dp->device_type->rtcm_writer(dp,
  1424. (const char *)device->lexer.outbuffer,
  1425. device->lexer.outbuflen);
  1426. if (0 < ret) {
  1427. GPSD_LOG(LOG_IO, &context.errout,
  1428. "<= DGPS: %zd bytes of RTCM relayed.\n",
  1429. device->lexer.outbuflen);
  1430. } else if (0 == ret) {
  1431. // nothing written, probably read_only
  1432. } else {
  1433. GPSD_LOG(LOG_ERROR, &context.errout,
  1434. "Write to RTCM sink failed, type %s\n",
  1435. dp->device_type->type_name);
  1436. }
  1437. }
  1438. /* *INDENT-ON* */
  1439. }
  1440. }
  1441. }
  1442. }
  1443. /*
  1444. * Time is eligible for shipping to NTPD if the driver has
  1445. * asserted NTPTIME_IS at any point in the current cycle.
  1446. */
  1447. if ((changed & CLEAR_IS)!=0)
  1448. device->ship_to_ntpd = false;
  1449. if ((changed & NTPTIME_IS)!=0)
  1450. device->ship_to_ntpd = true;
  1451. /*
  1452. * Only update the NTP time if we've seen the leap-seconds data.
  1453. * Else we may be providing GPS time.
  1454. */
  1455. if ((changed & TIME_SET) == 0) {
  1456. //GPSD_LOG(LOG_PROG, &context.errout, "NTP: No time this packet\n");
  1457. } else if ( 0 >= device->fixcnt && !batteryRTC ) {
  1458. /* many GPS spew random times until a valid GPS fix */
  1459. /* allow override with -r optin */
  1460. //GPSD_LOG(LOG_PROG, &context.errout, "NTP: no fix\n");
  1461. } else if (0 == device->newdata.time.tv_sec) {
  1462. //GPSD_LOG(LOG_PROG, &context.errout, "NTP: bad new time\n");
  1463. } else if (device->newdata.time.tv_sec <=
  1464. device->pps_thread.fix_in.real.tv_sec) {
  1465. //GPSD_LOG(LOG_PROG, &context.errout, "NTP: Not a new time\n");
  1466. } else if (!device->ship_to_ntpd) {
  1467. //GPSD_LOG(LOG_PROG, &context.errout,
  1468. // "NTP: No precision time report\n");
  1469. } else {
  1470. struct timedelta_t td;
  1471. struct gps_device_t *ppsonly;
  1472. ntp_latch(device, &td);
  1473. /* propagate this in-band-time to all PPS-only devices */
  1474. for (ppsonly = devices; ppsonly < devices + MAX_DEVICES; ppsonly++)
  1475. if (ppsonly->sourcetype == source_pps)
  1476. pps_thread_fixin(&ppsonly->pps_thread, &td);
  1477. if (device->shm_clock != NULL) {
  1478. (void)ntpshm_put(device, device->shm_clock, &td);
  1479. }
  1480. #ifdef SOCKET_EXPORT_ENABLE
  1481. notify_watchers(device, false, true,
  1482. "{\"class\":\"TOFF\",\"device\":\"%s\",\"real_sec\":"
  1483. "%lld, \"real_nsec\":%ld,\"clock_sec\":%lld,"
  1484. "\"clock_nsec\":%ld}\r\n",
  1485. device->gpsdata.dev.path,
  1486. (long long)td.real.tv_sec, td.real.tv_nsec,
  1487. (long long)td.clock.tv_sec, td.clock.tv_nsec);
  1488. #endif /* SOCKET_EXPORT_ENABLE */
  1489. }
  1490. /*
  1491. * If no reliable end of cycle, must report every time
  1492. * a sentence changes position or mode. Likely to
  1493. * cause display jitter.
  1494. */
  1495. if (!device->cycle_end_reliable && (changed & (LATLON_SET | MODE_SET))!=0)
  1496. changed |= REPORT_IS;
  1497. /* a few things are not per-subscriber reports */
  1498. if ((changed & REPORT_IS) != 0) {
  1499. #ifdef NETFEED_ENABLE
  1500. if (device->gpsdata.fix.mode == MODE_3D) {
  1501. struct gps_device_t *dgnss;
  1502. /*
  1503. * Pass the fix to every potential caster, here.
  1504. * netgnss_report() individual caster types get to
  1505. * make filtering decisiona.
  1506. */
  1507. for (dgnss = devices; dgnss < devices + MAX_DEVICES; dgnss++)
  1508. if (dgnss != device)
  1509. netgnss_report(&context, device, dgnss);
  1510. }
  1511. #endif /* NETFEED_ENABLE */
  1512. #if defined(DBUS_EXPORT_ENABLE)
  1513. if (device->gpsdata.fix.mode > MODE_NO_FIX)
  1514. send_dbus_fix(device);
  1515. #endif /* defined(DBUS_EXPORT_ENABLE) */
  1516. }
  1517. #ifdef SHM_EXPORT_ENABLE
  1518. if ((changed & (REPORT_IS|GST_SET|SATELLITE_SET|SUBFRAME_SET|
  1519. ATTITUDE_SET|RTCM2_SET|RTCM3_SET|AIS_SET)) != 0)
  1520. shm_update(&context, &device->gpsdata);
  1521. #endif /* SHM_EXPORT_ENABLE */
  1522. #ifdef SOCKET_EXPORT_ENABLE
  1523. /* update all subscribers associated with this device */
  1524. for (sub = subscribers; sub < subscribers + MAX_CLIENTS; sub++) {
  1525. if (sub == NULL || sub->active == 0 || !subscribed(sub, device))
  1526. continue;
  1527. #ifdef PASSTHROUGH_ENABLE
  1528. /* this is for passing through JSON packets */
  1529. if ((changed & PASSTHROUGH_IS) != 0) {
  1530. (void)strlcat((char *)device->lexer.outbuffer,
  1531. "\r\n",
  1532. sizeof(device->lexer.outbuffer));
  1533. (void)throttled_write(sub,
  1534. (char *)device->lexer.outbuffer,
  1535. device->lexer.outbuflen+2);
  1536. continue;
  1537. }
  1538. #endif /* PASSTHROUGH_ENABLE */
  1539. /* report raw packets to users subscribed to those */
  1540. raw_report(sub, device);
  1541. /* some listeners may be in watcher mode */
  1542. if (sub->policy.watcher) {
  1543. if (changed & DATA_IS) {
  1544. GPSD_LOG(LOG_PROG, &context.errout,
  1545. "Changed mask: %s with %sreliable "
  1546. "cycle detection\n",
  1547. gps_maskdump(changed),
  1548. device->cycle_end_reliable ? "" : "un");
  1549. if ((changed & REPORT_IS) != 0)
  1550. GPSD_LOG(LOG_PROG, &context.errout,
  1551. "time to report a fix\n");
  1552. if (sub->policy.nmea)
  1553. pseudonmea_report(sub, changed, device);
  1554. if (sub->policy.json) {
  1555. char buf[GPS_JSON_RESPONSE_MAX * 4];
  1556. if ((changed & AIS_SET) != 0)
  1557. if (device->gpsdata.ais.type == 24
  1558. && device->gpsdata.ais.type24.part != both
  1559. && !sub->policy.split24)
  1560. continue;
  1561. json_data_report(changed, device, &sub->policy,
  1562. buf, sizeof(buf));
  1563. if (buf[0] != '\0')
  1564. (void)throttled_write(sub, buf, strlen(buf));
  1565. }
  1566. }
  1567. }
  1568. } /* subscribers */
  1569. #endif /* SOCKET_EXPORT_ENABLE */
  1570. }
  1571. #ifdef SOCKET_EXPORT_ENABLE
  1572. /* Execute GPSD requests (?POLL, ?WATCH, etc.) from a buffer.
  1573. * The entire request must be in the buffer.
  1574. */
  1575. static int handle_gpsd_request(struct subscriber_t *sub, const char *buf)
  1576. {
  1577. char reply[GPS_JSON_RESPONSE_MAX + 1];
  1578. reply[0] = '\0';
  1579. if (buf[0] == '?') {
  1580. const char *end;
  1581. for (end = buf; *buf != '\0'; buf = end)
  1582. if (isspace((unsigned char) *buf))
  1583. end = buf + 1;
  1584. else
  1585. handle_request(sub, buf, &end,
  1586. reply + strlen(reply),
  1587. sizeof(reply) - strlen(reply));
  1588. }
  1589. return (int)throttled_write(sub, reply, strlen(reply));
  1590. }
  1591. #endif /* SOCKET_EXPORT_ENABLE */
  1592. #if defined(CONTROL_SOCKET_ENABLE) && defined(SOCKET_EXPORT_ENABLE)
  1593. static void ship_pps_message(struct gps_device_t *session,
  1594. struct timedelta_t *td)
  1595. /* on PPS interrupt, ship a message to all clients */
  1596. {
  1597. int precision = -20;
  1598. char buf[GPS_JSON_RESPONSE_MAX];
  1599. char ts_str[TIMESPEC_LEN];
  1600. if ( source_usb == session->sourcetype) {
  1601. /* PPS over USB not so good */
  1602. precision = -10;
  1603. }
  1604. GPSD_LOG(LOG_DATA, &session->context->errout,
  1605. "ship_pps: qErr_time %s qErr %ld, pps.tv_sec %lld\n",
  1606. timespec_str(&session->gpsdata.qErr_time, ts_str, sizeof(ts_str)),
  1607. session->gpsdata.qErr,
  1608. (long long)td->real.tv_sec);
  1609. /* real_XXX - the time the GPS thinks it is at the PPS edge */
  1610. /* clock_XXX - the time the system clock thinks it is at the PPS edge */
  1611. (void)snprintf(buf, sizeof(buf),
  1612. "{\"class\":\"PPS\",\"device\":\"%s\",\"real_sec\":%lld,"
  1613. "\"real_nsec\":%ld,\"clock_sec\":%lld,\"clock_nsec\":%ld,"
  1614. "\"precision\":%d",
  1615. session->gpsdata.dev.path,
  1616. (long long)td->real.tv_sec, td->real.tv_nsec,
  1617. (long long)td->clock.tv_sec, td->clock.tv_nsec,
  1618. precision);
  1619. // output qErr if timestamps line up
  1620. if (td->real.tv_sec == session->gpsdata.qErr_time.tv_sec) {
  1621. str_appendf(buf, sizeof(buf), ",\"qErr\":%ld",
  1622. session->gpsdata.qErr);
  1623. }
  1624. (void)strlcat(buf, "}\r\n", sizeof(buf));
  1625. notify_watchers(session, true, true, buf);
  1626. /*
  1627. * PPS receipt resets the device's timeout. This keeps PPS-only
  1628. * devices, which never deliver in-band data, from timing out.
  1629. */
  1630. (void)clock_gettime(CLOCK_REALTIME, &session->gpsdata.online);
  1631. }
  1632. #endif
  1633. #ifdef __UNUSED_AUTOCONNECT__
  1634. #define DGPS_THRESHOLD 1600000 /* max. useful dist. from DGPS server (m) */
  1635. #define SERVER_SAMPLE 12 /* # of servers within threshold to check */
  1636. struct dgps_server_t
  1637. {
  1638. double lat, lon;
  1639. char server[257];
  1640. double dist;
  1641. };
  1642. static int srvcmp(const void *s, const void *t)
  1643. {
  1644. return (int)(((const struct dgps_server_t *)s)->dist - ((const struct dgps_server_t *)t)->dist); /* fixes: warning: cast discards qualifiers from pointer target type */
  1645. }
  1646. static void netgnss_autoconnect(struct gps_context_t *context,
  1647. double lat, double lon, const char *serverlist)
  1648. /* tell the library to talk to the nearest DGPSIP server */
  1649. {
  1650. struct dgps_server_t keep[SERVER_SAMPLE], hold, *sp, *tp;
  1651. char buf[BUFSIZ];
  1652. FILE *sfp = fopen(serverlist, "r");
  1653. if (sfp == NULL) {
  1654. GPSD_LOG(LOG_ERROR, &context.errout, "no DGPS server list found.\n");
  1655. return;
  1656. }
  1657. for (sp = keep; sp < keep + SERVER_SAMPLE; sp++) {
  1658. sp->dist = DGPS_THRESHOLD;
  1659. sp->server[0] = '\0';
  1660. }
  1661. hold.lat = hold.lon = 0;
  1662. while (fgets(buf, (int)sizeof(buf), sfp)) {
  1663. char *cp = strchr(buf, '#');
  1664. if (cp != NULL)
  1665. *cp = '\0';
  1666. if (sscanf(buf, "%32lf %32lf %256s", &hold.lat, &hold.lon, hold.server) ==
  1667. 3) {
  1668. hold.dist = earth_distance(lat, lon, hold.lat, hold.lon);
  1669. tp = NULL;
  1670. /*
  1671. * The idea here is to look for a server in the sample array
  1672. * that is (a) closer than the one we're checking, and (b)
  1673. * furtherest away of all those that are closer. Replace it.
  1674. * In this way we end up with the closest possible set.
  1675. */
  1676. for (sp = keep; sp < keep + SERVER_SAMPLE; sp++)
  1677. if (hold.dist < sp->dist
  1678. && (tp == NULL || hold.dist > tp->dist))
  1679. tp = sp;
  1680. if (tp != NULL)
  1681. *tp = hold;
  1682. }
  1683. }
  1684. (void)fclose(sfp);
  1685. if (keep[0].server[0] == '\0') {
  1686. GPSD_LOG(LOG_ERROR, &context.errout,
  1687. "no DGPS servers within %dm.\n",
  1688. (int)(DGPS_THRESHOLD / 1000));
  1689. return;
  1690. }
  1691. /* sort them and try the closest first */
  1692. qsort((void *)keep, SERVER_SAMPLE, sizeof(struct dgps_server_t), srvcmp);
  1693. for (sp = keep; sp < keep + SERVER_SAMPLE; sp++) {
  1694. if (sp->server[0] != '\0') {
  1695. GPSD_LOG(LOG_INF, &context.errout,
  1696. "%s is %dkm away.\n", sp->server,
  1697. (int)(sp->dist / 1000));
  1698. if (dgpsip_open(context, sp->server) >= 0)
  1699. break;
  1700. }
  1701. }
  1702. }
  1703. #endif /* __UNUSED_AUTOCONNECT__ */
  1704. static void gpsd_terminate(struct gps_context_t *context)
  1705. /* finish cleanly, reverting device configuration */
  1706. {
  1707. int dfd;
  1708. for (dfd = 0; dfd < MAX_DEVICES; dfd++) {
  1709. if (allocated_device(&devices[dfd])) {
  1710. (void)gpsd_wrap(&devices[dfd]);
  1711. }
  1712. }
  1713. context->pps_hook = NULL; /* tell any PPS-watcher thread to die */
  1714. }
  1715. int main(int argc, char *argv[])
  1716. {
  1717. /* some of these statics suppress -W warnings due to longjmp() */
  1718. #ifdef SOCKET_EXPORT_ENABLE
  1719. static char *gpsd_service = NULL;
  1720. struct subscriber_t *sub;
  1721. #endif /* SOCKET_EXPORT_ENABLE */
  1722. fd_set rfds;
  1723. #ifdef CONTROL_SOCKET_ENABLE
  1724. fd_set control_fds;
  1725. #endif /* CONTROL_SOCKET_ENABLE */
  1726. #ifdef CONTROL_SOCKET_ENABLE
  1727. static socket_t csock;
  1728. socket_t cfd;
  1729. static char *control_socket = NULL;
  1730. #endif /* CONTROL_SOCKET_ENABLE */
  1731. #if defined(SOCKET_EXPORT_ENABLE) || defined(CONTROL_SOCKET_ENABLE)
  1732. sockaddr_t fsin;
  1733. #endif /* defined(SOCKET_EXPORT_ENABLE) || defined(CONTROL_SOCKET_ENABLE) */
  1734. static char *pid_file = NULL;
  1735. struct gps_device_t *device;
  1736. int i, option;
  1737. int msocks[2] = {-1, -1};
  1738. bool device_opened = false;
  1739. bool go_background = true;
  1740. volatile bool in_restart;
  1741. gps_context_init(&context, "gpsd");
  1742. #ifdef CONTROL_SOCKET_ENABLE
  1743. INVALIDATE_SOCKET(csock);
  1744. #if defined(SOCKET_EXPORT_ENABLE)
  1745. context.pps_hook = ship_pps_message;
  1746. #endif /* SOCKET_EXPORT_ENABLE */
  1747. #endif /* CONTROL_SOCKET_ENABLE */
  1748. while ((option = getopt(argc, argv, "bD:F:f:GhlNnP:rS:s:V")) != -1) {
  1749. switch (option) {
  1750. case 'b':
  1751. context.readonly = true;
  1752. break;
  1753. case 'D':
  1754. // accept decimal, octal and hex
  1755. context.errout.debug = (int)strtol(optarg, 0, 0);
  1756. #ifdef CLIENTDEBUG_ENABLE
  1757. gps_enable_debug(context.errout.debug, stderr);
  1758. #endif /* CLIENTDEBUG_ENABLE */
  1759. break;
  1760. #ifdef CONTROL_SOCKET_ENABLE
  1761. case 'F':
  1762. control_socket = optarg;
  1763. break;
  1764. #endif /* CONTROL_SOCKET_ENABLE */
  1765. case 'f':
  1766. // framing
  1767. if (3 == strlen(optarg) &&
  1768. ('7' == optarg[0] || '8' == optarg[0]) &&
  1769. ('E' == optarg[1] || 'N' == optarg[1] ||
  1770. 'O' == optarg[1]) &&
  1771. ('0' <= optarg[2] && '2' >= optarg[2])) {
  1772. // [78][ENO][012]
  1773. (void)strlcpy(context.fixed_port_framing, optarg,
  1774. sizeof(context.fixed_port_framing));
  1775. } else {
  1776. // invalid framing
  1777. GPSD_LOG(LOG_ERROR, &context.errout,
  1778. "-f has invalid framing %s\n", optarg);
  1779. exit(1);
  1780. }
  1781. break;
  1782. #ifndef FORCE_GLOBAL_ENABLE
  1783. case 'G':
  1784. listen_global = true;
  1785. break;
  1786. #endif /* FORCE_GLOBAL_ENABLE */
  1787. case 'l': /* list known device types and exit */
  1788. typelist();
  1789. break;
  1790. case 'N':
  1791. go_background = false;
  1792. break;
  1793. case 'n':
  1794. nowait = true;
  1795. break;
  1796. case 'P':
  1797. pid_file = optarg;
  1798. break;
  1799. case 'r':
  1800. batteryRTC = true;
  1801. break;
  1802. case 'S':
  1803. #ifdef SOCKET_EXPORT_ENABLE
  1804. gpsd_service = optarg;
  1805. #endif /* SOCKET_EXPORT_ENABLE */
  1806. break;
  1807. case 's':
  1808. {
  1809. // accept decimal, octal and hex
  1810. long speed = strtol(optarg, 0, 0);
  1811. if (0 < speed) {
  1812. // allow weird speeds
  1813. context.fixed_port_speed = (speed_t)speed;
  1814. } else {
  1815. // invalid speed
  1816. GPSD_LOG(LOG_ERROR, &context.errout,
  1817. "-s has invalid speed %ld\n", speed);
  1818. exit(1);
  1819. }
  1820. }
  1821. break;
  1822. case 'V':
  1823. (void)printf("%s: %s (revision %s)\n", argv[0], VERSION, REVISION);
  1824. exit(EXIT_SUCCESS);
  1825. case 'h':
  1826. // FALLTHROUGH
  1827. case '?':
  1828. // FALLTHROUGH
  1829. default:
  1830. usage();
  1831. exit(EXIT_SUCCESS);
  1832. }
  1833. }
  1834. /* sanity check */
  1835. if (argc - optind > MAX_DEVICES) {
  1836. GPSD_LOG(LOG_ERROR, &context.errout,
  1837. "Too many devices on command line.\n");
  1838. exit(1);
  1839. }
  1840. if (8 > sizeof(time_t)) {
  1841. GPSD_LOG(LOG_WARN, &context.errout,
  1842. "This system has a 32-bit time_t. "
  1843. "This gpsd will fail at 2038-01-19T03:14:07Z.\n");
  1844. }
  1845. #if defined(SYSTEMD_ENABLE) && defined(CONTROL_SOCKET_ENABLE)
  1846. sd_socket_count = sd_get_socket_count();
  1847. if (sd_socket_count > 0 && control_socket != NULL) {
  1848. GPSD_LOG(LOG_WARN, &context.errout,
  1849. "control socket passed on command line ignored\n");
  1850. control_socket = NULL;
  1851. }
  1852. #endif
  1853. #if defined(CONTROL_SOCKET_ENABLE) || defined(SYSTEMD_ENABLE)
  1854. if (
  1855. #ifdef CONTROL_SOCKET_ENABLE
  1856. control_socket == NULL
  1857. #endif
  1858. #if defined(CONTROL_SOCKET_ENABLE) && defined(SYSTEMD_ENABLE)
  1859. &&
  1860. #endif
  1861. #ifdef SYSTEMD_ENABLE
  1862. sd_socket_count <= 0
  1863. #endif
  1864. && optind >= argc) {
  1865. GPSD_LOG(LOG_ERROR, &context.errout,
  1866. "can't run with neither control socket nor devices\n");
  1867. exit(EXIT_FAILURE);
  1868. }
  1869. /*
  1870. * Control socket has to be created before we go background in order to
  1871. * avoid a race condition in which hotplug scripts can try opening
  1872. * the socket before it's created.
  1873. */
  1874. #if defined(SYSTEMD_ENABLE) && defined(CONTROL_SOCKET_ENABLE)
  1875. if (sd_socket_count > 0) {
  1876. csock = SD_SOCKET_FDS_START;
  1877. FD_SET(csock, &all_fds);
  1878. adjust_max_fd(csock, true);
  1879. }
  1880. #endif
  1881. #ifdef CONTROL_SOCKET_ENABLE
  1882. if (control_socket) {
  1883. (void)unlink(control_socket);
  1884. if (BAD_SOCKET(csock = filesock(control_socket))) {
  1885. GPSD_LOG(LOG_ERROR, &context.errout,
  1886. "control socket create failed, netlib error %d\n",
  1887. csock);
  1888. exit(EXIT_FAILURE);
  1889. } else
  1890. GPSD_LOG(LOG_SPIN, &context.errout,
  1891. "control socket %s is fd %d\n",
  1892. control_socket, csock);
  1893. FD_SET(csock, &all_fds);
  1894. adjust_max_fd(csock, true);
  1895. GPSD_LOG(LOG_PROG, &context.errout,
  1896. "control socket opened at %s\n",
  1897. control_socket);
  1898. }
  1899. #endif /* CONTROL_SOCKET_ENABLE */
  1900. #else
  1901. if (optind >= argc) {
  1902. GPSD_LOG(LOG_ERROR, &context.errout,
  1903. "can't run with no devices specified\n");
  1904. exit(EXIT_FAILURE);
  1905. }
  1906. #endif /* defined(CONTROL_SOCKET_ENABLE) || defined(SYSTEMD_ENABLE) */
  1907. // TODO, a dump of all options here at LOG_xx would be nice.
  1908. /* might be time to daemonize */
  1909. if (go_background) {
  1910. /* not SuS/POSIX portable, but we have our own fallback version */
  1911. if (os_daemon(0, 0) != 0)
  1912. GPSD_LOG(LOG_ERROR, &context.errout,
  1913. "daemonization failed: %s\n",strerror(errno));
  1914. }
  1915. if (pid_file != NULL) {
  1916. FILE *fp;
  1917. if ((fp = fopen(pid_file, "w")) != NULL) {
  1918. (void)fprintf(fp, "%u\n", (unsigned int)getpid());
  1919. (void)fclose(fp);
  1920. } else {
  1921. GPSD_LOG(LOG_ERROR, &context.errout,
  1922. "Cannot create PID file: %s.\n", pid_file);
  1923. }
  1924. }
  1925. openlog("gpsd", LOG_PID, LOG_USER);
  1926. GPSD_LOG(LOG_INF, &context.errout, "launching (Version %s)\n", VERSION);
  1927. #ifdef SOCKET_EXPORT_ENABLE
  1928. if (!gpsd_service)
  1929. gpsd_service =
  1930. getservbyname("gpsd", "tcp") ? "gpsd" : DEFAULT_GPSD_PORT;
  1931. if (passivesocks(gpsd_service, "tcp", QLEN, msocks) < 1) {
  1932. GPSD_LOG(LOG_ERROR, &context.errout,
  1933. "command sockets creation failed, netlib errors %d, %d\n",
  1934. msocks[0], msocks[1]);
  1935. if (pid_file != NULL)
  1936. (void)unlink(pid_file);
  1937. exit(EXIT_FAILURE);
  1938. }
  1939. GPSD_LOG(LOG_INF, &context.errout, "listening on port %s\n",
  1940. gpsd_service);
  1941. #endif /* SOCKET_EXPORT_ENABLE */
  1942. if (getuid() == 0) {
  1943. errno = 0;
  1944. // nice() can ONLY succeed when run as root!
  1945. // do not even bother as non-root
  1946. if (nice(NICEVAL) == -1 && errno != 0)
  1947. GPSD_LOG(LOG_WARN, &context.errout,
  1948. "PPS: o=priority setting failed. Time accuracy "
  1949. "will be degraded\n");
  1950. }
  1951. /*
  1952. * By initializing before we drop privileges, we guarantee that even
  1953. * hotplugged devices added *after* we drop privileges will be able
  1954. * to use segments 0 and 1.
  1955. */
  1956. (void)ntpshm_context_init(&context);
  1957. #if defined(DBUS_EXPORT_ENABLE)
  1958. /* we need to connect to dbus as root */
  1959. if (initialize_dbus_connection()) {
  1960. /* the connection could not be started */
  1961. GPSD_LOG(LOG_ERROR, &context.errout,
  1962. "unable to connect to the DBUS system bus\n");
  1963. } else
  1964. GPSD_LOG(LOG_PROG, &context.errout,
  1965. "successfully connected to the DBUS system bus\n");
  1966. #endif /* defined(DBUS_EXPORT_ENABLE) */
  1967. #ifdef SHM_EXPORT_ENABLE
  1968. /* create the shared segment as root so readers can't mess with it */
  1969. (void)shm_acquire(&context);
  1970. #endif /* SHM_EXPORT_ENABLE */
  1971. /*
  1972. * We open devices specified on the command line *before* dropping
  1973. * privileges in case one of them is a serial device with PPS support
  1974. * and we need to set the line discipline, which requires root.
  1975. */
  1976. in_restart = false;
  1977. for (i = optind; i < argc; i++) {
  1978. if (!gpsd_add_device(argv[i], nowait)) {
  1979. GPSD_LOG(LOG_ERROR, &context.errout,
  1980. "initial GPS device %s open failed\n",
  1981. argv[i]);
  1982. } else {
  1983. device_opened = true;
  1984. }
  1985. }
  1986. if (
  1987. #ifdef CONTROL_SOCKET_ENABLE
  1988. control_socket == NULL &&
  1989. #endif
  1990. #ifdef SYSTEMD_ENABLE
  1991. sd_socket_count <= 0 &&
  1992. #endif
  1993. !device_opened) {
  1994. GPSD_LOG(LOG_ERROR, &context.errout,
  1995. "can't run with neither control socket nor devices open\n");
  1996. exit(EXIT_FAILURE);
  1997. }
  1998. /* drop privileges */
  1999. if (0 == getuid()) {
  2000. struct passwd *pw;
  2001. struct stat stb;
  2002. /* make default devices accessible even after we drop privileges */
  2003. for (i = optind; i < argc; i++)
  2004. /* coverity[toctou] */
  2005. if (stat(argv[i], &stb) == 0)
  2006. (void)chmod(argv[i], stb.st_mode | S_IRGRP | S_IWGRP);
  2007. /*
  2008. * Drop privileges. Up to now we've been running as root.
  2009. * Instead, set the user ID to 'nobody' (or whatever the gpsd
  2010. * user set by thre build is) and the group ID to the owning
  2011. * group of a prototypical TTY device. This limits the scope
  2012. * of any compromises in the code. It requires that all GPS
  2013. * devices have their group read/write permissions set.
  2014. */
  2015. if (setgroups(0, NULL) != 0)
  2016. GPSD_LOG(LOG_ERROR, &context.errout,
  2017. "setgroups() failed, errno %s\n",
  2018. strerror(errno));
  2019. #ifdef GPSD_GROUP
  2020. {
  2021. struct group *grp = getgrnam(GPSD_GROUP);
  2022. if (grp)
  2023. if (setgid(grp->gr_gid) != 0)
  2024. GPSD_LOG(LOG_ERROR, &context.errout,
  2025. "setgid() failed, errno %s\n",
  2026. strerror(errno));
  2027. }
  2028. #else
  2029. if ((optind < argc && stat(argv[optind], &stb) == 0)
  2030. || stat(PROTO_TTY, &stb) == 0) {
  2031. GPSD_LOG(LOG_PROG, &context.errout,
  2032. "changing to group %d\n", stb.st_gid);
  2033. if (setgid(stb.st_gid) != 0)
  2034. GPSD_LOG(LOG_ERROR, &context.errout,
  2035. "setgid() failed, errno %s\n",
  2036. strerror(errno));
  2037. }
  2038. #endif
  2039. pw = getpwnam(GPSD_USER);
  2040. if (pw)
  2041. if (setuid(pw->pw_uid) != 0)
  2042. GPSD_LOG(LOG_ERROR, &context.errout,
  2043. "setuid() failed, errno %s\n",
  2044. strerror(errno));
  2045. }
  2046. GPSD_LOG(LOG_INF, &context.errout,
  2047. "running with effective group ID %d\n", getegid());
  2048. GPSD_LOG(LOG_INF, &context.errout,
  2049. "running with effective user ID %d\n", geteuid());
  2050. #ifdef SOCKET_EXPORT_ENABLE
  2051. for (i = 0; i < NITEMS(subscribers); i++) {
  2052. subscribers[i].fd = UNALLOCATED_FD;
  2053. (void)pthread_mutex_init(&subscribers[i].mutex, NULL);
  2054. }
  2055. #endif /* SOCKET_EXPORT_ENABLE*/
  2056. {
  2057. struct sigaction sa;
  2058. sa.sa_flags = 0;
  2059. #ifdef __COVERITY__
  2060. /*
  2061. * Obsolete and unused. We're only doing this to pacify Coverity
  2062. * which otherwise throws an UNINIT event here. Don't swap with the
  2063. * handler initialization, they're unioned on some architectures.
  2064. */
  2065. sa.sa_restorer = NULL;
  2066. #endif /* __COVERITY__ */
  2067. sa.sa_handler = onsig;
  2068. (void)sigfillset(&sa.sa_mask);
  2069. (void)sigaction(SIGHUP, &sa, NULL);
  2070. (void)sigaction(SIGINT, &sa, NULL);
  2071. (void)sigaction(SIGTERM, &sa, NULL);
  2072. (void)sigaction(SIGQUIT, &sa, NULL);
  2073. (void)signal(SIGPIPE, SIG_IGN);
  2074. }
  2075. /* daemon got termination or interrupt signal */
  2076. if (setjmp(restartbuf) > 0) {
  2077. gpsd_terminate(&context);
  2078. in_restart = true;
  2079. GPSD_LOG(LOG_WARN, &context.errout, "gpsd restarted by SIGHUP\n");
  2080. }
  2081. signalled = 0;
  2082. for (i = 0; i < AFCOUNT; i++)
  2083. if (msocks[i] >= 0) {
  2084. FD_SET(msocks[i], &all_fds);
  2085. adjust_max_fd(msocks[i], true);
  2086. }
  2087. #ifdef CONTROL_SOCKET_ENABLE
  2088. FD_ZERO(&control_fds);
  2089. #endif /* CONTROL_SOCKET_ENABLE */
  2090. /* initialize the GPS context's time fields */
  2091. gpsd_time_init(&context, time(NULL));
  2092. /*
  2093. * If we got here via SIGINT, reopen any command-line devices. PPS
  2094. * through these won't work, as we've dropped privileges and can
  2095. * no longer change line disciplines.
  2096. */
  2097. if (in_restart)
  2098. for (i = optind; i < argc; i++) {
  2099. if (!gpsd_add_device(argv[i], nowait)) {
  2100. GPSD_LOG(LOG_ERROR, &context.errout,
  2101. "GPS device %s open failed\n",
  2102. argv[i]);
  2103. }
  2104. }
  2105. while (0 == signalled) {
  2106. fd_set efds;
  2107. GPSD_LOG(LOG_RAW + 1, &context.errout, "await data\n");
  2108. switch(gpsd_await_data(&rfds, &efds, maxfd, &all_fds, &context.errout))
  2109. {
  2110. case AWAIT_GOT_INPUT:
  2111. break;
  2112. case AWAIT_NOT_READY:
  2113. for (device = devices; device < devices + MAX_DEVICES; device++)
  2114. /*
  2115. * The file descriptor validity check is required on some ARM
  2116. * platforms to prevent a core dump. This may be due to an
  2117. * implimentation error in FD_ISSET().
  2118. */
  2119. if (allocated_device(device)
  2120. && (0 <= device->gpsdata.gps_fd && device->gpsdata.gps_fd < (socket_t)FD_SETSIZE)
  2121. && FD_ISSET(device->gpsdata.gps_fd, &efds)) {
  2122. deactivate_device(device);
  2123. free_device(device);
  2124. }
  2125. continue;
  2126. case AWAIT_FAILED:
  2127. exit(EXIT_FAILURE);
  2128. }
  2129. #ifdef SOCKET_EXPORT_ENABLE
  2130. /* always be open to new client connections */
  2131. for (i = 0; i < AFCOUNT; i++) {
  2132. if (msocks[i] >= 0 && FD_ISSET(msocks[i], &rfds)) {
  2133. socklen_t alen = (socklen_t) sizeof(fsin);
  2134. socket_t ssock =
  2135. accept(msocks[i], (struct sockaddr *)&fsin, &alen);
  2136. if (BAD_SOCKET(ssock))
  2137. GPSD_LOG(LOG_ERROR, &context.errout,
  2138. "accept: fail: %s\n", strerror(errno));
  2139. else {
  2140. struct subscriber_t *client = NULL;
  2141. int opts = fcntl(ssock, F_GETFL);
  2142. static struct linger linger = { 1, RELEASE_TIMEOUT };
  2143. char *c_ip;
  2144. if (opts >= 0)
  2145. (void)fcntl(ssock, F_SETFL, opts | O_NONBLOCK);
  2146. c_ip = netlib_sock2ip(ssock);
  2147. client = allocate_client();
  2148. if (client == NULL) {
  2149. GPSD_LOG(LOG_ERROR, &context.errout,
  2150. "Client %s connect on fd %d -"
  2151. "no subscriber slots available\n", c_ip,
  2152. ssock);
  2153. (void)close(ssock);
  2154. } else
  2155. if (setsockopt
  2156. (ssock, SOL_SOCKET, SO_LINGER, (char *)&linger,
  2157. (int)sizeof(struct linger)) == -1) {
  2158. GPSD_LOG(LOG_ERROR, &context.errout,
  2159. "Error: SETSOCKOPT SO_LINGER\n");
  2160. (void)close(ssock);
  2161. } else {
  2162. char announce[GPS_JSON_RESPONSE_MAX];
  2163. FD_SET(ssock, &all_fds);
  2164. adjust_max_fd(ssock, true);
  2165. client->fd = ssock;
  2166. client->active = time(NULL);
  2167. GPSD_LOG(LOG_SPIN, &context.errout,
  2168. "client %s (%d) connect on fd %d\n", c_ip,
  2169. sub_index(client), ssock);
  2170. json_version_dump(announce, sizeof(announce));
  2171. (void)throttled_write(client, announce,
  2172. strlen(announce));
  2173. }
  2174. }
  2175. FD_CLR(msocks[i], &rfds);
  2176. }
  2177. }
  2178. #endif /* SOCKET_EXPORT_ENABLE */
  2179. #ifdef CONTROL_SOCKET_ENABLE
  2180. /* also be open to new control-socket connections */
  2181. if (csock > -1 && FD_ISSET(csock, &rfds)) {
  2182. socklen_t alen = (socklen_t) sizeof(fsin);
  2183. socket_t ssock = accept(csock, (struct sockaddr *)&fsin, &alen);
  2184. if (BAD_SOCKET(ssock))
  2185. GPSD_LOG(LOG_ERROR, &context.errout,
  2186. "accept: %s\n", strerror(errno));
  2187. else {
  2188. GPSD_LOG(LOG_INF, &context.errout,
  2189. "control socket connect on fd %d\n",
  2190. ssock);
  2191. FD_SET(ssock, &all_fds);
  2192. FD_SET(ssock, &control_fds);
  2193. adjust_max_fd(ssock, true);
  2194. }
  2195. FD_CLR(csock, &rfds);
  2196. }
  2197. /* read any commands that came in over the control socket */
  2198. GPSD_LOG(LOG_RAW + 1, &context.errout, "read control commands");
  2199. for (cfd = 0; cfd < (int)FD_SETSIZE; cfd++)
  2200. if (FD_ISSET(cfd, &control_fds)) {
  2201. char buf[BUFSIZ];
  2202. ssize_t rd;
  2203. while ((rd = read(cfd, buf, sizeof(buf) - 1)) > 0) {
  2204. buf[rd] = '\0';
  2205. GPSD_LOG(LOG_CLIENT, &context.errout,
  2206. "<= control(%d): %s\n", cfd, buf);
  2207. /* coverity[tainted_data] Safe, never handed to exec */
  2208. handle_control(cfd, buf);
  2209. }
  2210. GPSD_LOG(LOG_SPIN, &context.errout,
  2211. "close(%d) of control socket\n", cfd);
  2212. (void)close(cfd);
  2213. FD_CLR(cfd, &all_fds);
  2214. FD_CLR(cfd, &control_fds);
  2215. adjust_max_fd(cfd, false);
  2216. }
  2217. #endif /* CONTROL_SOCKET_ENABLE */
  2218. /* poll all active devices */
  2219. GPSD_LOG(LOG_RAW + 1, &context.errout, "poll active devices");
  2220. for (device = devices; device < devices + MAX_DEVICES; device++)
  2221. if (allocated_device(device) && device->gpsdata.gps_fd > 0)
  2222. switch (gpsd_multipoll(FD_ISSET(device->gpsdata.gps_fd, &rfds),
  2223. device, all_reports, DEVICE_REAWAKE))
  2224. {
  2225. case DEVICE_READY:
  2226. FD_SET(device->gpsdata.gps_fd, &all_fds);
  2227. adjust_max_fd(device->gpsdata.gps_fd, true);
  2228. break;
  2229. case DEVICE_UNREADY:
  2230. FD_CLR(device->gpsdata.gps_fd, &all_fds);
  2231. adjust_max_fd(device->gpsdata.gps_fd, false);
  2232. break;
  2233. case DEVICE_ERROR:
  2234. case DEVICE_EOF:
  2235. deactivate_device(device);
  2236. break;
  2237. default:
  2238. break;
  2239. }
  2240. #ifdef __UNUSED_AUTOCONNECT__
  2241. if (context.fixcnt > 0 && !context.autconnect) {
  2242. for (device = devices; device < devices + MAX_DEVICES; device++) {
  2243. if (device->gpsdata.fix.mode > MODE_NO_FIX) {
  2244. netgnss_autoconnect(&context,
  2245. device->gpsdata.fix.latitude,
  2246. device->gpsdata.fix.longitude);
  2247. context.autconnect = True;
  2248. break;
  2249. }
  2250. }
  2251. }
  2252. #endif /* __UNUSED_AUTOCONNECT__ */
  2253. #ifdef SOCKET_EXPORT_ENABLE
  2254. /* accept and execute commands for all clients */
  2255. for (sub = subscribers; sub < subscribers + MAX_CLIENTS; sub++) {
  2256. if (sub->active == 0)
  2257. continue;
  2258. lock_subscriber(sub);
  2259. if (FD_ISSET(sub->fd, &rfds)) {
  2260. char buf[BUFSIZ];
  2261. int buflen;
  2262. unlock_subscriber(sub);
  2263. GPSD_LOG(LOG_PROG, &context.errout,
  2264. "checking client(%d)\n",
  2265. sub_index(sub));
  2266. if ((buflen =
  2267. (int)recv(sub->fd, buf, sizeof(buf) - 1, 0)) <= 0) {
  2268. detach_client(sub);
  2269. } else {
  2270. if (buf[buflen - 1] != '\n')
  2271. buf[buflen++] = '\n';
  2272. buf[buflen] = '\0';
  2273. GPSD_LOG(LOG_CLIENT, &context.errout,
  2274. "<= client(%d): %s\n", sub_index(sub), buf);
  2275. /*
  2276. * When a command comes in, update subscriber.active to
  2277. * timestamp() so we don't close the connection
  2278. * after COMMAND_TIMEOUT seconds. This makes
  2279. * COMMAND_TIMEOUT useful.
  2280. */
  2281. sub->active = time(NULL);
  2282. if (handle_gpsd_request(sub, buf) < 0)
  2283. detach_client(sub);
  2284. }
  2285. } else {
  2286. unlock_subscriber(sub);
  2287. if (!sub->policy.watcher
  2288. && time(NULL) - sub->active > COMMAND_TIMEOUT) {
  2289. GPSD_LOG(LOG_WARN, &context.errout,
  2290. "client(%d) timed out on command wait.\n",
  2291. sub_index(sub));
  2292. detach_client(sub);
  2293. }
  2294. }
  2295. }
  2296. /*
  2297. * Mark devices with an identified packet type but no
  2298. * remaining subscribers to be closed in RELEASE_TIME seconds.
  2299. * See the explanation of RELEASE_TIME for the reasoning.
  2300. *
  2301. * Re-poll devices that are disconnected, but have potential
  2302. * subscribers in the same cycle.
  2303. */
  2304. for (device = devices; device < devices + MAX_DEVICES; device++) {
  2305. bool device_needed = nowait;
  2306. if (!allocated_device(device))
  2307. continue;
  2308. if (!device_needed)
  2309. for (sub=subscribers; sub<subscribers+MAX_CLIENTS; sub++) {
  2310. if (sub->active == 0)
  2311. continue;
  2312. device_needed = subscribed(sub, device);
  2313. if (device_needed)
  2314. break;
  2315. }
  2316. if (!device_needed && device->gpsdata.gps_fd > -1 &&
  2317. device->lexer.type != BAD_PACKET) {
  2318. if (device->releasetime == 0) {
  2319. device->releasetime = time(NULL);
  2320. GPSD_LOG(LOG_PROG, &context.errout,
  2321. "device %d (fd %d) released\n",
  2322. (int)(device - devices),
  2323. device->gpsdata.gps_fd);
  2324. } else if (time(NULL) - device->releasetime > RELEASE_TIMEOUT) {
  2325. GPSD_LOG(LOG_PROG, &context.errout,
  2326. "device %d closed\n",
  2327. (int)(device - devices));
  2328. GPSD_LOG(LOG_RAW, &context.errout,
  2329. "unflagging descriptor %d\n",
  2330. device->gpsdata.gps_fd);
  2331. deactivate_device(device);
  2332. }
  2333. }
  2334. if (device_needed && BAD_SOCKET(device->gpsdata.gps_fd) &&
  2335. (device->opentime == 0 ||
  2336. time(NULL) - device->opentime > DEVICE_RECONNECT)) {
  2337. device->opentime = time(NULL);
  2338. GPSD_LOG(LOG_INF, &context.errout,
  2339. "reconnection attempt on device %d\n",
  2340. (int)(device - devices));
  2341. (void)awaken(device);
  2342. }
  2343. }
  2344. #endif /* SOCKET_EXPORT_ENABLE */
  2345. /*
  2346. * Might be time for graceful shutdown if no command-line
  2347. * devices were specified, there are no subscribers, there are
  2348. * no active devices, and there *have been* active
  2349. * devices. The goal is to go away and free up text space when
  2350. * the daemon was hotplug-activated but there are no
  2351. * subscribers and the last GPS has unplugged, and the point
  2352. * of the last check is to prevent shutdown when the daemon
  2353. * has been launched but not yet received its first device
  2354. * over the socket.
  2355. */
  2356. if (argc == optind && highwater > 0) {
  2357. int subcount = 0, devcount = 0;
  2358. #ifdef SOCKET_EXPORT_ENABLE
  2359. for (sub = subscribers; sub < subscribers + MAX_CLIENTS; sub++)
  2360. if (sub->active != 0)
  2361. ++subcount;
  2362. #endif /* SOCKET_EXPORT_ENABLE */
  2363. for (device = devices; device < devices + MAX_DEVICES; device++)
  2364. if (allocated_device(device))
  2365. ++devcount;
  2366. if (subcount == 0 && devcount == 0) {
  2367. GPSD_LOG(LOG_SHOUT, &context.errout,
  2368. "no subscribers or devices, shutting down.\n");
  2369. goto shutdown;
  2370. }
  2371. }
  2372. }
  2373. /* if we make it here, we got a signal... deal with it */
  2374. /* restart on SIGHUP, clean up and exit otherwise */
  2375. if (SIGHUP == (int)signalled)
  2376. longjmp(restartbuf, 1);
  2377. GPSD_LOG(LOG_WARN, &context.errout,
  2378. "received terminating signal %d.\n", (int)signalled);
  2379. shutdown:
  2380. gpsd_terminate(&context);
  2381. GPSD_LOG(LOG_WARN, &context.errout, "exiting.\n");
  2382. #ifdef SOCKET_EXPORT_ENABLE
  2383. /*
  2384. * A linger option was set on each client socket when it was
  2385. * created. Now, shut them down gracefully, letting I/O drain.
  2386. * This is an attempt to avoid the sporadic race errors at the ends
  2387. * of our regression tests.
  2388. */
  2389. for (sub = subscribers; sub < subscribers + MAX_CLIENTS; sub++) {
  2390. if (sub->active != 0)
  2391. detach_client(sub);
  2392. }
  2393. #endif /* SOCKET_EXPORT_ENABLE */
  2394. #ifdef SHM_EXPORT_ENABLE
  2395. shm_release(&context);
  2396. #endif /* SHM_EXPORT_ENABLE */
  2397. #ifdef CONTROL_SOCKET_ENABLE
  2398. if (control_socket)
  2399. (void)unlink(control_socket);
  2400. #endif /* CONTROL_SOCKET_ENABLE */
  2401. if (pid_file)
  2402. (void)unlink(pid_file);
  2403. return 0;
  2404. }