forked from indilib/indi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
indiserver.cpp
3647 lines (3026 loc) · 99.6 KB
/
indiserver.cpp
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 <ecdowney@clearskyinstitute.com>
2013 Jasem Mutlaq <mutlaqja@ikarustech.com>
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.
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE // needed for siginfo_t and sigaction
#endif
#include "config.h"
#include <set>
#include <string>
#include <list>
#include <map>
#include <unordered_map>
#include <vector>
#include <thread>
#include <mutex>
#include <assert.h>
#include "indiapi.h"
#include "indidevapi.h"
#include "sharedblob.h"
#include "libs/lilxml.h"
#include "base64.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 <stdint.h>
#include <string.h>
#include <time.h>
#include <poll.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/mman.h>
#include <unistd.h>
#include <sys/un.h>
#ifdef MSG_ERRQUEUE
#include <linux/errqueue.h>
#endif
#include <ev++.h>
#define INDIPORT 7624 /* default TCP/IP port to listen */
#define INDIUNIXSOCK "/tmp/indiserver" /* default unix socket path (local connections) */
#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 */
#define MAXFD_PER_MESSAGE 16 /* No more than 16 buffer attached to a message */
#ifdef OSX_EMBEDED_MODE
#define LOGNAME "/Users/%s/Library/Logs/indiserver.log"
#define FIFONAME "/tmp/indiserverFIFO"
#endif
#define STRINGIFY_TOK(x) #x
#define TO_STRING(x) STRINGIFY_TOK(x)
static ev::default_loop loop;
template<class M>
class ConcurrentSet {
unsigned long identifier = 1;
std::map<unsigned long, M*> items;
public:
void insert(M* item) {
item->id = identifier++;
items[item->id] = item;
item->current = (ConcurrentSet<void>*)this;
}
void erase(M* item) {
items.erase(item->id);
item->id = 0;
item->current = nullptr;
}
std::vector<unsigned long> ids() const {
std::vector<unsigned long> result;
for(auto item : items) {
result.push_back(item.first);
}
return result;
}
M* operator[](unsigned long id) const {
auto e = items.find(id);
if (e == items.end()) {
return nullptr;
}
return e->second;
}
class iterator {
friend class ConcurrentSet<M>;
const ConcurrentSet<M> * parent;
std::vector<unsigned long> ids;
// Will be -1 when done
long int pos = 0;
void skip() {
if (pos == -1) return;
while(pos < (long int)ids.size() && !(*parent)[ids[pos]]) {
pos++;
}
if (pos == (long int)ids.size()) {
pos = -1;
}
}
public:
iterator(const ConcurrentSet<M> * parent) : parent(parent) {}
bool operator!=(const iterator & o) { return pos != o.pos; }
iterator & operator++() {
if (pos != -1)
{
pos++;
skip();
}
return *this;
}
M * operator*() const {
return (*parent)[ids[pos]];
}
};
iterator begin() const {
iterator result(this);
for(auto item : items) {
result.ids.push_back(item.first);
}
result.skip();
return result;
}
iterator end() const {
iterator result(nullptr);
result.pos = -1;
return result;
}
};
/* An object that can be put in a ConcurrentSet, and provide a heartbeat
* to detect removal from ConcurrentSet
*/
class Collectable {
template<class P> friend class ConcurrentSet;
unsigned long id = 0;
const ConcurrentSet<void> * current;
/* Keep the id */
class HeartBeat {
friend class Collectable;
unsigned long id;
const ConcurrentSet<void> * current;
HeartBeat(unsigned long id, const ConcurrentSet<void> * current)
:id(id), current(current) {}
public:
bool alive() const {
return id != 0 && (*current)[id] != nullptr;
}
};
protected:
/* heartbeat.alive will return true as long as this item has not changed collection.
* Also detect deletion of the Collectable */
HeartBeat heartBeat() const {
return HeartBeat(id, current);
}
};
/**
* A MsgChunk is either:
* a raw xml fragment
* a ref to a shared buffer in the message
*/
class MsgChunck {
friend class SerializedMsg;
friend class SerializedMsgWithSharedBuffer;
friend class SerializedMsgWithoutSharedBuffer;
friend class MsgChunckIterator;
MsgChunck();
MsgChunck(char * content, unsigned long length);
char * content;
unsigned long contentLength;
std::vector<int> sharedBufferIdsToAttach;
};
class Msg;
class MsgQueue;
class MsgChunckIterator;
class SerializationRequirement {
friend class Msg;
friend class SerializedMsg;
// If the xml is still required
bool xml;
// Set of sharedBuffer that are still required
std::set<int> sharedBuffers;
SerializationRequirement() : sharedBuffers() {
xml = false;
}
void add(const SerializationRequirement & from) {
xml |= from.xml;
for(auto fd : from.sharedBuffers) {
sharedBuffers.insert(fd);
}
}
bool operator==(const SerializationRequirement & sr) const {
return (xml == sr.xml) && (sharedBuffers == sr.sharedBuffers);
}
};
enum SerializationStatus { PENDING, RUNNING, CANCELING, TERMINATED };
class SerializedMsg {
friend class Msg;
friend class MsgChunckIterator;
std::recursive_mutex lock;
ev::async asyncProgress;
// Start a thread for execution of asyncRun
void async_start();
void async_cancel();
// Called within main loop when async task did some progress
void async_progressed();
// The requirements. Prior to starting, everything is required.
SerializationRequirement requirements;
void produce(bool sync);
protected:
// These methods are to be called from asyncRun
bool async_canceled();
void async_updateRequirement(const SerializationRequirement & n);
void async_pushChunck(const MsgChunck & m);
void async_done();
// True if a producing thread is active
bool isAsyncRunning();
protected:
SerializationStatus asyncStatus;
Msg * owner;
MsgQueue* blockedProducer;
std::set<MsgQueue *> awaiters;
private:
std::vector<MsgChunck> chuncks;
protected:
// Buffers malloced during asyncRun
std::list<void*> ownBuffers;
// This will notify awaiters and possibly release the owner
void onDataReady();
virtual bool generateContentAsync() const = 0;
virtual void generateContent() = 0;
void collectRequirements(SerializationRequirement & req);
// The task will cancel itself if all owner release it
void abort();
// Make sure the given receiver will not be processed until this task complete
// TODO : to implement + make sure the task start when it actually block something
void blockReceiver(MsgQueue * toblock);
public:
SerializedMsg(Msg * parent);
virtual ~SerializedMsg();
// Calling requestContent will start production
// Return true if some content is available
bool requestContent(const MsgChunckIterator & position);
// Return true if some content is available
// It is possible to have 0 to send, meaning end was actually reached
bool getContent(MsgChunckIterator & position, void * & data, ssize_t & nsend, std::vector<int> & sharedBuffers);
void advance(MsgChunckIterator & position, ssize_t s);
// When a queue is done with sending this message
void release(MsgQueue * from);
void addAwaiter(MsgQueue * awaiter);
ssize_t queueSize();
};
class SerializedMsgWithSharedBuffer: public SerializedMsg{
std::set<int> ownSharedBuffers;
protected:
bool detectInlineBlobs();
public:
SerializedMsgWithSharedBuffer(Msg * parent);
virtual ~SerializedMsgWithSharedBuffer();
virtual bool generateContentAsync() const;
virtual void generateContent();
};
class SerializedMsgWithoutSharedBuffer: public SerializedMsg {
public:
SerializedMsgWithoutSharedBuffer(Msg * parent);
virtual ~SerializedMsgWithoutSharedBuffer();
virtual bool generateContentAsync() const;
virtual void generateContent();
};
class MsgChunckIterator {
friend class SerializedMsg;
std::size_t chunckId;
unsigned long chunckOffset;
bool endReached;
public:
MsgChunckIterator() {
reset();
}
// Point to start of message.
void reset() {
chunckId = 0;
chunckOffset = 0;
// No risk of 0 length message, so always false here
endReached = false;
}
bool done() const {
return endReached;
}
};
class Msg {
friend class SerializedMsg;
friend class SerializedMsgWithSharedBuffer;
friend class SerializedMsgWithoutSharedBuffer;
private:
// Present for sure until message queing is doned. Prune asap then
XMLEle * xmlContent;
// Present until message was queued.
MsgQueue * from;
int queueSize;
bool hasInlineBlobs;
bool hasSharedBufferBlobs;
std::vector<int> sharedBuffers; /* fds of shared buffer */
// Convertion task and resultat of the task
SerializedMsg* convertionToSharedBuffer;
SerializedMsg* convertionToInline;
SerializedMsg * buildConvertionToSharedBuffer();
SerializedMsg * buildConvertionToInline();
bool fetchBlobs(std::list<int> & incomingSharedBuffers);
void releaseXmlContent();
void releaseSharedBuffers(const std::set<int> & keep);
// Remove resources that can be removed.
// Will be called when queuingDone is true and for every change of staus from convertionToXXX
void prune();
void releaseSerialization(SerializedMsg * form);
~Msg();
public:
/* Message will not be queued anymore. Release all possible resources, incl self */
void queuingDone();
Msg(MsgQueue * from, XMLEle * root);
static Msg * fromXml(MsgQueue * from, XMLEle * root, std::list<int> & incomingSharedBuffers);
/**
* Handle multiple cases:
*
* - inline => attached.
* Exceptional. The inline is already in memory within xml. It must be converted to shared buffer async.
* FIXME: The convertion should block the emitter.
*
* - attached => attached
* Default case. No convertion is required.
*
* - inline => inline
* Frequent on system not supporting attachment.
*
* - attached => inline
* Frequent. The convertion will be made during write. The convert/write must be offshored to a dedicated thread.
*
* The returned AsyncTask will be ready once "to" can write the message
*/
SerializedMsg * serialize(MsgQueue * from);
};
class MsgQueue: public Collectable {
int rFd, wFd;
LilXML * lp; /* XML parsing context */
ev::io rio, wio; /* Event loop io events */
void ioCb(ev::io &watcher, int revents);
// Update the status of FD read/write ability
void updateIos();
std::set<SerializedMsg*> readBlocker; /* The message that block this queue */
std::list<SerializedMsg*> msgq; /* To send msg queue */
std::list<int> incomingSharedBuffers; /* During reception, fds accumulate here */
// Position in the head message
MsgChunckIterator nsent;
// Handle fifo or socket case
size_t doRead(char * buff, size_t len);
void readFromFd();
/* write the next chunk of the current message in the queue to the given
* client. pop message from queue when complete and free the message if we are
* the last one to use it. shut down this client if trouble.
*/
void writeToFd();
protected:
bool useSharedBuffer;
int getRFd() const { return rFd; }
int getWFd() const { return wFd; }
/* print key attributes and values of the given xml to stderr. */
void traceMsg(const std::string & log, XMLEle *root);
/* Close the connection. (May be restarted later depending on driver logic) */
virtual void close() = 0;
/* Handle a message. root will be freed by caller. fds of buffers will be closed, unless set to -1 */
virtual void onMessage(XMLEle *root, std::list<int> & sharedBuffers) = 0;
/* convert the string value of enableBLOB to our B_ state value.
* no change if unrecognized
*/
static void crackBLOB(const char *enableBLOB, BLOBHandling *bp);
MsgQueue(bool useSharedBuffer);
public:
virtual ~MsgQueue();
void pushMsg(Msg * msg);
/* return storage size of all Msqs on the given q */
unsigned long msgQSize() const;
SerializedMsg * headMsg() const;
void consumeHeadMsg();
/* Remove all messages from queue */
void clearMsgQueue();
void messageMayHaveProgressed(const SerializedMsg * msg);
void setFds(int rFd, int wFd);
bool acceptSharedBuffers() const { return useSharedBuffer; }
virtual void log(const std::string & log) const;
};
/* device + property name */
class Property {
public:
std::string dev;
std::string name;
BLOBHandling blob = B_NEVER; /* when to snoop BLOBs */
Property(const std::string & dev, const std::string & name): dev(dev), name(name) {}
};
class Fifo {
std::string name; /* Path to FIFO for dynamic startups & shutdowns of drivers */
char buffer[1024];
int bufferPos = 0;
int fd = -1;
ev::io fdev;
void close();
void open();
void processLine(const char * line);
/* Read commands from FIFO and process them. Start/stop drivers accordingly */
void read();
void ioCb(ev::io &watcher, int revents);
public:
Fifo(const std::string & name);
void listen() { open(); }
};
static Fifo * fifo = nullptr;
class DvrInfo;
/* info for each connected client */
class ClInfo: public MsgQueue {
protected:
/* send message to each appropriate driver.
* also send all newXXX() to all other interested clients.
*/
virtual void onMessage(XMLEle *root, std::list<int> & sharedBuffers);
/* Update the client property BLOB handling policy */
void crackBLOBHandling(const std::string & dev, const std::string & name, const char *enableBLOB);
/* close down the given client */
virtual void close();
public:
std::list<Property*> props; /* props we want */
int allprops = 0; /* saw getProperties w/o device */
BLOBHandling blob = B_NEVER; /* when to send setBLOBs */
ClInfo(bool useSharedBuffer);
virtual ~ClInfo();
/* return 0 if cp may be interested in dev/name else -1
*/
int findDevice(const std::string & dev, const std::string & name) const;
/* add the given device and property to the props[] list of client if new.
*/
void addDevice(const std::string & dev, const std::string & name, int isblob);
virtual void log(const std::string & log) const;
/* put Msg mp on queue of each chained server client, except notme.
*/
static void q2Servers(DvrInfo *me, Msg *mp, XMLEle *root);
/* put Msg mp on queue of each client interested in dev/name, except notme.
* if BLOB always honor current mode.
*/
static void q2Clients(ClInfo *notme, int isblob, const std::string & dev, const std::string & name, Msg *mp, XMLEle *root);
/* Reference to all active clients */
static ConcurrentSet<ClInfo> clients;
};
/* info for each connected driver */
class DvrInfo: public MsgQueue
{
/* add dev/name to this device's snooping list.
* init with blob mode set to B_NEVER.
*/
void addSDevice(const std::string & dev, const std::string & name);
public:
/* return Property if dp is this driver is snooping dev/name, else NULL.
*/
Property *findSDevice(const std::string & dev, const std::string & name) const;
protected:
/* send message to each interested client
*/
virtual void onMessage(XMLEle *root, std::list<int> & sharedBuffers);
/* Construct an instance that will start the same driver */
DvrInfo(const DvrInfo & model);
public:
std::string name; /* persistent name */
std::set<std::string> dev; /* device served by this driver */
std::list<Property*>sprops; /* props we snoop */
int restarts; /* times process has been restarted */
bool restart = true; /* Restart on shutdown */
DvrInfo(bool useSharedBuffer);
virtual ~DvrInfo();
bool isHandlingDevice(const std::string & dev) const;
/* start the INDI driver process or connection.
* exit if trouble.
*/
virtual void start() = 0;
/* close down the given driver and restart if set*/
virtual void close();
/* Allocate an instance that will start the same driver */
virtual DvrInfo * clone() const = 0;
virtual void log(const std::string & log) const;
virtual const std::string remoteServerUid() const = 0;
/* put Msg mp on queue of each driver responsible for dev, or all drivers
* if dev empty.
*/
static void q2RDrivers(const std::string & dev, Msg *mp, XMLEle *root);
/* put Msg mp on queue of each driver snooping dev/name.
* if BLOB always honor current mode.
*/
static void q2SDrivers(DvrInfo *me, int isblob, const std::string & dev, const std::string & name, Msg *mp, XMLEle *root);
/* Reference to all active drivers */
static ConcurrentSet<DvrInfo> drivers;
};
class LocalDvrInfo: public DvrInfo {
char errbuff[1024]; /* buffer for stderr pipe. line too long will be clipped */
int errbuffpos = 0; /* first free pos in buffer */
ev::io eio; /* Event loop io events */
ev::child pidwatcher;
void onEfdEvent(ev::io &watcher, int revents); /* callback for data on efd */
void onPidEvent(ev::child & watcher, int revents);
int pid = 0; /* process id or 0 for N/A (not started/terminated) */
int efd = -1; /* stderr from driver, or -1 when N/A */
void closeEfd();
void closePid();
protected:
LocalDvrInfo(const LocalDvrInfo & model);
public:
std::string envDev;
std::string envConfig;
std::string envSkel;
std::string envPrefix;
LocalDvrInfo();
virtual ~LocalDvrInfo();
virtual void start();
virtual LocalDvrInfo * clone() const;
virtual const std::string remoteServerUid() const { return ""; }
};
class RemoteDvrInfo: public DvrInfo {
/* open a connection to the given host and port or die.
* return socket fd.
*/
int openINDIServer();
void extractRemoteId(const std::string & name, std::string & o_host, int & o_port, std::string & o_dev) const;
protected:
RemoteDvrInfo(const RemoteDvrInfo & model);
public:
std::string host;
int port;
RemoteDvrInfo();
virtual ~RemoteDvrInfo();
virtual void start();
virtual RemoteDvrInfo * clone() const;
virtual const std::string remoteServerUid() const
{
return std::string(host) + ":" + std::to_string(port);
}
};
class TcpServer {
int port;
int sfd = -1;
ev::io sfdev;
/* prepare for new client arriving on socket.
* exit if trouble.
*/
void accept();
void ioCb(ev::io &watcher, int revents);
public:
TcpServer(int port);
/* create the public INDI Driver endpoint lsocket on port.
* return server socket else exit.
*/
void listen();
};
class UnixServer {
std::string path;
int sfd = -1;
ev::io sfdev;
void accept();
void ioCb(ev::io & watcher, int revents);
virtual void log(const std::string & log) const;
public:
UnixServer(const std::string & path);
/* create the public INDI Driver endpoint over UNIX (local) domain.
* exit on failure
*/
void listen();
};
static void log(const std::string & log);
/* Turn a printf format into std::string */
static std::string fmt(const char * fmt, ...) __attribute__ ((format (printf, 1, 0)));
static char *indi_tstamp(char *s);
static const char *me; /* our name */
static int port = INDIPORT; /* public INDI port */
static std::string unixSocketPath = INDIUNIXSOCK;
static int verbose; /* chattiness */
static char *ldir; /* where to log driver messages */
static unsigned int maxqsiz = (DEFMAXQSIZ * 1024 * 1024); /* kill if these bytes behind */
static unsigned int maxstreamsiz = (DEFMAXSSIZ * 1024 * 1024); /* drop blobs if these bytes behind while streaming*/
static int maxrestarts = DEFMAXRESTART;
static std::vector<XMLEle *> findBlobElements(XMLEle * root);
static void logStartup(int ac, char *av[]);
static void usage(void);
static void noSIGPIPE(void);
static char *indi_tstamp(char *s);
static void logDMsg(XMLEle *root, const char *dev);
static void Bye(void);
static int readFdError(int fd); /* Read a pending error condition on the given fd. Return errno value or 0 if none */
static void * attachSharedBuffer(int fd, size_t & size);
static void dettachSharedBuffer(int fd, void * ptr, size_t size);
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 = new Fifo();
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 'u':
if (ac < 2)
{
fprintf(stderr, "-f requires local socket path\n");
usage();
}
unixSocketPath = *++av;
ac--;
break;
case 'f':
if (ac < 2)
{
fprintf(stderr, "-f requires fifo node\n");
usage();
}
fifo = new Fifo(*++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)
usage();
/* take care of some unixisms */
noSIGPIPE();
/* start each driver */
while (ac-- > 0)
{
std::string dvrName = *av++;
DvrInfo * dr;
if (dvrName.find('@') != std::string::npos) {
dr = new RemoteDvrInfo();
} else {
dr = new LocalDvrInfo();
}
dr->name = dvrName;
dr->start();
}
/* announce we are online */
(new TcpServer(port))->listen();
/* create a new unix server */
(new UnixServer(unixSocketPath))->listen();
/* Load up FIFO, if available */
if (fifo) fifo->listen();
/* handle new clients and all io */
loop.loop();
/* will not happen unless no more listener left ! */
log("unexpected return from event loop\n");
return (1);
}
/* record we have started and our args */
static void logStartup(int ac, char *av[])
{
int i;
std::string startupMsg = "startup:";
for (i = 0; i < ac; i++) {
startupMsg += " ";
startupMsg += av[i];
}
log(startupMsg);
}
/* 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, " -u path : Path for the local connection socket (abstract), default %s\n", INDIUNIXSOCK);
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);
}
/* turn off SIGPIPE on bad write so we can handle it inline */
static void noSIGPIPE()
{
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_IGN;