gpsd.c 98 KB

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