File: apcnisd.c

package info (click to toggle)
apcupsd 3.8.5-1.1.1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 7,012 kB
  • ctags: 2,783
  • sloc: ansic: 26,374; sh: 3,012; makefile: 1,860; cpp: 1,713; perl: 191; sed: 93
file content (372 lines) | stat: -rw-r--r-- 10,155 bytes parent folder | download
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
/*
 *  apcnisd.c	 -- Network Information Server daemon for apcupsd
 *
 *  Copyright (C) 1999 Kern Sibbald
 *     10 November 1999
 *
 *  apcupsd.c -- Simple Daemon to catch power failure signals from a
 *		 BackUPS, BackUPS Pro, or SmartUPS (from APCC).
 *	      -- Now SmartMode support for SmartUPS and BackUPS Pro.
 *
 *  Copyright (C) 1996-99 Andre M. Hedrick <andre@suse.com>
 *  All rights reserved.
 *
 */

/*
 *
 *		       GNU GENERAL PUBLIC LICENSE
 *			  Version 2, June 1991
 *
 *  Copyright (C) 1989, 1991 Free Software Foundation, Inc.
 *			     675 Mass Ave, Cambridge, MA 02139, USA
 *  Everyone is permitted to copy and distribute verbatim copies
 *  of this license document, but changing it is not allowed.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

/*
 *  IN NO EVENT SHALL ANY AND ALL PERSONS INVOLVED IN THE DEVELOPMENT OF THIS
 *  PACKAGE, NOW REFERRED TO AS "APCUPSD-Team" BE LIABLE TO ANY PARTY FOR 
 *  DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
 *  OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF ANY OR ALL
 *  OF THE "APCUPSD-Team" HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *  THE "APCUPSD-Team" SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
 *  BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 *  FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
 *  ON AN "AS IS" BASIS, AND THE "APCUPSD-Team" HAS NO OBLIGATION TO PROVIDE
 *  MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
 *
 *  THE "APCUPSD-Team" HAS ABSOLUTELY NO CONNECTION WITH THE COMPANY
 *  AMERICAN POWER CONVERSION, "APCC".  THE "APCUPSD-Team" DID NOT AND
 *  HAS NOT SIGNED ANY NON-DISCLOSURE AGREEMENTS WITH "APCC".  ANY AND ALL
 *  OF THE LOOK-A-LIKE ( UPSlink(tm) Language ) WAS DERIVED FROM THE
 *  SOURCES LISTED BELOW.
 *
 */


#include "apc.h"
#include "apc_nis.h"
#include <syslog.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define NETD_VERSION "1.0"

char *pname;

UPSINFO myUPS;
static char largebuf[4096];
static int  stat_recs;
static int  logstats = 0;

/* forward referenced subroutines */
void handle_client_request();
int do_daemon(int argc, char *argv[]); 
int do_inetd(int argc, char *argv[]);

void error_cleanup(UPSINFO *ups)
{
    destroy_ipc(ups);
    closelog();
    exit(1);
}


/*
 * This routine is called by the main process to
 * track its children. On CYGWIN, the child processes
 * don't always exit when the other end of the socket
 * hangs up. Thus they remain hung on a read(). After
 * 30 seconds, we send them a SIGTERM signal, which 
 * causes them to wake up to the reality of the situation.
 */
static void reap_children(int childpid)
{
   static int pids[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
   static int times[10];
   int i;
   time_t now;


   time(&now);
   for (i=0; i<10; i++) {
      if (pids[i] && (waitpid(pids[i], NULL, WNOHANG) == pids[i]))
	 pids[i] = 0;
      else if (pids[i] && ((now - times[i]) > 30))
	 kill(pids[i], SIGTERM);
   }
   for (i=0; i<10; i++) {
      if (pids[i] && (waitpid(pids[i], NULL, WNOHANG) == pids[i]))
	 pids[i] = 0;
      if (childpid && (pids[i] == 0)) {
	 pids[i] = childpid;
	 times[i] = now;
	 childpid = 0;
      }
   }
}


static void status_open(UPSINFO *ups)
{
   largebuf[0] = 0;
   stat_recs = 0;
   logstats = ups->logstats;
}

#define STAT_REV 1

static int status_close(UPSINFO *ups, int nsockfd)
{
    int i;   
    char buf[MAXSTRING];
    char *sptr, *eptr;

    i = strlen(largebuf);
    if (i > sizeof(largebuf)-1) 
        Error_abort1("Status buffer overflow %d bytes\n", i-sizeof(largebuf));
    sprintf(buf, "APC      : %03d,%03d,%04d\n", STAT_REV, stat_recs, i);
    
    if (net_send(nsockfd, buf, strlen(buf)) <= 0)
	return -1;
    sptr = eptr = largebuf;
    for ( ; i > 0; i--) {
        if (*eptr == '\n') {
	   eptr++;
	   if (net_send(nsockfd, sptr, eptr - sptr) <= 0)
	       break;
	   sptr = eptr;
	} else 
	   eptr++;
    }
    if (net_send(nsockfd, NULL, 0) < 0)
	return -1;
    return 0;
}



/********************************************************************* 
 * log one line of the status file
 * also send it to system log
 *
 */
static void status_write(UPSINFO *ups, char *fmt, ...)
{
    va_list ap;
    char buf[MAXSTRING];

    va_start(ap, fmt);

    vsprintf(buf, fmt, ap);
    va_end(ap);

    strcat(largebuf, buf);
    stat_recs++;
}


/* 
 * We begin execution here. If the first and only
 * argument given on the command line is a -i, then
 * we assume that we were called by inetd.  
 *
 */
int main(int argc, char *argv[])
{
    if (argc == 1) {
	do_daemon(argc, argv);
    } else if ((argc == 2) && (strcmp(argv[1], "-i") == 0)) {
	do_inetd(argc, argv);
    } else
        error_exit("Usage: %s \n", argv[0]);
    return 0;
}

/* Called here if started by any means other than by
 * inetd
 */
int do_daemon(int argc, char *argv[]) 
{
    int newsockfd, sockfd, clilen, childpid;
    struct sockaddr_in cli_addr;       /* client's address */
    struct sockaddr_in serv_addr;      /* our address */
    int turnon = 1;

    pname = argv[0];

    openlog("apcnetd", LOG_CONS|LOG_PID, LOG_DAEMON);

#ifndef HAVE_CYGWIN
    if ((childpid = fork()) < 0)
        Error_abort1("Cannot fork to become daemon. ERR=%s", strerror(errno));
    else if (childpid > 0)
	exit(0);			/* original parent */
#endif

    /* we are now a daemon */
    setsid();
    signal(SIGCHLD, SIG_IGN);	       /* prevent zombies */

    syslog(LOG_INFO, "apcnetd %s startup succeeded", NETD_VERSION);

    /*
     * Open a TCP socket  
     */
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
       Error_abort1("server: cannot open stream socket. ERR=%s", strerror(errno));

    /*
     * Reuse old sockets, ignore errors
     */
    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &turnon, sizeof(turnon));  

    /* 
     * Bind our local address so that the client can send to us.
     */
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(NISPORT);

    if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
       Error_abort1("server: cannot bind local address. ERR=%s", strerror(errno));

    listen(sockfd, 5);		       /* tell system we are ready */
    for (;;) {
	/* 
	 * Wait for a connection from a client process.
	 */
	 clilen = sizeof(cli_addr);
	 newsockfd = accept(sockfd, (struct sockaddr *)&cli_addr, &clilen);
	 if (newsockfd < 0) {
             Error_abort1("server: accept error. ERR=%s\n", strerror(errno));
	 }

#ifdef HAVE_LIBWRAP
       /*
        * This function checks the incoming client and if it's not
	* allowed closes the connection.
	*/
       if (check_wrappers(argvalue, newsockfd) == FAILURE) {
	   shutdown(newsockfd, 2);
	   close(newsockfd);
	   continue;
       }
#endif

#ifdef HAVE_CYGWIN
	childpid = 0;
	handle_client_request(newsockfd);	 /* process the request */
#else 
	/* fork to provide the response */
	if ((childpid = fork()) < 0)
            Error_abort1("server: fork error. ERR=%s\n", strerror(errno));
	else if (childpid == 0) {      /* child process */
	    close(sockfd);		/* close original socket */
	    handle_client_request(newsockfd);	     /* process the request */
	    close(newsockfd);
	    exit(0);
	}
#endif

	close(newsockfd);	       /* parent process */
        /* Reap any "previous" children that were not properly
	 * reaped by the SIG_IGN */
	reap_children(childpid);
     }
}   

/* Called here if started by inetd */
int do_inetd(int argc, char *argv[]) 
{
    /* read from "stdin" -- socket is already open */
    handle_client_request(0);	      /* process the request */
    exit(0);
}   


/* 
 * Accept requests from client.
 *
 * Return when the connection is terminated.
 */

void handle_client_request(int nsockfd)
{
    FILE *events_file;
    char line[MAXSTRING];
    char errmsg[]   = "Invalid command\n";
    char notavail[] = "Not available\n";
    char notrun[]   = "Apcupsd not running\n";
    UPSINFO *ups = &myUPS;


    if (attach_ipc(ups, SHM_RDONLY) != SUCCESS) {
	net_send(nsockfd, notrun, sizeof(notrun));
	net_send(nsockfd, NULL, 0);
        Error_abort0("Cannot attach SYSV IPC.\n");
    }

    for (;;) {
	/* Read command */
       if ((net_recv(nsockfd, line, MAXSTRING)) <= 0) {
	   break;			/* connection terminated */
       }

       if (read_shmarea(ups, 0) != SUCCESS) {
	   net_send(nsockfd, notavail, sizeof(notavail));
	   net_send(nsockfd, NULL, 0);
           syslog(LOG_ERR, "Cannot read shm data area.\n");
	   break;
       }

       if (strncmp("status", line, 6) == 0) {
	   if (output_status(ups, nsockfd, status_open, status_write, status_close) < 0) {
	       break;
	   }

       } else if (strncmp("events", line, 6) == 0) {
	   if ((ups->eventfile[0] == 0)  ||
               (events_file = fopen(ups->eventfile, "r")) == NULL) {
	       net_send(nsockfd, notavail, sizeof(notavail));
	       if (net_send(nsockfd, NULL, 0) < 0)
		   break;
	   } else {
	       int stat = output_events(nsockfd, events_file);
	       fclose(events_file);
	       if (stat < 0) {
		   net_send(nsockfd, notavail, sizeof(notavail));
		   net_send(nsockfd, NULL, 0);
		   break;
	      }
	   }

       } else {
	   net_send(nsockfd, errmsg, sizeof(errmsg));
	   if (net_send(nsockfd, NULL, 0) < 0)
	       break;
       }
    }
    detach_ipc(ups);
    return;
}