forked from indilib/indi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
indiserver.c
2247 lines (1981 loc) · 66.7 KB
/
indiserver.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* INDI Server for protocol version 1.7.
* Copyright (C) 2007 Elwood C. Downey <[email protected]>
2013 Jasem Mutlaq <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* argv lists names of Driver programs to run or sockets to connect for Devices.
* Drivers are restarted if they exit or connection closes.
* Each local Driver's stdin/out are assumed to provide INDI traffic and are
* connected here via pipes. Local Drivers' stderr are connected to our
* stderr with date stamp and driver name prepended.
* We only support Drivers that advertise support for one Device. The problem
* with multiple Devices in one Driver is without a way to know what they
* _all_ are there is no way to avoid sending all messages to all Drivers.
* Outbound messages are limited to Devices and Properties seen inbound.
* Messages to Devices on sockets always include Device so the chained
* indiserver will only pass back info from that Device.
* All newXXX() received from one Client are echoed to all other Clients who
* have shown an interest in the same Device and property.
*
* 2017-01-29 JM: Added option to drop stream blobs if client blob queue is
* higher than maxstreamsiz bytes
*
* Implementation notes:
*
* We fork each driver and open a server socket listening for INDI clients.
* Then forever we listen for new clients and pass traffic between clients and
* drivers, subject to optimizations based on sniffing messages for matching
* Devices and Properties. Since one message might be destined to more than
* one client or device, they are queued and only removed after the last
* consumer is finished. XMLEle are converted to linear strings before being
* sent to optimize write system calls and avoid blocking to slow clients.
* Clients that get more than maxqsiz bytes behind are shut down.
*/
#define _GNU_SOURCE // needed for siginfo_t and sigaction
#include "config.h"
#include "fq.h"
#include "indiapi.h"
#include "indidevapi.h"
#include "lilxml.h"
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <netdb.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/socket.h>
#define INDIPORT 7624 /* default TCP/IP port to listen */
#define REMOTEDVR (-1234) /* invalid PID to flag remote drivers */
#define MAXSBUF 512
#define MAXRBUF 49152 /* max read buffering here */
#define MAXWSIZ 49152 /* max bytes/write */
#define SHORTMSGSIZ 2048 /* buf size for most messages */
#define DEFMAXQSIZ 128 /* default max q behind, MB */
#define DEFMAXSSIZ 5 /* default max stream behind, MB */
#define DEFMAXRESTART 10 /* default max restarts */
#ifdef OSX_EMBEDED_MODE
#define LOGNAME "/Users/%s/Library/Logs/indiserver.log"
#define FIFONAME "/tmp/indiserverFIFO"
#endif
/* associate a usage count with queuded client or device message */
typedef struct
{
int count; /* number of consumers left */
unsigned long cl; /* content length */
char *cp; /* content: buf or malloced */
char buf[SHORTMSGSIZ]; /* local buf for most messages */
} Msg;
/* device + property name */
typedef struct
{
char dev[MAXINDIDEVICE];
char name[MAXINDINAME];
BLOBHandling blob; /* when to snoop BLOBs */
} Property;
/* record of each snooped property
typedef struct {
Property prop;
BLOBHandling blob;
} Property;
*/
struct
{
const char *name; /* Path to FIFO for dynamic startups & shutdowns of drivers */
int fd;
//FILE *fs;
} fifo;
/* info for each connected client */
typedef struct
{
int active; /* 1 when this record is in use */
Property *props; /* malloced array of props we want */
int nprops; /* n entries in props[] */
int allprops; /* saw getProperties w/o device */
BLOBHandling blob; /* when to send setBLOBs */
int s; /* socket for this client */
LilXML *lp; /* XML parsing context */
FQ *msgq; /* Msg queue */
unsigned int nsent; /* bytes of current Msg sent so far */
} ClInfo;
static ClInfo *clinfo; /* malloced pool of clients */
static int nclinfo; /* n total (not active) */
/* info for each connected driver */
typedef struct
{
char name[MAXINDINAME]; /* persistent name */
char envDev[MAXSBUF];
char envConfig[MAXSBUF];
char envSkel[MAXSBUF];
char envPrefix[MAXSBUF];
char host[MAXSBUF];
int port;
//char dev[MAXINDIDEVICE]; /* device served by this driver */
char **dev; /* device served by this driver */
int ndev; /* number of devices served by this driver */
int active; /* 1 when this record is in use */
Property *sprops; /* malloced array of props we snoop */
int nsprops; /* n entries in sprops[] */
int pid; /* process id or REMOTEDVR if remote */
int rfd; /* read pipe fd */
int wfd; /* write pipe fd */
int efd; /* stderr from driver, if local */
int restarts; /* times process has been restarted */
LilXML *lp; /* XML parsing context */
FQ *msgq; /* Msg queue */
unsigned int nsent; /* bytes of current Msg sent so far */
} DvrInfo;
static DvrInfo *dvrinfo; /* malloced array of drivers */
static int ndvrinfo; /* n total */
static char *me; /* our name */
static int port = INDIPORT; /* public INDI port */
static int verbose; /* chattiness */
static int lsocket; /* listen socket */
static char *ldir; /* where to log driver messages */
static int maxqsiz = (DEFMAXQSIZ * 1024 * 1024); /* kill if these bytes behind */
static int maxstreamsiz = (DEFMAXSSIZ * 1024 * 1024); /* drop blobs if these bytes behind while streaming*/
static int maxrestarts = DEFMAXRESTART;
static int terminateddrv = 0;
static void logStartup(int ac, char *av[]);
static void usage(void);
//static void noZombies(void);
static void reapZombies(void);
static void noSIGPIPE(void);
static void indiFIFO(void);
static void indiRun(void);
static void indiListen(void);
static void newFIFO(void);
static void newClient(void);
static int newClSocket(void);
static void shutdownClient(ClInfo *cp);
static int readFromClient(ClInfo *cp);
static void startDvr(DvrInfo *dp);
static void startLocalDvr(DvrInfo *dp);
static void startRemoteDvr(DvrInfo *dp);
static int openINDIServer(char host[], int indi_port);
static void shutdownDvr(DvrInfo *dp, int restart);
static int isDeviceInDriver(const char *dev, DvrInfo *dp);
static void q2RDrivers(const char *dev, Msg *mp, XMLEle *root);
static void q2SDrivers(DvrInfo *me, int isblob, const char *dev, const char *name, Msg *mp, XMLEle *root);
static int q2Clients(ClInfo *notme, int isblob, const char *dev, const char *name, Msg *mp, XMLEle *root);
static int q2Servers(DvrInfo *me, Msg *mp, XMLEle *root);
static void addSDevice(DvrInfo *dp, const char *dev, const char *name);
static Property *findSDevice(DvrInfo *dp, const char *dev, const char *name);
static void addClDevice(ClInfo *cp, const char *dev, const char *name, int isblob);
static int findClDevice(ClInfo *cp, const char *dev, const char *name);
static int readFromDriver(DvrInfo *dp);
static int stderrFromDriver(DvrInfo *dp);
static int msgQSize(FQ *q);
static void setMsgXMLEle(Msg *mp, XMLEle *root);
static void setMsgStr(Msg *mp, char *str);
static void freeMsg(Msg *mp);
static Msg *newMsg(void);
static int sendClientMsg(ClInfo *cp);
static int sendDriverMsg(DvrInfo *cp);
static void crackBLOB(const char *enableBLOB, BLOBHandling *bp);
static void crackBLOBHandling(const char *dev, const char *name, const char *enableBLOB, ClInfo *cp);
static void traceMsg(XMLEle *root);
static char *indi_tstamp(char *s);
static void logDMsg(XMLEle *root, const char *dev);
static void Bye(void);
int main(int ac, char *av[])
{
/* log startup */
logStartup(ac, av);
/* save our name */
me = av[0];
#ifdef OSX_EMBEDED_MODE
char logname[128];
snprintf(logname, 128, LOGNAME, getlogin());
fprintf(stderr, "switching stderr to %s", logname);
freopen(logname, "w", stderr);
fifo.name = FIFONAME;
verbose = 1;
ac = 0;
#else
/* crack args */
while ((--ac > 0) && ((*++av)[0] == '-'))
{
char *s;
for (s = av[0] + 1; *s != '\0'; s++)
switch (*s)
{
case 'l':
if (ac < 2)
{
fprintf(stderr, "-l requires log directory\n");
usage();
}
ldir = *++av;
ac--;
break;
case 'm':
if (ac < 2)
{
fprintf(stderr, "-m requires max MB behind\n");
usage();
}
maxqsiz = 1024 * 1024 * atoi(*++av);
ac--;
break;
case 'p':
if (ac < 2)
{
fprintf(stderr, "-p requires port value\n");
usage();
}
port = atoi(*++av);
ac--;
break;
case 'd':
if (ac < 2)
{
fprintf(stderr, "-d requires max stream MB behind\n");
usage();
}
maxstreamsiz = 1024 * 1024 * atoi(*++av);
ac--;
break;
case 'f':
if (ac < 2)
{
fprintf(stderr, "-f requires fifo node\n");
usage();
}
fifo.name = *++av;
ac--;
break;
case 'r':
if (ac < 2)
{
fprintf(stderr, "-r requires number of restarts\n");
usage();
}
maxrestarts = atoi(*++av);
if (maxrestarts < 0)
maxrestarts = 0;
ac--;
break;
case 'v':
verbose++;
break;
default:
usage();
}
}
#endif
/* at this point there are ac args in av[] to name our drivers */
if (ac == 0 && !fifo.name)
usage();
/* take care of some unixisms */
/*noZombies();*/
reapZombies();
noSIGPIPE();
/* realloc seed for client pool */
clinfo = (ClInfo *)malloc(1);
nclinfo = 0;
/* create driver info array all at once since size never changes */
ndvrinfo = ac;
dvrinfo = (DvrInfo *)calloc(ndvrinfo, sizeof(DvrInfo));
/* start each driver */
while (ac-- > 0)
{
strncpy(dvrinfo[ac].name, *av++, MAXINDINAME);
startDvr(&dvrinfo[ac]);
}
/* announce we are online */
indiListen();
/* Load up FIFO, if available */
indiFIFO();
/* handle new clients and all io */
while (1)
indiRun();
/* whoa! */
fprintf(stderr, "unexpected return from main\n");
return (1);
}
/* record we have started and our args */
static void logStartup(int ac, char *av[])
{
int i;
fprintf(stderr, "%s: startup: ", indi_tstamp(NULL));
for (i = 0; i < ac; i++)
fprintf(stderr, "%s ", av[i]);
fprintf(stderr, "\n");
}
/* print usage message and exit (2) */
static void usage(void)
{
fprintf(stderr, "Usage: %s [options] driver [driver ...]\n", me);
fprintf(stderr, "Purpose: server for local and remote INDI drivers\n");
fprintf(stderr, "INDI Library: %s\nCode %s. Protocol %g.\n", CMAKE_INDI_VERSION_STRING, GIT_TAG_STRING, INDIV);
fprintf(stderr, "Options:\n");
fprintf(stderr, " -l d : log driver messages to <d>/YYYY-MM-DD.islog\n");
fprintf(stderr, " -m m : kill client if gets more than this many MB behind, default %d\n", DEFMAXQSIZ);
fprintf(stderr,
" -d m : drop streaming blobs if client gets more than this many MB behind, default %d. 0 to disable\n",
DEFMAXSSIZ);
fprintf(stderr, " -p p : alternate IP port, default %d\n", INDIPORT);
fprintf(stderr, " -r r : maximum driver restarts on error, default %d\n", DEFMAXRESTART);
fprintf(stderr, " -f path : Path to fifo for dynamic startup and shutdown of drivers.\n");
fprintf(stderr, " -v : show key events, no traffic\n");
fprintf(stderr, " -vv : -v + key message content\n");
fprintf(stderr, " -vvv : -vv + complete xml\n");
fprintf(stderr, "driver : executable or [device]@host[:port]\n");
exit(2);
}
/* arrange for no zombies if drivers die */
//static void noZombies()
//{
// struct sigaction sa;
// sa.sa_handler = SIG_IGN;
// sigemptyset(&sa.sa_mask);
//#ifdef SA_NOCLDWAIT
// sa.sa_flags = SA_NOCLDWAIT;
//#else
// sa.sa_flags = 0;
//#endif
// (void)sigaction(SIGCHLD, &sa, NULL);
//}
/* reap zombies when drivers die, in order to leave SIGCHLD unmodified for subprocesses */
static void zombieRaised(int signum, siginfo_t *sig, void *data)
{
INDI_UNUSED(data);
switch (signum)
{
case SIGCHLD:
fprintf(stderr, "Child process %d died\n", sig->si_pid);
waitpid(sig->si_pid, NULL, WNOHANG);
break;
default:
fprintf(stderr, "Received unexpected signal %d\n", signum);
}
}
/* reap zombies as they die */
static void reapZombies()
{
struct sigaction sa;
sa.sa_sigaction = zombieRaised;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_SIGINFO;
(void)sigaction(SIGCHLD, &sa, NULL);
}
/* turn off SIGPIPE on bad write so we can handle it inline */
static void noSIGPIPE()
{
struct sigaction sa;
sa.sa_handler = SIG_IGN;
sigemptyset(&sa.sa_mask);
(void)sigaction(SIGPIPE, &sa, NULL);
}
static DvrInfo *allocDvr()
{
DvrInfo *dp = NULL;
int dvi;
/* try to reuse a driver slot, else add one */
for (dvi = 0; dvi < ndvrinfo; dvi++)
if (!(dp = &dvrinfo[dvi])->active)
break;
if (dvi == ndvrinfo)
{
/* grow dvrinfo */
dvrinfo = (DvrInfo *)realloc(dvrinfo, (ndvrinfo + 1) * sizeof(DvrInfo));
if (!dvrinfo)
{
fprintf(stderr, "no memory for new drivers\n");
Bye();
}
dp = &dvrinfo[ndvrinfo++];
}
if (dp == NULL)
return NULL;
/* rig up new dvrinfo entry */
memset(dp, 0, sizeof(*dp));
dp->active = 1;
dp->ndev = 0;
return dp;
}
/* start the given INDI driver process or connection.
* exit if trouble.
*/
static void startDvr(DvrInfo *dp)
{
if (strchr(dp->name, '@'))
startRemoteDvr(dp);
else
startLocalDvr(dp);
}
/* start the given local INDI driver process.
* exit if trouble.
*/
static void startLocalDvr(DvrInfo *dp)
{
Msg *mp;
char buf[32];
int rp[2], wp[2], ep[2];
int pid;
#ifdef OSX_EMBEDED_MODE
fprintf(stderr, "STARTING \"%s\"\n", dp->name);
fflush(stderr);
#endif
/* build three pipes: r, w and error*/
if (pipe(rp) < 0)
{
fprintf(stderr, "%s: read pipe: %s\n", indi_tstamp(NULL), strerror(errno));
Bye();
}
if (pipe(wp) < 0)
{
fprintf(stderr, "%s: write pipe: %s\n", indi_tstamp(NULL), strerror(errno));
Bye();
}
if (pipe(ep) < 0)
{
fprintf(stderr, "%s: stderr pipe: %s\n", indi_tstamp(NULL), strerror(errno));
Bye();
}
/* fork&exec new process */
pid = fork();
if (pid < 0)
{
fprintf(stderr, "%s: fork: %s\n", indi_tstamp(NULL), strerror(errno));
Bye();
}
if (pid == 0)
{
/* child: exec name */
int fd;
/* rig up pipes */
dup2(wp[0], 0); /* driver stdin reads from wp[0] */
dup2(rp[1], 1); /* driver stdout writes to rp[1] */
dup2(ep[1], 2); /* driver stderr writes to e[]1] */
for (fd = 3; fd < 100; fd++)
(void)close(fd);
if (*dp->envDev)
setenv("INDIDEV", dp->envDev, 1);
/* Only reset environment variable in case of FIFO */
else if (fifo.fd > 0)
unsetenv("INDIDEV");
if (*dp->envConfig)
setenv("INDICONFIG", dp->envConfig, 1);
else if (fifo.fd > 0)
unsetenv("INDICONFIG");
if (*dp->envSkel)
setenv("INDISKEL", dp->envSkel, 1);
else if (fifo.fd > 0)
unsetenv("INDISKEL");
char executable[MAXSBUF];
if (*dp->envPrefix)
{
setenv("INDIPREFIX", dp->envPrefix, 1);
#if defined(OSX_EMBEDED_MODE)
snprintf(executable, MAXSBUF, "%s/Contents/MacOS/%s", dp->envPrefix, dp->name);
#elif defined(__APPLE__)
snprintf(executable, MAXSBUF, "%s/%s", dp->envPrefix, dp->name);
#else
snprintf(executable, MAXSBUF, "%s/bin/%s", dp->envPrefix, dp->name);
#endif
fprintf(stderr, "%s\n", executable);
execlp(executable, dp->name, NULL);
}
else
{
if (fifo.fd > 0)
unsetenv("INDIPREFIX");
if (dp->name[0] == '.')
{
snprintf(executable, MAXSBUF, "%s/%s", dirname(me), dp->name);
execlp(executable, dp->name, NULL);
}
else
{
execlp(dp->name, dp->name, NULL);
}
}
#ifdef OSX_EMBEDED_MODE
fprintf(stderr, "FAILED \"%s\"\n", dp->name);
fflush(stderr);
#endif
fprintf(stderr, "%s: Driver %s: execlp: %s\n", indi_tstamp(NULL), dp->name, strerror(errno));
_exit(1); /* parent will notice EOF shortly */
}
/* don't need child's side of pipes */
close(wp[0]);
close(rp[1]);
close(ep[1]);
/* record pid, io channels, init lp and snoop list */
dp->pid = pid;
strncpy(dp->host, "localhost", MAXSBUF);
dp->port = -1;
dp->rfd = rp[0];
dp->wfd = wp[1];
dp->efd = ep[0];
dp->lp = newLilXML();
dp->msgq = newFQ(1);
dp->sprops = (Property *)malloc(1); /* seed for realloc */
dp->nsprops = 0;
dp->nsent = 0;
dp->active = 1;
dp->ndev = 0;
dp->dev = (char **)malloc(sizeof(char *));
/* first message primes driver to report its properties -- dev known
* if restarting
*/
mp = newMsg();
pushFQ(dp->msgq, mp);
snprintf(buf, sizeof(buf), "<getProperties version='%g'/>\n", INDIV);
setMsgStr(mp, buf);
mp->count++;
if (verbose > 0)
fprintf(stderr, "%s: Driver %s: pid=%d rfd=%d wfd=%d efd=%d\n", indi_tstamp(NULL), dp->name, dp->pid, dp->rfd,
dp->wfd, dp->efd);
}
/* start the given remote INDI driver connection.
* exit if trouble.
*/
static void startRemoteDvr(DvrInfo *dp)
{
Msg *mp;
char dev[MAXINDIDEVICE] = {0};
char host[MAXSBUF] = {0};
char buf[MAXSBUF] = {0};
int indi_port, sockfd;
/* extract host and port */
indi_port = INDIPORT;
if (sscanf(dp->name, "%[^@]@%[^:]:%d", dev, host, &indi_port) < 2)
{
// Device missing? Try a different syntax for all devices
if (sscanf(dp->name, "@%[^:]:%d", host, &indi_port) < 1)
{
fprintf(stderr, "Bad remote device syntax: %s\n", dp->name);
Bye();
}
}
/* connect */
sockfd = openINDIServer(host, indi_port);
/* record flag pid, io channels, init lp and snoop list */
dp->pid = REMOTEDVR;
strncpy(dp->host, host, MAXSBUF);
dp->port = indi_port;
dp->rfd = sockfd;
dp->wfd = sockfd;
dp->lp = newLilXML();
dp->msgq = newFQ(1);
dp->sprops = (Property *)malloc(1); /* seed for realloc */
dp->nsprops = 0;
dp->nsent = 0;
dp->active = 1;
dp->ndev = 1;
dp->dev = (char **)malloc(sizeof(char *));
/* N.B. storing name now is key to limiting outbound traffic to this
* dev.
*/
dp->dev[0] = (char *)malloc(MAXINDIDEVICE * sizeof(char));
strncpy(dp->dev[0], dev, MAXINDIDEVICE - 1);
dp->dev[0][MAXINDIDEVICE - 1] = '\0';
/* Sending getProperties with device lets remote server limit its
* outbound (and our inbound) traffic on this socket to this device.
*/
mp = newMsg();
pushFQ(dp->msgq, mp);
if (dev[0])
sprintf(buf, "<getProperties device='%s' version='%g'/>\n", dp->dev[0], INDIV);
else
// This informs downstream server that it is connecting to an upstream server
// and not a regular client. The difference is in how it treats snooping properties
// among properties.
sprintf(buf, "<getProperties device='*' version='%g'/>\n", INDIV);
setMsgStr(mp, buf);
mp->count++;
if (verbose > 0)
fprintf(stderr, "%s: Driver %s: socket=%d\n", indi_tstamp(NULL), dp->name, sockfd);
}
/* open a connection to the given host and port or die.
* return socket fd.
*/
static int openINDIServer(char host[], int indi_port)
{
struct sockaddr_in serv_addr;
struct hostent *hp;
int sockfd;
/* lookup host address */
hp = gethostbyname(host);
if (!hp)
{
fprintf(stderr, "gethostbyname(%s): %s\n", host, strerror(errno));
Bye();
}
/* create a socket to the INDI server */
(void)memset((char *)&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = ((struct in_addr *)(hp->h_addr_list[0]))->s_addr;
serv_addr.sin_port = htons(indi_port);
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
fprintf(stderr, "socket(%s,%d): %s\n", host, indi_port, strerror(errno));
Bye();
}
/* connect */
if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
fprintf(stderr, "connect(%s,%d): %s\n", host, indi_port, strerror(errno));
Bye();
}
/* ok */
return (sockfd);
}
/* create the public INDI Driver endpoint lsocket on port.
* return server socket else exit.
*/
static void indiListen()
{
struct sockaddr_in serv_socket;
int sfd;
int reuse = 1;
/* make socket endpoint */
if ((sfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
fprintf(stderr, "%s: socket: %s\n", indi_tstamp(NULL), strerror(errno));
Bye();
}
/* bind to given port for any IP address */
memset(&serv_socket, 0, sizeof(serv_socket));
serv_socket.sin_family = AF_INET;
#ifdef SSH_TUNNEL
serv_socket.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
#else
serv_socket.sin_addr.s_addr = htonl(INADDR_ANY);
#endif
serv_socket.sin_port = htons((unsigned short)port);
if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0)
{
fprintf(stderr, "%s: setsockopt: %s\n", indi_tstamp(NULL), strerror(errno));
Bye();
}
if (bind(sfd, (struct sockaddr *)&serv_socket, sizeof(serv_socket)) < 0)
{
fprintf(stderr, "%s: bind: %s\n", indi_tstamp(NULL), strerror(errno));
Bye();
}
/* willing to accept connections with a backlog of 5 pending */
if (listen(sfd, 5) < 0)
{
fprintf(stderr, "%s: listen: %s\n", indi_tstamp(NULL), strerror(errno));
Bye();
}
/* ok */
lsocket = sfd;
if (verbose > 0)
fprintf(stderr, "%s: listening to port %d on fd %d\n", indi_tstamp(NULL), port, sfd);
}
/* Attempt to open up FIFO */
static void indiFIFO(void)
{
close(fifo.fd);
fifo.fd = -1;
/* Open up FIFO, if available */
if (fifo.name)
{
fifo.fd = open(fifo.name, O_RDWR | O_NONBLOCK);
if (fifo.fd < 0)
{
fprintf(stderr, "%s: open(%s): %s.\n", indi_tstamp(NULL), fifo.name, strerror(errno));
Bye();
}
}
}
/* service traffic from clients and drivers */
static void indiRun(void)
{
fd_set rs, ws;
int maxfd = 0;
int i, s;
/* init with no writers or readers */
FD_ZERO(&ws);
FD_ZERO(&rs);
if (fifo.name && fifo.fd >= 0)
{
FD_SET(fifo.fd, &rs);
maxfd = fifo.fd;
}
/* always listen for new clients */
FD_SET(lsocket, &rs);
if (lsocket > maxfd)
maxfd = lsocket;
/* add all client readers and client writers with work to send */
for (i = 0; i < nclinfo; i++)
{
ClInfo *cp = &clinfo[i];
if (cp->active)
{
FD_SET(cp->s, &rs);
if (nFQ(cp->msgq) > 0)
FD_SET(cp->s, &ws);
if (cp->s > maxfd)
maxfd = cp->s;
}
}
/* add all driver readers and driver writers with work to send */
for (i = 0; i < ndvrinfo; i++)
{
DvrInfo *dp = &dvrinfo[i];
if (dp->active)
{
FD_SET(dp->rfd, &rs);
if (dp->rfd > maxfd)
maxfd = dp->rfd;
if (dp->pid != REMOTEDVR)
{
FD_SET(dp->efd, &rs);
if (dp->efd > maxfd)
maxfd = dp->efd;
}
if (nFQ(dp->msgq) > 0)
{
FD_SET(dp->wfd, &ws);
if (dp->wfd > maxfd)
maxfd = dp->wfd;
}
}
}
/* wait for action */
s = select(maxfd + 1, &rs, &ws, NULL, NULL);
if (s < 0)
{
if(errno == EINTR)
return;
fprintf(stderr, "%s: select(%d): %s\n", indi_tstamp(NULL), maxfd + 1, strerror(errno));
Bye();
}
/* new command from FIFO? */
if (s > 0 && fifo.fd >= 0 && FD_ISSET(fifo.fd, &rs))
{
newFIFO();
s--;
}
/* new client? */
if (s > 0 && FD_ISSET(lsocket, &rs))
{
newClient();
s--;
}
/* message to/from client? */
for (i = 0; s > 0 && i < nclinfo; i++)
{
ClInfo *cp = &clinfo[i];
if (cp->active)
{
if (FD_ISSET(cp->s, &rs))
{
if (readFromClient(cp) < 0)
return; /* fds effected */
s--;
}
if (s > 0 && FD_ISSET(cp->s, &ws))
{
if (sendClientMsg(cp) < 0)
return; /* fds effected */
s--;
}
}
}
/* message to/from driver? */
for (i = 0; s > 0 && i < ndvrinfo; i++)
{
DvrInfo *dp = &dvrinfo[i];
if (dp->active)
{
if (dp->pid != REMOTEDVR && FD_ISSET(dp->efd, &rs))
{
if (stderrFromDriver(dp) < 0)
return; /* fds effected */
s--;
}
if (s > 0 && FD_ISSET(dp->rfd, &rs))
{
if (readFromDriver(dp) < 0)
return; /* fds effected */
s--;
}
if (s > 0 && FD_ISSET(dp->wfd, &ws) && nFQ(dp->msgq) > 0)
{
if (sendDriverMsg(dp) < 0)
return; /* fds effected */
s--;
}
}
}
}
int isDeviceInDriver(const char *dev, DvrInfo *dp)
{
int i = 0;
for (i = 0; i < dp->ndev; i++)
{
if (!strcmp(dev, dp->dev[i]))
return 1;
}
return 0;
}
/* Read commands from FIFO and process them. Start/stop drivers accordingly */
static void newFIFO(void)
{
//char line[MAXRBUF], tDriver[MAXRBUF], tConfig[MAXRBUF], tDev[MAXRBUF], tSkel[MAXRBUF], envDev[MAXRBUF], envConfig[MAXRBUF], envSkel[MAXR];
char line[MAXRBUF];
DvrInfo *dp = NULL;
int startCmd = 0, i = 0, remoteDriver = 0;
while (i < MAXRBUF)
{
if (read(fifo.fd, line + i, 1) <= 0)
{
// Reset FIFO now, otherwise select will always return with no data from FIFO.
indiFIFO();
return;
}
if (line[i] == '\n')
{
line[i] = '\0';
i = 0;
}
else
{
i++;
continue;
}
if (verbose)
fprintf(stderr, "FIFO: %s\n", line);
char cmd[MAXSBUF], arg[4][1], var[4][MAXSBUF], tDriver[MAXSBUF], tName[MAXSBUF], envConfig[MAXSBUF],
envSkel[MAXSBUF], envPrefix[MAXSBUF];
memset(&tDriver[0], 0, sizeof(char) * MAXSBUF);
memset(&tName[0], 0, sizeof(char) * MAXSBUF);
memset(&envConfig[0], 0, sizeof(char) * MAXSBUF);
memset(&envSkel[0], 0, sizeof(char) * MAXSBUF);
memset(&envPrefix[0], 0, sizeof(char) * MAXSBUF);
int n = 0;
// If remote driver
if (strstr(line, "@"))
{
n = sscanf(line, "%s %512[^\n]", cmd, tDriver);
// Remove quotes if any
char *ptr = tDriver;
int len = strlen(tDriver);
while ((ptr = strstr(tDriver, "\"")))
{
memmove(ptr, ptr + 1, --len);
ptr[len] = '\0';
}
//fprintf(stderr, "Remote Driver: %s\n", tDriver);
remoteDriver = 1;
}
// If local driver
else
{
n = sscanf(line, "%s %s -%1c \"%512[^\"]\" -%1c \"%512[^\"]\" -%1c \"%512[^\"]\" -%1c \"%512[^\"]\"", cmd,
tDriver, arg[0], var[0], arg[1], var[1], arg[2], var[2], arg[3], var[3]);
remoteDriver = 0;
}
int n_args = (n - 2) / 2;