gpsd.c 78 KB

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