File: apcnis.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 (436 lines) | stat: -rw-r--r-- 11,597 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
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
/*
 *  apcserver.c  -- Network server for apcupsd
 *
 *   Kern Sibbald 14 November 1999
 *
 *		       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>
#ifdef HAVE_LIBWRAP
#include <tcpd.h>
#endif

#ifdef HAVE_PTHREADS
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
#else
#define P(x)
#define V(x)
#endif
static char largebuf[4096];
static int stat_recs;

struct s_arg {
   UPSINFO *ups;
   int newsockfd;
};

#ifdef HAVE_LIBWRAP
int allow_severity = LOG_INFO;
int deny_severity = LOG_WARNING;

int check_wrappers(char *av, int newsock)
{
    struct request_info req;
    char *av0;

    if (strchr(av, '/'))
        av0 = strrchr(av, '/');
    else
	av0 = av;

    request_init(&req, RQ_DAEMON, av0, RQ_FILE, newsock, NULL);
    fromhost(&req);
    if (!hosts_access(&req)) {
	log_event(core_ups, LOG_WARNING,
            _("Connection from %.500s refused by tcp_wrappers."),
	    eval_client(&req));
	return FAILURE;
    }
#ifdef I_WANT_LOTS_OF_LOGGING
    log_event(core_ups, LOG_NOTICE, "connect from %.500s", eval_client(&req));
#endif
    return SUCCESS;
}

#endif /* HAVE_LIBWRAP */


/* forward referenced subroutines */
void *handle_client_request(void *arg);

/*
 * 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.
 */
#ifndef HAVE_PTHREADS
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;
	}
    }
}
#endif /* HAVE_PTHREADS */

static void status_open(UPSINFO *ups)
{
    P(mutex);
    largebuf[0] = 0;
    stat_recs = 0;
}

#define STAT_REV 1

/*
 * Send the status lines across the network one line
 * at a time (to prevent sending too large a buffer).
 *
 * Returns -1 on error or EOF
 *	    0 OK
 */
static int status_close(UPSINFO *ups, int nsockfd) 
{
    int i;
    char buf[MAXSTRING];
    char *sptr, *eptr;

    i = strlen(largebuf);
    sprintf(buf, "APC      : %03d,%03d,%04d\n", STAT_REV, stat_recs, i);
    
    if (net_send(nsockfd, buf, strlen(buf)) <= 0) {
	V(mutex);
	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) {
	V(mutex);
	return -1;
    }
    V(mutex);
    return 0;
}



/********************************************************************* 
 * 
 * Buffer up the status messages so that they can be sent
 * by the status_close() routine over the network.
 */
static void status_write(UPSINFO *ups, char *fmt, ...)
{
    va_list ap;
    int i;
    char buf[MAXSTRING];

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

    if ((i=(strlen(largebuf) + strlen(buf))) < (sizeof(largebuf)-1)) {
	strcat(largebuf, buf);
	stat_recs++;
    } else
	log_event(ups, LOG_ERR,
          "apcserver.c: Status buffer overflow %d bytes\n", i-sizeof(largebuf));
}


void do_server(UPSINFO *ups)
{
   int newsockfd, sockfd, clilen, childpid;
   struct sockaddr_in cli_addr;       /* client's address */
   struct sockaddr_in serv_addr;      /* our address */
   int tlog;
   int turnon = 1;
   struct s_arg *arg;

   init_thread_signals();

   for (tlog=0; attach_ipc(ups, SHM_RDONLY) != SUCCESS; tlog -= 5*60 ) {
      if (tlog <= 0) {
	 tlog = 60*60; 
         log_event(ups, LOG_ERR, "apcserver: Cannot attach SYSV IPC.\n");
      }
      sleep(5*60);
   }

   for (tlog=0; read_shmarea(ups, 0) != SUCCESS; tlog -= 5*60 ) {
      if (tlog <= 0) {
	 tlog = 60*60; 
         log_event(ups, LOG_ERR, "apcserver: Cannot read shm data area.\n");
      }
      sleep(5*60);
   }

   /*
    * Open a TCP socket  
    */
   for (tlog=0; (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0; tlog -= 5*60 ) {
      if (tlog <= 0) {
	 tlog = 60*60; 
         log_event(ups, LOG_ERR,  "apcserver: cannot open stream socket");
      }
      sleep(5*60);
   }

   /*
    * Reuse old sockets 
    */
   if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &turnon, sizeof(turnon)) < 0) {
      log_event(ups, LOG_WARNING, "Cannot set SO_REUSEADDR on socket: %s\n" , strerror(errno));
   }
   /* 
    * Bind our local address so that the client can send to us.
    */
   memset((char *)&serv_addr, 0, sizeof(serv_addr));
   serv_addr.sin_family = AF_INET;
   serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
   serv_addr.sin_port = htons(ups->statusport);

   for (tlog=0; bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0; tlog -= 5*60 ) {
      if (tlog <= 0) {
	 tlog = 60*60; 
         log_event(ups, LOG_ERR, "apcserver: cannot bind port %d. ERR=%s",
	    ups->statusport, strerror(errno));
      }
      sleep(5*60);
   }
   listen(sockfd, 5);		      /* tell system we are ready */

   log_event(ups, LOG_INFO, "NIS server startup succeeded");

   for (;;) {
      /* 
       * Wait for a connection from a client process.
       */
       clilen = sizeof(cli_addr);
       for (tlog=0; (newsockfd = accept(sockfd, (struct sockaddr *)&cli_addr, &clilen)) < 0; tlog -= 5*60 ) {
	  if (tlog <= 0) {
	     tlog = 60*60; 
             log_event(ups, LOG_ERR,  "apcserver: accept error. ERR=%s",
		strerror(errno));
	  }
	  sleep(5*60);
       }

#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

       arg = malloc(sizeof(struct s_arg));
       arg->newsockfd = newsockfd;
       arg->ups = ups;
       childpid = 0;

#ifdef HAVE_CYGWIN
       handle_client_request(arg);
       close(newsockfd);	      /* parent process */
#else

#ifdef HAVE_PTHREADS
       {
	  pthread_t tid;
	  pthread_create(&tid, NULL, handle_client_request, arg);
       }

#else 

       /* fork to provide the response */
       for (tlog=0; (childpid = fork()) < 0; tlog -= 5*60 ) {
	  if (tlog <= 0) {
	     tlog = 60*60; 
             log_event(ups, LOG_ERR, "apcserver: fork error. ERR=%s",
		strerror(errno));
	  }
	  sleep(5*60);
       } 
       if (childpid == 0) {	      /* child process */
	  close(sockfd);	      /* close original socket */
	  handle_client_request(arg); /* process the request */
	  shutdown(newsockfd, 2);
	  close(newsockfd);
	  exit(0);
       }
       close(newsockfd);	      /* parent process */
       reap_children(childpid);
#endif /* HAVE_PTHREADS */

#endif /* HAVE_CYGWIN */

    }
}   

/* 
 * Accept requests from client.  Send output one line
 * at a time followed by a zero length transmission.
 *
 * Return when the connection is terminated or there
 * is an error.
 */

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

#ifdef HAVE_PTHREADS
    pthread_detach(pthread_self());
#endif
    if (attach_ipc(ups, SHM_RDONLY) != SUCCESS) {
	net_send(nsockfd, notrun, sizeof(notrun));
	net_send(nsockfd, NULL, 0);
	free(arg);
        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);
            log_event(ups, LOG_ERR, "apcserver: 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 if (strncmp("rawupsinfo", line, 10) == 0) {
	    net_send(nsockfd, (char *)ups, sizeof(UPSINFO));
	    if (net_send(nsockfd, NULL, 0) < 0) {
		break;
	    }
	
	} else {
	    net_send(nsockfd, errmsg, sizeof(errmsg));
	    if (net_send(nsockfd, NULL, 0) < 0) {
		break;
	    }
	}
    }
    detach_ipc(ups);
#ifdef HAVE_PTHREADS
    shutdown(nsockfd, 2);
    close(nsockfd);
#endif
    free(arg);
    return NULL;
}