File: apcupsd.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 (538 lines) | stat: -rw-r--r-- 15,566 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
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
/*
 *  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.
 *
 */

/*
 *  Parts of the code are from Miquel van Smoorenburg's powerd.c
 *  Other parts are original from Christian Holtje <docwhat@uiuc.edu>
 *  Smart-UPS code from Pavel Korensky's apcd.c, apcd.h, and upsnet.c.
 *  I believe that it is okay to say that this is Public Domain, just
 *  give credit, where credit is due.
 *
 *  9/20/96 2:00am
 *
 */

/*
 * Add here an identifer that is unique for tracking changes
 * made by each person other than myself.
 *
 * Christopher J. Reimer <reimer@doe.carleton.ca>	CJR
 * Werner Panocha <wpanocha@t-online.de>		w.p.
 * Brian Schau <bsc@fleggaard.dk>			BSC
 * Marko Sakari Asplund <Marko.Asplund@cern.ch> 	MSA
 * Riccardo Facchetti <riccardo@master.oasi.gpa.it>			-RF
 * Jonathan H N Chin <jc254@newton.cam.ac.uk>		JHNC
 * Kern Sibbald <kern@sibbald.com>			KES
 */

/* The big overall flow of apcupsd is as follows
 *
 *   Assuming no networking features are turned on.
 *
 * Main Process:
 *   process configuration file
 *   establish contact with the UPS
 *   read the state of the UPS
 *   Fork to become a daemon
 *   write the shared memory
 *   start child process apcser -- subroutine do_serial()
 *   start child process apcnis, if configured -- subroutine do_server()
 *   wait for child processes to complete
 *   exit
 *
 * Child process apcser -- subroutine do_serial()
 *   wait for activity on serial port or timeout 
 *	from select() (5 seconds) -- check_serial()
 *   call do_action()
 *	read and lock the shared memory
 *	check to see if UPS state has changed and if we should take any action. I.e.
 *	      are we on batteries, should we shutdown, ...
 *	write and unlock shared memory
 *   call fillUPS()
 *	read and lock shared memory
 *	Poll the UPS for each state variable
 *	enable the UPS
 *	enable the UPS again
 *	write and unlock shared memory
 *   call do_reports()
 *	if DATA report time expired, write DATA report -- log_data()
 *	if STATUS report time expired, write STATUS report
 *   loop
 *
 * 
 */ 

#include "apc.h"

/*
 * myUPS is a structure that need to be defined in _all_ the forked processes.
 * The syncronization of data into this structure is done with the shared
 * memory area so this is made reentrant by the shm mechanics.
 */
UPSINFO myUPS;
UPSINFO *core_ups = &myUPS;
char argvalue[MAXSTRING];

int le_bit   = TIOCM_LE;
int st_bit   = TIOCM_ST;
int sr_bit   = TIOCM_SR;
int dtr_bit  = TIOCM_DTR;
int rts_bit  = TIOCM_RTS;
int cts_bit  = TIOCM_CTS;
int cd_bit   = TIOCM_CD;
int rng_bit  = TIOCM_RNG;
int dsr_bit  = TIOCM_DSR;

struct termios oldtio;
struct termios newtio;

static int daemon_running = 0;	      /* set after becoming daemon */

static void daemon_start();

int shm_OK = 0;


/**********************************************************************
 * the terminate function and trapping signals allows apcupsd
 * to exit and cleanly close logfiles, and reset the tty back
 * to its original settings. You may want to add this
 * to all configurations.  Of course, the file descriptors
 * must be global for this to work, I also set them to
 * NULL initially to allow terminate to determine whether
 * it should close them.
 *********************************************************************/
void terminate(int sig)
{
    UPSINFO *ups = &myUPS;

    restore_signals();

    if (sig != 0) {
        log_event(ups, LOG_WARNING, _("apcupsd exiting, signal %u\n"), sig);
    }

    clear_files();

    if (ups->fd != -1) {
	/*
	 * If the ups device is opened:
	 * 1 - Close it
	 * 2 - Delete lock file
	 *
	 * -RF
	 */
	/* Note, if the tcsetattr() code is executed,
	 * it can cause the serial port line statuses to be
         * reset, which for a "dumb" UPS is the signal to
	 * kill the power. This caused premature powerkills.
	 */
	if (ups->mode.type > SHAREBASIC) {
		tcflush(ups->fd, TCIFLUSH);
		tcsetattr(ups->fd, TCSANOW, &oldtio);
	}
	close(ups->fd);
    }
    delete_lockfile(ups);

    clean_threads();
    destroy_ipc(ups);
    log_event(ups, LOG_WARNING, _("apcupsd shutdown succeeded"));
    closelog();
    _exit(0);
}

void error_cleanup(UPSINFO *ups)
{
    if (ups->fd != -1) {
	/* See important not in terminate() subroutine! */
	if (ups->mode.type > SHAREBASIC) {
	    tcflush(ups->fd, TCIFLUSH);
	    tcsetattr(ups->fd, TCSANOW, &oldtio);
	}
	close(ups->fd);
    }
    delete_lockfile(ups);
    clean_threads();
    destroy_ipc(ups);
    log_event(ups, LOG_ERR, _("apcupsd error shutdown completed"));
    closelog();
    exit(1);
}

/*********************************************************************
 * subroutine error_out prints FATAL ERROR with file,
 *  line number, and the error message then cleans up 
 *  and exits. It is normally called from the Error_abort
 *  define, which inserts the file and line number.
 */
void error_out(char *file, int line, char *fmt,...)
{
    char      buf[256];
    va_list   arg_ptr;
    int       i;

    sprintf(buf, _("apcupsd FATAL ERROR in %s at line %d\n"), file, line);
    i = strlen(buf);
    va_start(arg_ptr, fmt);
    vsprintf((char *)&buf[i], (char *) fmt, arg_ptr);
    va_end(arg_ptr);
    fprintf(stderr, buf);
    log_event(core_ups, LOG_ERR, buf);
    error_cleanup(core_ups);		/* finish the work */
}

/* subroutine error_exit simply prints the supplied error
 * message, cleans up, and exits
 */
void error_exit(char *fmt,...)
{
    char      buf[256];
    va_list   arg_ptr;

    va_start(arg_ptr, fmt);
    vsprintf(buf, (char *) fmt, arg_ptr);
    va_end(arg_ptr);
    fprintf(stderr, buf);
    log_event(core_ups, LOG_ERR, buf);
    error_cleanup(core_ups);		/* finish the work */
}


/*********************************************************************/
/*		       Main program.				     */
/*********************************************************************/

int main(int argc, char *argv[]) {
#ifndef HAVE_PTHREADS
    int serial_pid = 0;
#endif
    UPSINFO  *ups = &myUPS;

    /*
     * Default config file. If we set a config file in startup switches, it
     * will be re-filled by parse_options()
     */
    cfgfile = APCCONF;

    /*
     * If NLS is compiled in, enable NLS messages translation.
     */
    textdomain("apcupsd");

    /* If there's not one in libc, then we have to use our own version
     * which requires initialization.
     */
    init_proctitle(argv[0]);
    strncpy(argvalue, argv[0], sizeof(argvalue)-1);
    argvalue[sizeof(argvalue)-1] = 0;
    init_ups_struct(ups);

    /*
     * parse_options is self messaging on errors, so we need only to exit()
     */
    if (parse_options(argc, argv))
	exit(1);

    if (show_version == TRUE) {
        printf("apcupsd " APCUPSD_RELEASE " (" DATE ") " APCUPSD_HOST"\n");
	exit(0);
    }

    /* We open the log file early to be able to write to it
     * it at any time. However, please note that if the user
     * specifies a different facility in the config file
     * the log will be closed and reopened (see match_facility())
     * in apcconfig.c.	Any changes here should also be made
     * to the code in match_facility().
     */
    openlog("apcupsd", LOG_CONS|LOG_PID, ups->sysfac);   

    if ((getuid() != 0) && (geteuid() != 0))
        Error_abort0(_("Needs super user privileges to run.\n"));

    check_for_config(ups, cfgfile);
    insertUps(ups);
    ups->start_time = time(NULL);
    delete_lockfile(ups);

    if (update_battery_date == TRUE) {
	if (ups->mode.type < BKPRO)
            Error_abort1(_("Cannot update battery date %s\n"),
			   ups->mode.long_name);
        printf(_("Attempting to update UPS battery date ...\n"));
	setup_serial(ups);
	get_UPS_capabilities(ups);
	if (ups->UPS_Cap[CI_BATTDAT])
	    setup_ups_replace(ups);
	exit(0);
    }

    if (configure_ups == TRUE) {
	if (ups->mode.type < BKPRO)
            Error_abort0(_("This model cannot be configured.\n"));
        printf(_("Attempting to configure UPS ...\n"));
	setup_serial(ups);
	setup_extended(ups);	 /* set new values in UPS */
        printf("\nReading updated UPS configuration ...\n\n");
	ReadUPS(ups);
	/* Print report of status */
	output_status(ups, 0, stat_open, stat_print, stat_close);
	exit(0);
    }

    if (rename_ups == TRUE) {
	if (ups->mode.type < NBKPRO)
            Error_abort1(_("Can not rename %s\n"),  ups->mode.long_name);
        printf(_("Attempting to rename UPS ...\n"));
	setup_serial(ups);
	get_UPS_capabilities(ups);
	if (ups->UPS_Cap[CI_IDEN])
	    setup_ups_name(ups);
	exit(0);
    }



    /* Create temp events file */
    if (ups->eventfile[0] != 0) {
	ups->event_fd = open(ups->eventfile, O_WRONLY|O_CREAT|O_APPEND, 0644);
	if (ups->event_fd < 0) {
            log_event(ups, LOG_WARNING, "Could not open events file %s: %s\n",
		      ups->eventfile, strerror(errno));
	}
    }


    switch(ups->sharenet.type) {
    case DISABLE:
    case SHARE:
	setup_serial(ups);
	break;
    case NET:
	switch(ups->class.type) {
	case NO_CLASS:
	case STANDALONE:
	case SHARESLAVE:
	case SHAREMASTER:
	case SHARENETMASTER:
	    break;
	case NETSLAVE:
	    if (kill_ups_power)
                Error_abort0(_("Ignoring killpower for slave\n"));
	    if (prepare_slave(ups)) 
                Error_abort0(_("Error setting up slave\n"));
	    break;
	case NETMASTER:
	    setup_serial(ups);
	    if ((kill_ups_power == 0) && (prepare_master(ups)))
                Error_abort0("Error setting up master\n");
	    break;
	default:
            Error_abort1(_("NET Class Error %s\n\a"), strerror(errno));
	}
	break;
    case SHARENET:
	setup_serial(ups);
	if ((kill_ups_power == 0) && (prepare_master(ups)))
            Error_abort0("Error setting up master.\n");
	break;
    default:
        Error_abort0(_("Unknown share net type\n"));
    }

    if (kill_ups_power) {
	if (ups->fd != -1)
	    kill_power(ups);
	else
	    kill_net(ups);
	terminate(0);
    }

    if (init_ipc(ups) == FAILURE) {
        Error_abort1(_("%s: init_ipc failed.\n"), argv[0]);
    }

    /*
     * Delete the lockfile just before fork. We will reacquire it just
     * after.
     */

    delete_lockfile(ups);

    daemon_start();

    daemon_running = 1;

    setproctitle("apcmain");

    make_pid_file();

    if (create_lockfile(ups) == LCKERROR) {
        Error_abort1(_("failed to reacquire serial port lock file on device %s\n"), ups->device);
    }

    init_signals(terminate);

    if (ups->fd != -1) {
	prep_serial(ups);
        /* This isn't a documented option but can be used
	 * for testing dumb mode on a SmartUPS if you have
	 * the proper cable.
	 */
	if (dumb_mode_test) {
	    char ans[20];
            write(ups->fd, "R", 1);  /* enter dumb mode */
	    *ans = 0;
	    getline(ans, sizeof(ans), ups);
            printf("Going dumb: %s\n", ans);
	}
    }



    /*
     * Now update the shared area with ups data.
     */
    write_shmarea(ups);
    shm_OK = 1;

    /*
     * From now ... we must _only_ start up threads!
     * No more unchecked writes to myUPS because the threads must rely
     * on write locks and up to date data in the shared structure.
     */


    if (slave_count) {
	/* we are the netmaster */
        start_thread(ups, do_slaves, "apcmst", argv[0]);
    }

    /* Network status information server */
    if (ups->netstats) {
        start_thread(ups, do_server, "apcnis", argv[0]);
    }
   
#ifdef HAVE_PTHREADS
    log_event(ups, LOG_WARNING, "apcupsd " APCUPSD_RELEASE " (" DATE ") " APCUPSD_HOST " startup succeeded");
    /* If we have threads, we simply go there rather
     * than creating a thread.
     */
    if (ups->fd != -1) {
	/* serial port reading and report generation -- apcserial.c */
	do_serial(ups);
    } else {
        /* we are a slave -- thus the net is our "serial port" */
	do_net(ups);
    }
#else
    if (ups->fd != -1) {
	/* serial port reading and report generation -- apcserial.c */
        serial_pid = start_thread(ups, do_serial, "apcser", argv[0]); 
    } else {
        /* we are a slave -- thus the net is our "serial port" */
        serial_pid = start_thread(ups, do_net, "apcslv", argv[0]);
    }

    log_event(ups, LOG_WARNING, "apcupsd " APCUPSD_RELEASE " (" DATE ") " APCUPSD_HOST " startup succeeded");
    wait_for_termination(serial_pid);  /* wait for child processes to terminate */
#endif

    terminate(0);
    return -1;			  /* to keep compiler happy */
}

/*
 * Initialize a daemon process completely detaching us from
 * any terminal processes.
 */
static void daemon_start()
{
#ifndef HAVE_CYGWIN
    pid_t cpid;
    mode_t oldmask;

    if ( (cpid = fork() ) < 0)
            Error_abort0("Cannot fork to become daemon\n");
    else if (cpid > 0)
	    exit(0);		  /* parent exits */

    /* Child continues */
    setsid();			  /* become session leader */

    /* Should close open file descriptors here, but since  
       we have a lot of them open including the serial
       port, we close only the standard descriptors */
#ifndef DEBUG
    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);
#endif

    /* move to root directory */
    chdir("/");
   
    /* 
     * Avoid creating files 0666 but don't override a
     * more restrictive umask set by the caller.
     */
    oldmask = umask(022);
    oldmask |= 022;
    umask(oldmask);

#endif /* HAVE_CYGWIN */
}