~ubuntu-branches/ubuntu/quantal/libindi/quantal

« back to all changes in this revision

Viewing changes to .svn/tmp/indiserver.c.tmp

  • Committer: Bazaar Package Importer
  • Author(s): Rohan Garg, Rohan Garg, Jonathan Riddell, Jonathan Thomas
  • Date: 2011-07-14 18:18:04 UTC
  • mfrom: (1.1.2 upstream)
  • Revision ID: james.westby@ubuntu.com-20110714181804-3fybxiy3tpjnk9kq
Tags: 0.8-0ubuntu1
[ Rohan Garg ]
* New upstream release
  - Add boost to build deps
  - Bump soversion to 0.8

[ Jonathan Riddell ]
* Use source format 3.0
* Add kubuntu_01_link_pthreads.diff to fix linking with pthreads

[ Jonathan Thomas ]
* Change Maintainer from MOTU to Ubuntu Developers

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/* INDI Server for protocol version 1.7.
2
 
 * Copyright (C) 2007 Elwood C. Downey ecdowney@clearskyinstitute.com
3
 
 
4
 
    This library is free software; you can redistribute it and/or
5
 
    modify it under the terms of the GNU Lesser General Public
6
 
    License as published by the Free Software Foundation; either
7
 
    version 2.1 of the License, or (at your option) any later version.
8
 
 
9
 
    This library is distributed in the hope that it will be useful,
10
 
    but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12
 
    Lesser General Public License for more details.
13
 
 
14
 
    You should have received a copy of the GNU Lesser General Public
15
 
    License along with this library; if not, write to the Free Software
16
 
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
17
 
 
18
 
 * argv lists names of Driver programs to run or sockets to connect for Devices.
19
 
 * Drivers are restarted if they exit or connection closes.
20
 
 * Each local Driver's stdin/out are assumed to provide INDI traffic and are
21
 
 *   connected here via pipes. Local Drivers' stderr are connected to our
22
 
 *   stderr with date stamp and driver name prepended.
23
 
 * We only support Drivers that advertise support for one Device. The problem
24
 
 *   with multiple Devices in one Driver is without a way to know what they
25
 
 *   _all_ are there is no way to avoid sending all messages to all Drivers.
26
 
 * Outbound messages are limited to Devices and Properties seen inbound.
27
 
 *   Messages to Devices on sockets always include Device so the chained
28
 
 *   indiserver will only pass back info from that Device.
29
 
 * All newXXX() received from one Client are echoed to all other Clients who
30
 
 *   have shown an interest in the same Device and property.
31
 
 *
32
 
 * Implementation notes:
33
 
 *
34
 
 * We fork each driver and open a server socket listening for INDI clients.
35
 
 * Then forever we listen for new clients and pass traffic between clients and
36
 
 * drivers, subject to optimizations based on sniffing messages for matching
37
 
 * Devices and Properties. Since one message might be destined to more than
38
 
 * one client or device, they are queued and only removed after the last
39
 
 * consumer is finished. XMLEle are converted to linear strings before being
40
 
 * sent to optimize write system calls and avoid blocking to slow clients.
41
 
 * Clients that get more than maxqsiz bytes behind are shut down.
42
 
 */
43
 
 
44
 
#include <stdio.h>
45
 
#include <stdlib.h>
46
 
#include <stdarg.h>
47
 
#include <signal.h>
48
 
#include <string.h>
49
 
#include <errno.h>
50
 
#include <unistd.h>
51
 
#include <time.h>
52
 
#include <fcntl.h>
53
 
#include <sys/time.h>
54
 
#include <sys/types.h>
55
 
#include <sys/stat.h>
56
 
#include <sys/socket.h>
57
 
#include <netinet/in.h>
58
 
#include <netdb.h>
59
 
#include <arpa/inet.h>
60
 
 
61
 
#include "lilxml.h"
62
 
#include "indiapi.h"
63
 
#include "fq.h"
64
 
 
65
 
#define INDIPORT        7624            /* default TCP/IP port to listen */
66
 
#define REMOTEDVR       (-1234)         /* invalid PID to flag remote drivers */
67
 
#define MAXRBUF         4096            /* max read buffering here */
68
 
#define MAXWSIZ         4096            /* max bytes/write */
69
 
#define DEFMAXQSIZ      10              /* default max q behind, MB */
70
 
 
71
 
/* associate a usage count with queuded client or device message */
72
 
typedef struct {
73
 
    int count;                          /* number of consumers left */
74
 
    unsigned int cl;                    /* content length */
75
 
    char *cp;                           /* content: buf or malloced */
76
 
    char buf[MAXWSIZ];          /* local buf for most messages */
77
 
} Msg;
78
 
 
79
 
/* BLOB handling, NEVER is the default */
80
 
typedef enum {B_NEVER=0, B_ALSO, B_ONLY} BLOBHandling;
81
 
 
82
 
/* device + property name */
83
 
typedef struct {
84
 
    char dev[MAXINDIDEVICE];
85
 
    char name[MAXINDINAME];
86
 
} Property;
87
 
 
88
 
/* record of each snooped property */
89
 
typedef struct {
90
 
    Property prop;
91
 
    BLOBHandling blob;                  /* when to snoop BLOBs */
92
 
} Snoopee;
93
 
 
94
 
/* info for each connected client */
95
 
typedef struct {
96
 
    int active;                         /* 1 when this record is in use */
97
 
    Property *props;                    /* malloced array of props we want */
98
 
    int nprops;                         /* n entries in props[] */
99
 
    int allprops;                       /* saw getProperties w/o device */
100
 
    BLOBHandling blob;                  /* when to send setBLOBs */
101
 
    int s;                              /* socket for this client */
102
 
    LilXML *lp;                         /* XML parsing context */
103
 
    FQ *msgq;                           /* Msg queue */
104
 
    unsigned int nsent;                         /* bytes of current Msg sent so far */
105
 
} ClInfo;
106
 
static ClInfo *clinfo;                  /*  malloced pool of clients */
107
 
static int nclinfo;                     /* n total (not active) */
108
 
 
109
 
/* info for each connected driver */
110
 
typedef struct {
111
 
    const char *name;                           /* persistent malloced name */
112
 
    char dev[MAXINDIDEVICE];            /* device served by this driver */
113
 
    Snoopee *sprops;                    /* malloced array of props we snoop */
114
 
    int nsprops;                        /* n entries in sprops[] */
115
 
    int pid;                            /* process id or REMOTEDVR if remote */
116
 
    int rfd;                            /* read pipe fd */
117
 
    int wfd;                            /* write pipe fd */
118
 
    int efd;                            /* stderr from driver, if local */
119
 
    int restarts;                       /* times process has been restarted */
120
 
    LilXML *lp;                         /* XML parsing context */
121
 
    FQ *msgq;                           /* Msg queue */
122
 
    unsigned int nsent;                 /* bytes of current Msg sent so far */
123
 
} DvrInfo;
124
 
static DvrInfo *dvrinfo;                /* malloced array of drivers */
125
 
static int ndvrinfo;                    /* n total */
126
 
 
127
 
static char *me;                        /* our name */
128
 
static int port = INDIPORT;             /* public INDI port */
129
 
static int verbose;                     /* chattiness */
130
 
static int lsocket;                     /* listen socket */
131
 
static char *ldir;                      /* where to log driver messages */
132
 
static int maxqsiz = (DEFMAXQSIZ*1024*1024); /* kill if these bytes behind */
133
 
 
134
 
static void logStartup(int ac, char *av[]);
135
 
static void usage (void);
136
 
static void noZombies (void);
137
 
static void noSIGPIPE (void);
138
 
static void indiRun (void);
139
 
static void indiListen (void);
140
 
static void newClient (void);
141
 
static int newClSocket (void);
142
 
static void shutdownClient (ClInfo *cp);
143
 
static int readFromClient (ClInfo *cp);
144
 
static void startDvr (DvrInfo *dp);
145
 
static void startLocalDvr (DvrInfo *dp);
146
 
static void startRemoteDvr (DvrInfo *dp);
147
 
static int openINDIServer (char host[], int indi_port);
148
 
static void restartDvr (DvrInfo *dp);
149
 
static void q2RDrivers (const char *dev, Msg *mp, XMLEle *root);
150
 
static void q2SDrivers (int isblob, const char *dev, const char *name, Msg *mp,
151
 
    XMLEle *root);
152
 
static int q2Clients (ClInfo *notme, int isblob, const char *dev, const char *name,
153
 
    Msg *mp, XMLEle *root);
154
 
static void q2NDrivers (int isblob, const char *dev, const char *name, Msg *mp, XMLEle *root);
155
 
static void addSDevice (DvrInfo *dp, const char *dev, const char *name);
156
 
static Snoopee *findSDevice (DvrInfo *dp, const char *dev, const char *name);
157
 
static void addClDevice (ClInfo *cp, const char *dev, const char *name);
158
 
static int findClDevice (ClInfo *cp, const char *dev, const char *name);
159
 
static int readFromDriver (DvrInfo *dp);
160
 
static int stderrFromDriver (DvrInfo *dp);
161
 
static int msgQSize (FQ *q);
162
 
static void setMsgXMLEle (Msg *mp, XMLEle *root);
163
 
static void setMsgStr (Msg *mp, char *str);
164
 
static void freeMsg (Msg *mp);
165
 
static Msg *newMsg (void);
166
 
static int sendClientMsg (ClInfo *cp);
167
 
static int sendDriverMsg (DvrInfo *cp);
168
 
static void crackBLOB (char *enableBLOB, BLOBHandling *bp);
169
 
static void traceMsg (XMLEle *root);
170
 
static char *indi_tstamp (char *s);
171
 
static void logDMsg (XMLEle *root, const char *dev);
172
 
static void Bye(void);
173
 
 
174
 
int
175
 
main (int ac, char *av[])
176
 
{
177
 
        /* log startup */
178
 
        logStartup(ac, av);
179
 
 
180
 
        /* save our name */
181
 
        me = av[0];
182
 
 
183
 
        /* crack args */
184
 
        while ((--ac > 0) && ((*++av)[0] == '-')) {
185
 
            char *s;
186
 
            for (s = av[0]+1; *s != '\0'; s++)
187
 
                switch (*s) {
188
 
                case 'l':
189
 
                    if (ac < 2) {
190
 
                        fprintf (stderr, "-l requires log directory\n");
191
 
                        usage();
192
 
                    }
193
 
                    ldir = *++av;
194
 
                    ac--;
195
 
                    break;
196
 
                case 'm':
197
 
                    if (ac < 2) {
198
 
                        fprintf (stderr, "-m requires max MB behind\n");
199
 
                        usage();
200
 
                    }
201
 
                    maxqsiz = 1024*1024*atoi(*++av);
202
 
                    ac--;
203
 
                    break;
204
 
                case 'p':
205
 
                    if (ac < 2) {
206
 
                        fprintf (stderr, "-p requires port value\n");
207
 
                        usage();
208
 
                    }
209
 
                    port = atoi(*++av);
210
 
                    ac--;
211
 
                    break;
212
 
                case 'v':
213
 
                    verbose++;
214
 
                    break;
215
 
                default:
216
 
                    usage();
217
 
                }
218
 
        }
219
 
 
220
 
        /* at this point there are ac args in av[] to name our drivers */
221
 
        if (ac == 0)
222
 
            usage();
223
 
 
224
 
        /* take care of some unixisms */
225
 
        noZombies();
226
 
        noSIGPIPE();
227
 
 
228
 
        /* realloc seed for client pool */
229
 
        clinfo = (ClInfo *) malloc (1);
230
 
        nclinfo = 0;
231
 
 
232
 
        /* create driver info array all at once since size never changes */
233
 
        ndvrinfo = ac;
234
 
        dvrinfo = (DvrInfo *) calloc (ndvrinfo, sizeof(DvrInfo));
235
 
 
236
 
        /* start each driver */
237
 
        while (ac-- > 0) {
238
 
            dvrinfo[ac].name = *av++;
239
 
            startDvr (&dvrinfo[ac]);
240
 
        }
241
 
 
242
 
        /* announce we are online */
243
 
        indiListen();
244
 
 
245
 
        /* handle new clients and all io */
246
 
        while (1)
247
 
            indiRun();
248
 
 
249
 
        /* whoa! */
250
 
        fprintf (stderr, "unexpected return from main\n");
251
 
        return (1);
252
 
}
253
 
 
254
 
/* record we have started and our args */
255
 
static void
256
 
logStartup(int ac, char *av[])
257
 
{
258
 
        int i;
259
 
 
260
 
        fprintf (stderr, "%s: startup: ", indi_tstamp(NULL));
261
 
        for (i = 0; i < ac; i++)
262
 
            fprintf (stderr, "%s ", av[i]);
263
 
        fprintf (stderr, "\n");
264
 
}
265
 
 
266
 
/* print usage message and exit (2) */
267
 
static void
268
 
usage(void)
269
 
{
270
 
        fprintf (stderr, "Usage: %s [options] driver [driver ...]\n", me);
271
 
        fprintf (stderr, "Purpose: server for local and remote INDI drivers\n");
272
 
        fprintf (stderr, "Code %s. Protocol %g.\n", "$Revision: 726523 $", INDIV);
273
 
        fprintf (stderr, "Options:\n");
274
 
        fprintf (stderr, " -l d  : log driver messages to <d>/YYYY-MM-DD.islog\n");
275
 
        fprintf (stderr, " -m m  : kill client if gets more than this many MB behind, default %d\n", DEFMAXQSIZ);
276
 
        fprintf (stderr, " -p p  : alternate IP port, default %d\n", INDIPORT);
277
 
        fprintf (stderr, " -v    : show key events, no traffic\n");
278
 
        fprintf (stderr, " -vv   : -v + key message content\n");
279
 
        fprintf (stderr, " -vvv  : -vv + complete xml\n");
280
 
        fprintf (stderr, "driver : executable or device@host[:port]\n");
281
 
 
282
 
        exit (2);
283
 
}
284
 
 
285
 
/* arrange for no zombies if drivers die */
286
 
static void
287
 
noZombies()
288
 
{
289
 
        struct sigaction sa;
290
 
        sa.sa_handler = SIG_IGN;
291
 
        sigemptyset(&sa.sa_mask);
292
 
#ifdef SA_NOCLDWAIT
293
 
        sa.sa_flags = SA_NOCLDWAIT;
294
 
#else
295
 
        sa.sa_flags = 0;
296
 
#endif
297
 
        (void)sigaction(SIGCHLD, &sa, NULL);
298
 
}
299
 
 
300
 
/* turn off SIGPIPE on bad write so we can handle it inline */
301
 
static void
302
 
noSIGPIPE()
303
 
{
304
 
        struct sigaction sa;
305
 
        sa.sa_handler = SIG_IGN;
306
 
        sigemptyset(&sa.sa_mask);
307
 
        (void)sigaction(SIGPIPE, &sa, NULL);
308
 
}
309
 
 
310
 
/* start the given INDI driver process or connection.
311
 
 * exit if trouble.
312
 
 */
313
 
static void
314
 
startDvr (DvrInfo *dp)
315
 
{
316
 
        if (strchr (dp->name, '@'))
317
 
            startRemoteDvr (dp);
318
 
        else
319
 
            startLocalDvr (dp);
320
 
}
321
 
 
322
 
/* start the given local INDI driver process.
323
 
 * exit if trouble.
324
 
 */
325
 
static void
326
 
startLocalDvr (DvrInfo *dp)
327
 
{
328
 
        Msg *mp;
329
 
        char buf[1024];
330
 
        int rp[2], wp[2], ep[2];
331
 
        int pid;
332
 
 
333
 
        /* build three pipes: r, w and error*/
334
 
        if (pipe (rp) < 0) {
335
 
            fprintf (stderr, "%s: read pipe: %s\n", indi_tstamp(NULL),
336
 
                                                            strerror(errno));
337
 
            Bye();
338
 
        }
339
 
        if (pipe (wp) < 0) {
340
 
            fprintf (stderr, "%s: write pipe: %s\n", indi_tstamp(NULL),
341
 
                                                            strerror(errno));
342
 
            Bye();
343
 
        }
344
 
        if (pipe (ep) < 0) {
345
 
            fprintf (stderr, "%s: stderr pipe: %s\n", indi_tstamp(NULL),
346
 
                                                            strerror(errno));
347
 
            Bye();
348
 
        }
349
 
 
350
 
        /* fork&exec new process */
351
 
        pid = fork();
352
 
        if (pid < 0) {
353
 
            fprintf (stderr, "%s: fork: %s\n", indi_tstamp(NULL), strerror(errno));
354
 
            Bye();
355
 
        }
356
 
        if (pid == 0) {
357
 
            /* child: exec name */
358
 
            int fd;
359
 
 
360
 
            /* rig up pipes */
361
 
            dup2 (wp[0], 0);    /* driver stdin reads from wp[0] */
362
 
            dup2 (rp[1], 1);    /* driver stdout writes to rp[1] */
363
 
            dup2 (ep[1], 2);    /* driver stderr writes to e[]1] */
364
 
            for (fd = 3; fd < 100; fd++)
365
 
                (void) close (fd);
366
 
 
367
 
            /* go -- should never return */
368
 
            execlp (dp->name, dp->name, NULL);
369
 
            fprintf (stderr, "%s: Driver %s: execlp: %s\n", indi_tstamp(NULL),
370
 
                                                dp->name, strerror(errno));
371
 
            _exit (1);  /* parent will notice EOF shortly */
372
 
        }
373
 
 
374
 
        /* don't need child's side of pipes */
375
 
        close (wp[0]);
376
 
        close (rp[1]);
377
 
        close (ep[1]);
378
 
 
379
 
        /* record pid, io channels, init lp and snoop list */
380
 
        dp->pid = pid;
381
 
        dp->rfd = rp[0];
382
 
        dp->wfd = wp[1];
383
 
        dp->efd = ep[0];
384
 
        dp->lp = newLilXML();
385
 
        dp->msgq = newFQ(1);
386
 
        dp->sprops = (Snoopee*) malloc (1);     /* seed for realloc */
387
 
        dp->nsprops = 0;
388
 
        dp->nsent = 0;
389
 
 
390
 
        /* first message primes driver to report its properties -- dev known
391
 
         * if restarting
392
 
         */
393
 
        mp = newMsg();
394
 
        pushFQ (dp->msgq, mp);
395
 
        if (dp->dev[0])
396
 
            sprintf (buf, "<getProperties device='%s' version='%g'/>\n",
397
 
                                                            dp->dev, INDIV);
398
 
        else
399
 
            sprintf (buf, "<getProperties version='%g'/>\n", INDIV);
400
 
        setMsgStr (mp, buf);
401
 
        mp->count++;
402
 
 
403
 
        if (verbose > 0)
404
 
            fprintf (stderr, "%s: Driver %s: pid=%d rfd=%d wfd=%d efd=%d\n",
405
 
                    indi_tstamp(NULL), dp->name, dp->pid, dp->rfd, dp->wfd, dp->efd);
406
 
}
407
 
 
408
 
/* start the given remote INDI driver connection.
409
 
 * exit if trouble.
410
 
 */
411
 
static void
412
 
startRemoteDvr (DvrInfo *dp)
413
 
{
414
 
        Msg *mp;
415
 
        char dev[1024];
416
 
        char host[1024];
417
 
        char buf[1024];
418
 
        int indi_port, sockfd;
419
 
 
420
 
        /* extract host and port */
421
 
        indi_port = INDIPORT;
422
 
        if (sscanf (dp->name, "%[^@]@%[^:]:%d", dev, host, &indi_port) < 2) {
423
 
            fprintf (stderr, "Bad remote device syntax: %s\n", dp->name);
424
 
            Bye();
425
 
        }
426
 
 
427
 
        /* connect */
428
 
        sockfd = openINDIServer (host, indi_port);
429
 
 
430
 
        /* record flag pid, io channels, init lp and snoop list */
431
 
        dp->pid = REMOTEDVR;
432
 
        dp->rfd = sockfd;
433
 
        dp->wfd = sockfd;
434
 
        dp->lp = newLilXML();
435
 
        dp->msgq = newFQ(1);
436
 
        dp->sprops = (Snoopee*) malloc (1);     /* seed for realloc */
437
 
        dp->nsprops = 0;
438
 
        dp->nsent = 0;
439
 
 
440
 
        /* N.B. storing name now is key to limiting outbound traffic to this
441
 
         * dev.
442
 
         */
443
 
        strncpy (dp->dev, dev, MAXINDIDEVICE-1);
444
 
        dp->dev[MAXINDIDEVICE-1] = '\0';
445
 
 
446
 
        /* Sending getProperties with device lets remote server limit its
447
 
         * outbound (and our inbound) traffic on this socket to this device.
448
 
         */
449
 
        mp = newMsg();
450
 
        pushFQ (dp->msgq, mp);
451
 
        sprintf (buf, "<getProperties device='%s' version='%g'/>\n",
452
 
                                                            dp->dev, INDIV);
453
 
        setMsgStr (mp, buf);
454
 
        mp->count++;
455
 
 
456
 
        if (verbose > 0)
457
 
            fprintf (stderr, "%s: Driver %s: socket=%d\n", indi_tstamp(NULL),
458
 
                                                            dp->name, sockfd);
459
 
}
460
 
 
461
 
/* open a connection to the given host and port or die.
462
 
 * return socket fd.
463
 
 */
464
 
static int
465
 
openINDIServer (char host[], int indi_port)
466
 
{
467
 
        struct sockaddr_in serv_addr;
468
 
        struct hostent *hp;
469
 
        int sockfd;
470
 
 
471
 
        /* lookup host address */
472
 
        hp = gethostbyname (host);
473
 
        if (!hp) {
474
 
            fprintf (stderr, "gethostbyname(%s): %s\n", host, strerror(errno));
475
 
            Bye();
476
 
        }
477
 
 
478
 
        /* create a socket to the INDI server */
479
 
        (void) memset ((char *)&serv_addr, 0, sizeof(serv_addr));
480
 
        serv_addr.sin_family = AF_INET;
481
 
        serv_addr.sin_addr.s_addr =
482
 
                            ((struct in_addr *)(hp->h_addr_list[0]))->s_addr;
483
 
        serv_addr.sin_port = htons(indi_port);
484
 
        if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0) {
485
 
            fprintf (stderr, "socket(%s,%d): %s\n", host, indi_port,strerror(errno));
486
 
            Bye();
487
 
        }
488
 
 
489
 
        /* connect */
490
 
        if (connect (sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr))<0){
491
 
            fprintf (stderr, "connect(%s,%d): %s\n", host,indi_port,strerror(errno));
492
 
            Bye();
493
 
        }
494
 
 
495
 
        /* ok */
496
 
        return (sockfd);
497
 
}
498
 
 
499
 
/* create the public INDI Driver endpoint lsocket on port.
500
 
 * return server socket else exit.
501
 
 */
502
 
static void
503
 
indiListen ()
504
 
{
505
 
        struct sockaddr_in serv_socket;
506
 
        int sfd;
507
 
        int reuse = 1;
508
 
 
509
 
        /* make socket endpoint */
510
 
        if ((sfd = socket (AF_INET, SOCK_STREAM, 0)) < 0) {
511
 
            fprintf (stderr, "%s: socket: %s\n", indi_tstamp(NULL), strerror(errno));
512
 
            Bye();
513
 
        }
514
 
 
515
 
        /* bind to given port for any IP address */
516
 
        memset (&serv_socket, 0, sizeof(serv_socket));
517
 
        serv_socket.sin_family = AF_INET;
518
 
        #ifdef SSH_TUNNEL
519
 
        serv_socket.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
520
 
        #else
521
 
        serv_socket.sin_addr.s_addr = htonl (INADDR_ANY);
522
 
        #endif
523
 
        serv_socket.sin_port = htons ((unsigned short)port);
524
 
        if (setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse)) < 0){
525
 
            fprintf (stderr, "%s: setsockopt: %s\n", indi_tstamp(NULL),
526
 
                                                            strerror(errno));
527
 
            Bye();
528
 
        }
529
 
        if (bind(sfd,(struct sockaddr*)&serv_socket,sizeof(serv_socket)) < 0){
530
 
            fprintf (stderr, "%s: bind: %s\n", indi_tstamp(NULL), strerror(errno));
531
 
            Bye();
532
 
        }
533
 
 
534
 
        /* willing to accept connections with a backlog of 5 pending */
535
 
        if (listen (sfd, 5) < 0) {
536
 
            fprintf (stderr, "%s: listen: %s\n", indi_tstamp(NULL), strerror(errno));
537
 
            Bye();
538
 
        }
539
 
 
540
 
        /* ok */
541
 
        lsocket = sfd;
542
 
        if (verbose > 0)
543
 
            fprintf (stderr, "%s: listening to port %d on fd %d\n",
544
 
                                                indi_tstamp(NULL), port, sfd);
545
 
}
546
 
 
547
 
/* service traffic from clients and drivers */
548
 
static void
549
 
indiRun(void)
550
 
{
551
 
        fd_set rs, ws;
552
 
        int maxfd;
553
 
        int i, s;
554
 
 
555
 
        /* init with no writers or readers */
556
 
        FD_ZERO(&ws);
557
 
        FD_ZERO(&rs);
558
 
 
559
 
        /* always listen for new clients */
560
 
        FD_SET(lsocket, &rs);
561
 
        maxfd = lsocket;
562
 
 
563
 
        /* add all client readers and client writers with work to send */
564
 
        for (i = 0; i < nclinfo; i++) {
565
 
            ClInfo *cp = &clinfo[i];
566
 
            if (cp->active) {
567
 
                FD_SET(cp->s, &rs);
568
 
                if (nFQ(cp->msgq) > 0)
569
 
                    FD_SET(cp->s, &ws);
570
 
                if (cp->s > maxfd)
571
 
                    maxfd = cp->s;
572
 
            }
573
 
        }
574
 
 
575
 
        /* add all driver readers and driver writers with work to send */
576
 
        for (i = 0; i < ndvrinfo; i++) {
577
 
            DvrInfo *dp = &dvrinfo[i];
578
 
            FD_SET(dp->rfd, &rs);
579
 
            if (dp->rfd > maxfd)
580
 
                maxfd = dp->rfd;
581
 
            if (dp->pid != REMOTEDVR) {
582
 
                FD_SET(dp->efd, &rs);
583
 
                if (dp->efd > maxfd)
584
 
                    maxfd = dp->efd;
585
 
            }
586
 
            if (nFQ(dp->msgq) > 0) {
587
 
                FD_SET(dp->wfd, &ws);
588
 
                if (dp->wfd > maxfd)
589
 
                    maxfd = dp->wfd;
590
 
            }
591
 
        }
592
 
 
593
 
        /* wait for action */
594
 
        s = select (maxfd+1, &rs, &ws, NULL, NULL);
595
 
        if (s < 0) {
596
 
            fprintf (stderr, "%s: select(%d): %s\n", indi_tstamp(NULL), maxfd+1,
597
 
                                                            strerror(errno));
598
 
            Bye();
599
 
        }
600
 
 
601
 
        /* new client? */
602
 
        if (s > 0 && FD_ISSET(lsocket, &rs)) {
603
 
            newClient();
604
 
            s--;
605
 
        }
606
 
 
607
 
        /* message to/from client? */
608
 
        for (i = 0; s > 0 && i < nclinfo; i++) {
609
 
            ClInfo *cp = &clinfo[i];
610
 
            if (cp->active) {
611
 
                if (FD_ISSET(cp->s, &rs)) {
612
 
                    if (readFromClient(cp) < 0)
613
 
                        return; /* fds effected */
614
 
                    s--;
615
 
                }
616
 
                if (s > 0 && FD_ISSET(cp->s, &ws)) {
617
 
                    if (sendClientMsg(cp) < 0)
618
 
                        return; /* fds effected */
619
 
                    s--;
620
 
                }
621
 
            }
622
 
        }
623
 
 
624
 
        /* message to/from driver? */
625
 
        for (i = 0; s > 0 && i < ndvrinfo; i++) {
626
 
            DvrInfo *dp = &dvrinfo[i];
627
 
            if (dp->pid != REMOTEDVR && FD_ISSET(dp->efd, &rs)) {
628
 
                if (stderrFromDriver(dp) < 0)
629
 
                    return;     /* fds effected */
630
 
                s--;
631
 
            }
632
 
            if (s > 0 && FD_ISSET(dp->rfd, &rs)) {
633
 
                if (readFromDriver(dp) < 0)
634
 
                    return;     /* fds effected */
635
 
                s--;
636
 
            }
637
 
            if (s > 0 && FD_ISSET(dp->wfd, &ws) && nFQ(dp->msgq) > 0) {
638
 
                if (sendDriverMsg(dp) < 0)
639
 
                    return;     /* fds effected */
640
 
                s--;
641
 
            }
642
 
        }
643
 
}
644
 
 
645
 
/* prepare for new client arriving on lsocket.
646
 
 * exit if trouble.
647
 
 */
648
 
static void
649
 
newClient()
650
 
{
651
 
        ClInfo *cp = NULL;
652
 
        int s, cli;
653
 
 
654
 
        /* assign new socket */
655
 
        s = newClSocket ();
656
 
 
657
 
        /* try to reuse a clinfo slot, else add one */
658
 
        for (cli = 0; cli < nclinfo; cli++)
659
 
            if (!(cp = &clinfo[cli])->active)
660
 
                break;
661
 
        if (cli == nclinfo) {
662
 
            /* grow clinfo */
663
 
            clinfo = (ClInfo *) realloc (clinfo, (nclinfo+1)*sizeof(ClInfo));
664
 
            if (!clinfo) {
665
 
                fprintf (stderr, "no memory for new client\n");
666
 
                Bye();
667
 
            }
668
 
            cp = &clinfo[nclinfo++];
669
 
        }
670
 
 
671
 
        /* rig up new clinfo entry */
672
 
        memset (cp, 0, sizeof(*cp));
673
 
        cp->active = 1;
674
 
        cp->s = s;
675
 
        cp->lp = newLilXML();
676
 
        cp->msgq = newFQ(1);
677
 
        cp->props = malloc (1);
678
 
        cp->nsent = 0;
679
 
 
680
 
        if (verbose > 0) {
681
 
            struct sockaddr_in addr;
682
 
            socklen_t len = sizeof(addr);
683
 
            getpeername(s, (struct sockaddr*)&addr, &len);
684
 
            fprintf(stderr,"%s: Client %d: new arrival from %s:%d - welcome!\n",
685
 
                            indi_tstamp(NULL), cp->s, inet_ntoa(addr.sin_addr),
686
 
                                                        ntohs(addr.sin_port));
687
 
        }
688
 
}
689
 
 
690
 
/* read more from the given client, send to each appropriate driver when see
691
 
 * xml closure. also send all newXXX() to all other interested clients.
692
 
 * return -1 if had to shut down anything, else 0.
693
 
 */
694
 
static int
695
 
readFromClient (ClInfo *cp)
696
 
{
697
 
        char buf[MAXRBUF];
698
 
        int shutany = 0;
699
 
        int i, nr;
700
 
 
701
 
        /* read client */
702
 
        nr = read (cp->s, buf, sizeof(buf));
703
 
        if (nr <= 0) {
704
 
            if (nr < 0)
705
 
                fprintf (stderr, "%s: Client %d: read: %s\n", indi_tstamp(NULL),
706
 
                                                        cp->s, strerror(errno));
707
 
            else if (verbose > 0)
708
 
                fprintf (stderr, "%s: Client %d: read EOF\n", indi_tstamp(NULL),
709
 
                                                                        cp->s);
710
 
            shutdownClient (cp);
711
 
            return (-1);
712
 
        }
713
 
 
714
 
        /* process XML, sending when find closure */
715
 
        for (i = 0; i < nr; i++) {
716
 
            char err[1024];
717
 
            XMLEle *root = readXMLEle (cp->lp, buf[i], err);
718
 
            if (root) {
719
 
                char *roottag = tagXMLEle(root);
720
 
                const char *dev = findXMLAttValu (root, "device");
721
 
                const char *name = findXMLAttValu (root, "name");
722
 
                int isblob = !strcmp (tagXMLEle(root), "setBLOBVector");
723
 
                Msg *mp;
724
 
 
725
 
                if (verbose > 2) {
726
 
                    fprintf (stderr, "%s: Client %d: read ",indi_tstamp(NULL),cp->s);
727
 
                    traceMsg (root);
728
 
                } else if (verbose > 1) {
729
 
                    fprintf (stderr, "%s: Client %d: read <%s device='%s' name='%s'>\n",
730
 
                                    indi_tstamp(NULL), cp->s, tagXMLEle(root),
731
 
                                    findXMLAttValu (root, "device"),
732
 
                                    findXMLAttValu (root, "name"));
733
 
                }
734
 
 
735
 
                /* snag interested properties.
736
 
                 * N.B. don't open to alldevs if seen specific dev already, else
737
 
                 *   remote client connections start returning too much.
738
 
                 */
739
 
                if (dev[0])
740
 
                    addClDevice (cp, dev, name);
741
 
                else if (!strcmp (roottag, "getProperties") && !cp->nprops)
742
 
                    cp->allprops = 1;
743
 
 
744
 
                /* snag enableBLOB -- send to remote drivers too */
745
 
                if (!strcmp (roottag, "enableBLOB"))
746
 
                    crackBLOB (pcdataXMLEle(root), &cp->blob);
747
 
 
748
 
                /* build a new message -- set content iff anyone cares */
749
 
                mp = newMsg();
750
 
 
751
 
                /* send message to driver(s) responsible for dev */
752
 
                q2RDrivers (dev, mp, root);
753
 
 
754
 
                /* echo new* commands back to other clients */
755
 
                if (!strncmp (roottag, "new", 3)) {
756
 
                    if (q2Clients (cp, isblob, dev, name, mp, root) < 0)
757
 
                        shutany++;
758
 
                }
759
 
 
760
 
                /* set message content if anyone cares else forget it */
761
 
                if (mp->count > 0)
762
 
                    setMsgXMLEle (mp, root);
763
 
                else
764
 
                    freeMsg (mp);
765
 
                delXMLEle (root);
766
 
 
767
 
            } else if (err[0]) {
768
 
                char *ts = indi_tstamp(NULL);
769
 
                fprintf (stderr, "%s: Client %d: XML error: %s\n", ts,
770
 
                                                                cp->s, err);
771
 
                fprintf (stderr, "%s: Client %d: XML read: %.*s\n", ts,
772
 
                                                            cp->s, nr, buf);
773
 
                shutdownClient (cp);
774
 
                return (-1);
775
 
            }
776
 
        }
777
 
 
778
 
        return (shutany ? -1 : 0);
779
 
}
780
 
 
781
 
/* read more from the given driver, send to each interested client when see
782
 
 * xml closure. if driver dies, try restarting.
783
 
 * return 0 if ok else -1 if had to shut down anything.
784
 
 */
785
 
static int
786
 
readFromDriver (DvrInfo *dp)
787
 
{
788
 
        char buf[MAXRBUF];
789
 
        int shutany = 0;
790
 
        int i, nr;
791
 
 
792
 
        /* read driver */
793
 
        nr = read (dp->rfd, buf, sizeof(buf));
794
 
        if (nr <= 0) {
795
 
            if (nr < 0)
796
 
                fprintf (stderr, "%s: Driver %s: stdin %s\n", indi_tstamp(NULL),
797
 
                                                    dp->name, strerror(errno));
798
 
            else
799
 
                fprintf (stderr, "%s: Driver %s: stdin EOF\n",
800
 
                                                        indi_tstamp(NULL), dp->name);
801
 
            restartDvr (dp);
802
 
            return (-1);
803
 
        }
804
 
 
805
 
        /* process XML, sending when find closure */
806
 
        for (i = 0; i < nr; i++) {
807
 
            char err[1024];
808
 
            XMLEle *root = readXMLEle (dp->lp, buf[i], err);
809
 
            if (root) {
810
 
                char *roottag = tagXMLEle(root);
811
 
                const char *dev = findXMLAttValu (root, "device");
812
 
                const char *name = findXMLAttValu (root, "name");
813
 
                int isblob = !strcmp (tagXMLEle(root), "setBLOBVector");
814
 
                Msg *mp;
815
 
 
816
 
                if (verbose > 2) {
817
 
                    fprintf(stderr, "%s: Driver %s: read ", indi_tstamp(0),dp->name);
818
 
                    traceMsg (root);
819
 
                } else if (verbose > 1) {
820
 
                    fprintf (stderr, "%s: Driver %s: read <%s device='%s' name='%s'>\n",
821
 
                                    indi_tstamp(NULL), dp->name, tagXMLEle(root),
822
 
                                    findXMLAttValu (root, "device"),
823
 
                                    findXMLAttValu (root, "name"));
824
 
                }
825
 
 
826
 
                /* that's all if driver is just registering a snoop */
827
 
                if (!strcmp (roottag, "getProperties")) {
828
 
                    addSDevice (dp, dev, name);
829
 
                    delXMLEle (root);
830
 
                    continue;
831
 
                }
832
 
 
833
 
                /* that's all if driver is just registering a BLOB mode */
834
 
                if (!strcmp (roottag, "enableBLOB")) {
835
 
                    Snoopee *sp = findSDevice (dp, dev, name);
836
 
                    if (sp)
837
 
                        crackBLOB (pcdataXMLEle (root), &sp->blob);
838
 
                    delXMLEle (root);
839
 
                    continue;
840
 
                }
841
 
 
842
 
                /* snag device name if not known yet */
843
 
                if (!dp->dev[0] && dev[0]) {
844
 
                    strncpy (dp->dev, dev, MAXINDIDEVICE-1);
845
 
                    dp->dev[MAXINDIDEVICE-1] = '\0';
846
 
                }
847
 
 
848
 
                /* log messages if any and wanted */
849
 
                if (ldir)
850
 
                    logDMsg (root, dev);
851
 
 
852
 
                /* build a new message -- set content iff anyone cares */
853
 
                mp = newMsg();
854
 
 
855
 
                /* send to interested clients */
856
 
                if (q2Clients (NULL, isblob, dev, name, mp, root) < 0)
857
 
                    shutany++;
858
 
 
859
 
                /* send to snooping drivers */
860
 
                q2SDrivers (isblob, dev, name, mp, root);
861
 
 
862
 
                /* set message content if anyone cares else forget it */
863
 
                if (mp->count > 0)
864
 
                    setMsgXMLEle (mp, root);
865
 
                else
866
 
                    freeMsg (mp);
867
 
                delXMLEle (root);
868
 
 
869
 
            } else if (err[0]) {
870
 
                char *ts = indi_tstamp(NULL);
871
 
                fprintf (stderr, "%s: Driver %s: XML error: %s\n", ts,
872
 
                                                                dp->name, err);
873
 
                fprintf (stderr, "%s: Driver %s: XML read: %.*s\n", ts,
874
 
                                                            dp->name, nr, buf);
875
 
                restartDvr (dp);
876
 
                return (-1);
877
 
            }
878
 
        }
879
 
 
880
 
        return (shutany ? -1 : 0);
881
 
}
882
 
 
883
 
/* read more from the given driver stderr, add prefix and send to our stderr.
884
 
 * return 0 if ok else -1 if had to restart.
885
 
 */
886
 
static int
887
 
stderrFromDriver (DvrInfo *dp)
888
 
{
889
 
        static char exbuf[MAXRBUF];
890
 
        static int nexbuf;
891
 
        int i, nr;
892
 
 
893
 
        /* read more */
894
 
        nr = read (dp->efd, exbuf+nexbuf, sizeof(exbuf)-nexbuf);
895
 
        if (nr <= 0) {
896
 
            if (nr < 0)
897
 
                fprintf (stderr, "%s: Driver %s: stderr %s\n", indi_tstamp(NULL),
898
 
                                                    dp->name, strerror(errno));
899
 
            else
900
 
                fprintf (stderr, "%s: Driver %s: stderr EOF\n",
901
 
                                                        indi_tstamp(NULL), dp->name);
902
 
            restartDvr (dp);
903
 
            return (-1);
904
 
        }
905
 
        nexbuf += nr;
906
 
 
907
 
        /* prefix each whole line to our stderr, save extra for next time */
908
 
        for (i = 0; i < nexbuf; i++) {
909
 
            if (exbuf[i] == '\n') {
910
 
                fprintf (stderr, "%s: Driver %s: %.*s\n", indi_tstamp(NULL),
911
 
                                                            dp->name, i, exbuf);
912
 
                i++;                              /* count including nl */
913
 
                nexbuf -= i;                      /* remove from nexbuf */
914
 
                memmove (exbuf, exbuf+i, nexbuf); /* slide remaining to front */
915
 
                i = -1;                           /* restart for loop scan */
916
 
            }
917
 
        }
918
 
 
919
 
        return (0);
920
 
}
921
 
 
922
 
/* close down the given client */
923
 
static void
924
 
shutdownClient (ClInfo *cp)
925
 
{
926
 
        Msg *mp;
927
 
 
928
 
        /* close connection */
929
 
        shutdown (cp->s, SHUT_RDWR);
930
 
        close (cp->s);
931
 
 
932
 
        /* free memory */
933
 
        delLilXML (cp->lp);
934
 
        free (cp->props);
935
 
 
936
 
        /* decrement and possibly free any unsent messages for this client */
937
 
        while ((mp = (Msg*) popFQ(cp->msgq)) != NULL)
938
 
            if (--mp->count == 0)
939
 
                freeMsg (mp);
940
 
        delFQ (cp->msgq);
941
 
 
942
 
        /* ok now to recycle */
943
 
        cp->active = 0;
944
 
 
945
 
        if (verbose > 0)
946
 
            fprintf (stderr, "%s: Client %d: shut down complete - bye!\n",
947
 
                                                        indi_tstamp(NULL), cp->s);
948
 
}
949
 
 
950
 
/* close down the given driver and restart */
951
 
static void
952
 
restartDvr (DvrInfo *dp)
953
 
{
954
 
        Msg *mp;
955
 
 
956
 
        /* make sure it's dead, reclaim resources */
957
 
        if (dp->pid == REMOTEDVR) {
958
 
            /* socket connection */
959
 
            shutdown (dp->wfd, SHUT_RDWR);
960
 
            close (dp->wfd);    /* same as rfd */
961
 
        } else {
962
 
            /* local pipe connection */
963
 
            kill (dp->pid, SIGKILL);    /* we've insured there are no zombies */
964
 
            close (dp->wfd);
965
 
            close (dp->rfd);
966
 
            close (dp->efd);
967
 
        }
968
 
 
969
 
        /* free memory */
970
 
        free (dp->sprops);
971
 
        delLilXML (dp->lp);
972
 
 
973
 
        /* decrement and possibly free any unsent messages for this client */
974
 
        while ((mp = (Msg*) popFQ(dp->msgq)) != NULL)
975
 
            if (--mp->count == 0)
976
 
                freeMsg (mp);
977
 
        delFQ (dp->msgq);
978
 
 
979
 
        fprintf (stderr, "%s: Driver %s: restart #%d\n", indi_tstamp(NULL),
980
 
                                                    dp->name, ++dp->restarts);
981
 
        startDvr (dp);
982
 
}
983
 
 
984
 
/* put Msg mp on queue of each driver responsible for dev, or all drivers
985
 
 * if dev not specified.
986
 
 */
987
 
static void
988
 
q2RDrivers (const char *dev, Msg *mp, XMLEle *root)
989
 
{
990
 
        int sawremote = 0;
991
 
        DvrInfo *dp;
992
 
 
993
 
        /* queue message to each interested driver.
994
 
         * N.B. don't send generic getProps to more than one remote driver,
995
 
         *   otherwise they all fan out and we get multiple responses back.
996
 
         */
997
 
        for (dp = dvrinfo; dp < &dvrinfo[ndvrinfo]; dp++) {
998
 
            int isremote = (dp->pid == REMOTEDVR);
999
 
            if (dev[0] && dp->dev[0] && strcmp (dev, dp->dev))
1000
 
                continue;       /* driver known to not support this dev */
1001
 
            if (!dev[0] && isremote && sawremote)
1002
 
                continue;       /* already sent generic to another remote */
1003
 
            if (isremote)
1004
 
                sawremote = 1;
1005
 
 
1006
 
            /* ok: queue message to this driver */
1007
 
            mp->count++;
1008
 
            pushFQ (dp->msgq, mp);
1009
 
            if (verbose > 1)
1010
 
                fprintf (stderr, "%s: Driver %s: queuing responsible for <%s device='%s' name='%s'>\n",
1011
 
                                    indi_tstamp(NULL), dp->name, tagXMLEle(root),
1012
 
                                    findXMLAttValu (root, "device"),
1013
 
                                    findXMLAttValu (root, "name"));
1014
 
        }
1015
 
}
1016
 
 
1017
 
/* put Msg mp on queue of driver target in newXXX
1018
 
 * if BLOB always honor current mode.
1019
 
 */
1020
 
/* TODO We need to echo messages back to other drivers. If no drivers found with this name, then echo it back to other clients.
1021
 
static void*/
1022
 
q2NDrivers (int isblob, const char *dev, const char *name, Msg *mp, XMLEle *root)
1023
 
{
1024
 
 
1025
 
<<<<<<< .working
1026
 
        DvrInfo *dp;
1027
 
 
1028
 
        if (strstr(tagXMLEle(root), "new") == NULL)
1029
 
                return;
1030
 
 
1031
 
=======
1032
 
        DvrInfo *dp;
1033
 
 
1034
 
>>>>>>> .merge-right.r236
1035
 
<<<<<<< .working
1036
 
        for (dp = dvrinfo; dp < &dvrinfo[ndvrinfo]; dp++) 
1037
 
        {
1038
 
           fprintf(stderr, "Checking if we can send a newXXX command to driver %s for newXXX was issued to %s, snoop_redirect is %d\n", dp->dev, dev, snoop_redirect);
1039
 
           if (!strcmp(dp->dev, dev))
1040
 
           {
1041
 
                    if ((isblob && dp->blob==B_NEVER) || (!isblob && dp->blob==B_ONLY))
1042
 
                        return;
1043
 
 
1044
 
                    fprintf(stderr, "sending newXXX to driver %s\n", dp->dev);
1045
 
                    /* ok: queue message to this device */
1046
 
                    mp->count++;
1047
 
                    pushFQ (dp->msgq, mp);
1048
 
 
1049
 
                    if (verbose > 1)
1050
 
                    {
1051
 
                        fprintf (stderr, "%s: Driver %s: queuing snooped <%s device='%s' name='%s'>\n",
1052
 
                                    indi_tstamp(NULL), dp->name, tagXMLEle(root),
1053
 
                                    findXMLAttValu (root, "device"),
1054
 
                                    findXMLAttValu (root, "name"));
1055
 
                    }
1056
 
                    return;
1057
 
           }
1058
 
        }
1059
 
 
1060
 
}
1061
 
 
1062
 
/* put Msg mp on queue of each driver snooping dev/name.
1063
 
 * if BLOB always honor current mode.
1064
 
 */
1065
 
static void
1066
 
q2SDrivers (int isblob, const char *dev, const char *name, Msg *mp, XMLEle *root)
1067
 
{
1068
 
        DvrInfo *dp;
1069
 
        for (dp = dvrinfo; dp < &dvrinfo[ndvrinfo]; dp++) 
1070
 
        {
1071
 
=======
1072
 
        for (dp = dvrinfo; dp < &dvrinfo[ndvrinfo]; dp++) {
1073
 
>>>>>>> .merge-right.r236
1074
 
            Snoopee *sp = findSDevice (dp, dev, name);
1075
 
 
1076
 
            /* nothing for dp if not snooping for dev/name or wrong BLOB mode */
1077
 
            if (!sp)
1078
 
                continue;
1079
 
            if ((isblob && sp->blob==B_NEVER) || (!isblob && sp->blob==B_ONLY))
1080
 
                continue;
1081
 
 
1082
 
            /* ok: queue message to this device */
1083
 
            mp->count++;
1084
 
            pushFQ (dp->msgq, mp);
1085
 
            if (verbose > 1) {
1086
 
                fprintf (stderr, "%s: Driver %s: queuing snooped <%s device='%s' name='%s'>\n",
1087
 
                                    indi_tstamp(NULL), dp->name, tagXMLEle(root),
1088
 
                                    findXMLAttValu (root, "device"),
1089
 
                                    findXMLAttValu (root, "name"));
1090
 
            }
1091
 
        }
1092
 
}
1093
 
 
1094
 
/* add dev/name to dp's snooping list.
1095
 
 * init with blob mode set to B_NEVER.
1096
 
 */
1097
 
static void
1098
 
addSDevice (DvrInfo *dp, const char *dev, const char *name)
1099
 
{
1100
 
        Snoopee *sp;
1101
 
        char *ip;
1102
 
 
1103
 
        /* no dups */
1104
 
        sp = findSDevice (dp, dev, name);
1105
 
        if (sp)
1106
 
            return;
1107
 
 
1108
 
        /* add dev to sdevs list */
1109
 
        dp->sprops = (Snoopee*) realloc (dp->sprops,
1110
 
                                            (dp->nsprops+1)*sizeof(Snoopee));
1111
 
        sp = &dp->sprops[dp->nsprops++];
1112
 
 
1113
 
        ip = sp->prop.dev;
1114
 
        strncpy (ip, dev, MAXINDIDEVICE-1);
1115
 
        ip[MAXINDIDEVICE-1] = '\0';
1116
 
 
1117
 
        ip = sp->prop.name;
1118
 
        strncpy (ip, name, MAXINDINAME-1);
1119
 
        ip[MAXINDINAME-1] = '\0';
1120
 
 
1121
 
        sp->blob = B_NEVER;
1122
 
 
1123
 
        if (verbose)
1124
 
            fprintf (stderr, "%s: Driver %s: snooping on %s.%s\n", indi_tstamp(NULL),
1125
 
                                                        dp->name, dev, name);
1126
 
}
1127
 
 
1128
 
/* return Snoopee if dp is snooping dev/name, else NULL.
1129
 
 */
1130
 
static Snoopee *
1131
 
findSDevice (DvrInfo *dp, const char *dev, const char *name)
1132
 
{
1133
 
        int i;
1134
 
 
1135
 
        for (i = 0; i < dp->nsprops; i++) {
1136
 
            Snoopee *sp = &dp->sprops[i];
1137
 
            Property *pp = &sp->prop;
1138
 
            if (!strcmp (pp->dev, dev) &&
1139
 
                    (!pp->name[0] || !strcmp(pp->name, name)))
1140
 
                return (sp);
1141
 
        }
1142
 
 
1143
 
        return (NULL);
1144
 
}
1145
 
 
1146
 
/* put Msg mp on queue of each client interested in dev/name, except notme.
1147
 
 * if BLOB always honor current mode.
1148
 
 * return -1 if had to shut down any clients, else 0.
1149
 
 */
1150
 
static int
1151
 
q2Clients (ClInfo *notme, int isblob, const char *dev, const char *name, Msg *mp, XMLEle *root)
1152
 
{
1153
 
        int shutany = 0;
1154
 
        ClInfo *cp;
1155
 
        int ql;
1156
 
<<<<<<< .working
1157
 
 
1158
 
        /* Don't send newXXX messages to clients, for now 
1159
 
        if (strstr(tagXMLEle(root), "new"))
1160
 
                return 0;
1161
 
=======
1162
 
>>>>>>> .merge-right.r236
1163
 
        */
1164
 
 
1165
 
        /* queue message to each interested client */
1166
 
        for (cp = clinfo; cp < &clinfo[nclinfo]; cp++) {
1167
 
            /* cp in use? notme? want this dev/name? blob? */
1168
 
            if (!cp->active || cp == notme)
1169
 
                continue;
1170
 
            if (findClDevice (cp, dev, name) < 0)
1171
 
                continue;
1172
 
            if ((isblob && cp->blob==B_NEVER) || (!isblob && cp->blob==B_ONLY))
1173
 
                continue;
1174
 
 
1175
 
            /* shut down this client if its q is already too large */
1176
 
            ql = msgQSize(cp->msgq);
1177
 
            if (ql > maxqsiz) {
1178
 
                if (verbose)
1179
 
                    fprintf (stderr, "%s: Client %d: %d bytes behind, shutting down\n",
1180
 
                                                    indi_tstamp(NULL), cp->s, ql);
1181
 
                shutdownClient (cp);
1182
 
                shutany++;
1183
 
                continue;
1184
 
            }
1185
 
 
1186
 
            /* ok: queue message to this client */
1187
 
            mp->count++;
1188
 
            pushFQ (cp->msgq, mp);
1189
 
            if (verbose > 1)
1190
 
                fprintf (stderr, "%s: Client %d: queuing <%s device='%s' name='%s'>\n",
1191
 
                                    indi_tstamp(NULL), cp->s, tagXMLEle(root),
1192
 
                                    findXMLAttValu (root, "device"),
1193
 
                                    findXMLAttValu (root, "name"));
1194
 
        }
1195
 
 
1196
 
        return (shutany ? -1 : 0);
1197
 
}
1198
 
 
1199
 
/* return size of all Msqs on the given q */
1200
 
static int
1201
 
msgQSize (FQ *q)
1202
 
{
1203
 
        int i, l = 0;
1204
 
 
1205
 
        for (i = 0; i < nFQ(q); i++) {
1206
 
            Msg *mp = (Msg *) peekiFQ(q,i);
1207
 
            l += mp->cl;
1208
 
        }
1209
 
 
1210
 
        return (l);
1211
 
}
1212
 
 
1213
 
/* print root as content in Msg mp.
1214
 
 */
1215
 
static void
1216
 
setMsgXMLEle (Msg *mp, XMLEle *root)
1217
 
{
1218
 
        /* want cl to only count content, but need room for final \0 */
1219
 
        mp->cl = sprlXMLEle (root, 0);
1220
 
        if (mp->cl < sizeof(mp->buf))
1221
 
            mp->cp = mp->buf;
1222
 
        else
1223
 
            mp->cp = malloc (mp->cl+1);
1224
 
        sprXMLEle (mp->cp, root, 0);
1225
 
}
1226
 
 
1227
 
/* save str as content in Msg mp.
1228
 
 */
1229
 
static void
1230
 
setMsgStr (Msg *mp, char *str)
1231
 
{
1232
 
        /* want cl to only count content, but need room for final \0 */
1233
 
        mp->cl = strlen (str);
1234
 
        if (mp->cl < sizeof(mp->buf))
1235
 
            mp->cp = mp->buf;
1236
 
        else
1237
 
            mp->cp = malloc (mp->cl+1);
1238
 
        strcpy (mp->cp, str);
1239
 
}
1240
 
 
1241
 
/* return pointer to one new nulled Msg
1242
 
 */
1243
 
static Msg *
1244
 
newMsg (void)
1245
 
{
1246
 
        return ((Msg *) calloc (1, sizeof(Msg)));
1247
 
}
1248
 
 
1249
 
/* free Msg mp and everything it contains */
1250
 
static void
1251
 
freeMsg (Msg *mp)
1252
 
{
1253
 
        if (mp->cp && mp->cp != mp->buf)
1254
 
            free (mp->cp);
1255
 
        free (mp);
1256
 
}
1257
 
 
1258
 
/* write the next chunk of the current message in the queue to the given
1259
 
 * client. pop message from queue when complete and free the message if we are
1260
 
 * the last one to use it. shut down this client if trouble.
1261
 
 * N.B. we assume we will never be called with cp->msgq empty.
1262
 
 * return 0 if ok else -1 if had to shut down.
1263
 
 */
1264
 
static int
1265
 
sendClientMsg (ClInfo *cp)
1266
 
{
1267
 
        int nsend, nw;
1268
 
        Msg *mp;
1269
 
 
1270
 
        /* get current message */
1271
 
        mp = (Msg *) peekFQ (cp->msgq);
1272
 
 
1273
 
        /* send next chunk, never more than MAXWSIZ to reduce blocking */
1274
 
        nsend = mp->cl - cp->nsent;
1275
 
        if (nsend > MAXWSIZ)
1276
 
            nsend = MAXWSIZ;
1277
 
        nw = write (cp->s, &mp->cp[cp->nsent], nsend);
1278
 
 
1279
 
        /* shut down if trouble */
1280
 
        if (nw <= 0) {
1281
 
            if (nw == 0)
1282
 
                fprintf (stderr, "%s: Client %d: write returned 0\n",
1283
 
                                                    indi_tstamp(NULL), cp->s);
1284
 
            else
1285
 
                fprintf (stderr, "%s: Client %d: write: %s\n", indi_tstamp(NULL),
1286
 
                                                    cp->s, strerror(errno));
1287
 
            shutdownClient (cp);
1288
 
            return (-1);
1289
 
        }
1290
 
 
1291
 
        /* trace */
1292
 
        if (verbose > 2) {
1293
 
            fprintf(stderr, "%s: Client %d: sending msg copy %d nq %d:\n%.*s\n",
1294
 
                                indi_tstamp(NULL), cp->s, mp->count, nFQ(cp->msgq),
1295
 
                                nw, &mp->cp[cp->nsent]);
1296
 
        } else if (verbose > 1) {
1297
 
            fprintf(stderr, "%s: Client %d: sending %.50s\n", indi_tstamp(NULL),
1298
 
                                                    cp->s, &mp->cp[cp->nsent]);
1299
 
        }
1300
 
 
1301
 
        /* update amount sent. when complete: free message if we are the last
1302
 
         * to use it and pop from our queue.
1303
 
         */
1304
 
        cp->nsent += nw;
1305
 
        if (cp->nsent == mp->cl) {
1306
 
            if (--mp->count == 0)
1307
 
                freeMsg (mp);
1308
 
            popFQ (cp->msgq);
1309
 
            cp->nsent = 0;
1310
 
        }
1311
 
 
1312
 
        return (0);
1313
 
}
1314
 
 
1315
 
/* write the next chunk of the current message in the queue to the given
1316
 
 * driver. pop message from queue when complete and free the message if we are
1317
 
 * the last one to use it. restart this driver if touble.
1318
 
 * N.B. we assume we will never be called with dp->msgq empty.
1319
 
 * return 0 if ok else -1 if had to shut down.
1320
 
 */
1321
 
static int
1322
 
sendDriverMsg (DvrInfo *dp)
1323
 
{
1324
 
        int nsend, nw;
1325
 
        Msg *mp;
1326
 
 
1327
 
        /* get current message */
1328
 
        mp = (Msg *) peekFQ (dp->msgq);
1329
 
 
1330
 
        /* send next chunk, never more than MAXWSIZ to reduce blocking */
1331
 
        nsend = mp->cl - dp->nsent;
1332
 
        if (nsend > MAXWSIZ)
1333
 
            nsend = MAXWSIZ;
1334
 
        nw = write (dp->wfd, &mp->cp[dp->nsent], nsend);
1335
 
 
1336
 
        /* restart if trouble */
1337
 
        if (nw <= 0) {
1338
 
            if (nw == 0)
1339
 
                fprintf (stderr, "%s: Driver %s: write returned 0\n",
1340
 
                                                    indi_tstamp(NULL), dp->name);
1341
 
            else
1342
 
                fprintf (stderr, "%s: Driver %s: write: %s\n", indi_tstamp(NULL),
1343
 
                                                    dp->name, strerror(errno));
1344
 
            restartDvr (dp);
1345
 
            return (-1);
1346
 
        }
1347
 
 
1348
 
        /* trace */
1349
 
        if (verbose > 2) {
1350
 
            fprintf(stderr, "%s: Driver %s: sending msg copy %d nq %d:\n%.*s\n",
1351
 
                            indi_tstamp(NULL), dp->name, mp->count, nFQ(dp->msgq),
1352
 
                            nw, &mp->cp[dp->nsent]);
1353
 
        } else if (verbose > 1) {
1354
 
            fprintf(stderr, "%s: Driver %s: sending %.50s\n", indi_tstamp(NULL),
1355
 
                                                dp->name, &mp->cp[dp->nsent]);
1356
 
        }
1357
 
 
1358
 
        /* update amount sent. when complete: free message if we are the last
1359
 
         * to use it and pop from our queue.
1360
 
         */
1361
 
        dp->nsent += nw;
1362
 
        if (dp->nsent == mp->cl) {
1363
 
            if (--mp->count == 0)
1364
 
                freeMsg (mp);
1365
 
            popFQ (dp->msgq);
1366
 
            dp->nsent = 0;
1367
 
        }
1368
 
 
1369
 
        return (0);
1370
 
}
1371
 
 
1372
 
/* return 0 if cp may be interested in dev/name else -1
1373
 
 */
1374
 
static int
1375
 
findClDevice (ClInfo *cp, const char *dev, const char *name)
1376
 
{
1377
 
        int i;
1378
 
 
1379
 
        if (cp->allprops || !dev[0])
1380
 
            return (0);
1381
 
        for (i = 0; i < cp->nprops; i++) {
1382
 
            Property *pp = &cp->props[i];
1383
 
            if (!strcmp (pp->dev, dev) &&
1384
 
                                    (!pp->name[0] || !strcmp(pp->name, name)))
1385
 
                return (0);
1386
 
        }
1387
 
        return (-1);
1388
 
}
1389
 
 
1390
 
/* add the given device and property to the devs[] list of client if new.
1391
 
 */
1392
 
static void
1393
 
addClDevice (ClInfo *cp, const char *dev, const char *name)
1394
 
{
1395
 
        Property *pp;
1396
 
        char *ip;
1397
 
 
1398
 
        /* no dups */
1399
 
        if (!findClDevice (cp, dev, name))
1400
 
            return;
1401
 
 
1402
 
        /* add */
1403
 
        cp->props = (Property *) realloc (cp->props,
1404
 
                                            (cp->nprops+1)*sizeof(Property));
1405
 
        pp = &cp->props[cp->nprops++];
1406
 
 
1407
 
        ip = pp->dev;
1408
 
        strncpy (ip, dev, MAXINDIDEVICE-1);
1409
 
        ip[MAXINDIDEVICE-1] = '\0';
1410
 
 
1411
 
        ip = pp->name;
1412
 
        strncpy (ip, name, MAXINDINAME-1);
1413
 
        ip[MAXINDINAME-1] = '\0';
1414
 
}
1415
 
 
1416
 
 
1417
 
/* block to accept a new client arriving on lsocket.
1418
 
 * return private nonblocking socket or exit.
1419
 
 */
1420
 
static int
1421
 
newClSocket ()
1422
 
{
1423
 
        struct sockaddr_in cli_socket;
1424
 
        socklen_t cli_len;
1425
 
        int cli_fd;
1426
 
 
1427
 
        /* get a private connection to new client */
1428
 
        cli_len = sizeof(cli_socket);
1429
 
        cli_fd = accept (lsocket, (struct sockaddr *)&cli_socket, &cli_len);
1430
 
        if(cli_fd < 0) {
1431
 
            fprintf (stderr, "accept: %s\n", strerror(errno));
1432
 
            Bye();
1433
 
        }
1434
 
 
1435
 
        /* ok */
1436
 
        return (cli_fd);
1437
 
}
1438
 
 
1439
 
/* convert the string value of enableBLOB to our B_ state value.
1440
 
 * no change if unrecognized
1441
 
 */
1442
 
static void
1443
 
crackBLOB (char *enableBLOB, BLOBHandling *bp)
1444
 
{
1445
 
        if (!strcmp (enableBLOB, "Also"))
1446
 
            *bp = B_ALSO;
1447
 
        else if (!strcmp (enableBLOB, "Only"))
1448
 
            *bp = B_ONLY;
1449
 
        else if (!strcmp (enableBLOB, "Never"))
1450
 
            *bp = B_NEVER;
1451
 
}
1452
 
 
1453
 
/* print key attributes and values of the given xml to stderr.
1454
 
 */
1455
 
static void
1456
 
traceMsg (XMLEle *root)
1457
 
{
1458
 
        static const char *prtags[] = {
1459
 
            "defNumber", "oneNumber",
1460
 
            "defText",   "oneText",
1461
 
            "defSwitch", "oneSwitch",
1462
 
            "defLight",  "oneLight",
1463
 
        };
1464
 
        XMLEle *e;
1465
 
        const char *msg, *perm, *pcd;
1466
 
        unsigned int i;
1467
 
 
1468
 
        /* print tag header */
1469
 
        fprintf (stderr, "%s %s %s %s", tagXMLEle(root),
1470
 
                                                findXMLAttValu(root,"device"),
1471
 
                                                findXMLAttValu(root,"name"),
1472
 
                                                findXMLAttValu(root,"state"));
1473
 
        pcd = pcdataXMLEle (root);
1474
 
        if (pcd[0])
1475
 
            fprintf (stderr, " %s", pcd);
1476
 
        perm = findXMLAttValu(root,"perm");
1477
 
        if (perm[0])
1478
 
            fprintf (stderr, " %s", perm);
1479
 
        msg = findXMLAttValu(root,"message");
1480
 
        if (msg[0])
1481
 
            fprintf (stderr, " '%s'", msg);
1482
 
 
1483
 
        /* print each array value */
1484
 
        for (e = nextXMLEle(root,1); e; e = nextXMLEle(root,0))
1485
 
            for (i = 0; i < sizeof(prtags)/sizeof(prtags[0]); i++)
1486
 
                if (strcmp (prtags[i], tagXMLEle(e)) == 0)
1487
 
                    fprintf (stderr, "\n %10s='%s'", findXMLAttValu(e,"name"),
1488
 
                                                            pcdataXMLEle (e));
1489
 
 
1490
 
        fprintf (stderr, "\n");
1491
 
}
1492
 
 
1493
 
/* fill s with current UT string.
1494
 
 * if no s, use a static buffer
1495
 
 * return s or buffer.
1496
 
 * N.B. if use our buffer, be sure to use before calling again
1497
 
 */
1498
 
static char *
1499
 
indi_tstamp (char *s)
1500
 
{
1501
 
        static char sbuf[64];
1502
 
        struct tm *tp;
1503
 
        time_t t;
1504
 
 
1505
 
        time (&t);
1506
 
        tp = gmtime (&t);
1507
 
        if (!s)
1508
 
            s = sbuf;
1509
 
        strftime (s, sizeof(sbuf), "%Y-%m-%dT%H:%M:%S", tp);
1510
 
        return (s);
1511
 
}
1512
 
 
1513
 
/* log message in root known to be from device dev to ldir, if any.
1514
 
 */
1515
 
static void
1516
 
logDMsg (XMLEle *root, const char *dev)
1517
 
{
1518
 
        char stamp[64];
1519
 
        char logfn[1024];
1520
 
        const char *ts, *ms;
1521
 
        FILE *fp;
1522
 
 
1523
 
        /* get message, if any */
1524
 
        ms = findXMLAttValu (root, "message");
1525
 
        if (!ms[0])
1526
 
            return;
1527
 
 
1528
 
        /* get timestamp now if not provided */
1529
 
        ts = findXMLAttValu (root, "timestamp");
1530
 
        if (!ts[0])
1531
 
        {
1532
 
            indi_tstamp (stamp);
1533
 
            ts = stamp;
1534
 
        }
1535
 
 
1536
 
        /* append to log file, name is date portion of time stamp */
1537
 
        sprintf (logfn, "%s/%.10s.islog", ldir, ts);
1538
 
        fp = fopen (logfn, "a");
1539
 
        if (!fp)
1540
 
            return;     /* oh well */
1541
 
        fprintf (fp, "%s: %s: %s\n", ts, dev, ms);
1542
 
        fclose (fp);
1543
 
}
1544
 
 
1545
 
/* log when then exit */
1546
 
static void
1547
 
Bye()
1548
 
{
1549
 
        fprintf (stderr, "%s: good bye\n", indi_tstamp(NULL));
1550
 
        exit(1);
1551
 
}
1552