summaryrefslogtreecommitdiffstats
path: root/lib/plugins/stonith/apcsmart.c
blob: 18d161249d7bcd4ceb90eaee200ac287f2655cab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
/*
 * Stonith module for APCSmart Stonith device
 * Copyright (c) 2000 Andreas Piesk <a.piesk@gmx.net>
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.*
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Original version of this UPS code was taken from:
 *   'Network UPS Tools' by Russell Kroll <rkroll@exploits.org>
 *   homepage: http://www.networkupstools.org/
 *
 *  Significantly mangled by Alan Robertson <alanr@unix.sh>
 */

#include <lha_internal.h>

#define	DEVICE	                "APCSmart"

#include "stonith_plugin_common.h"

/*
 * APCSmart (tested with old 900XLI, APC SmartUPS 700 and SmartUPS-1000)
 *
 * The reset is a combined reset: "S" and "@000"
 * The "S" command tells the ups that if it is on-battery, it should
 * remain offline until the power is back. 
 * If that command is not accepted, the "@000" command will be sent
 * to tell the ups to turn off and back on right away.
 * In both cases, if the UPS supports a 20 second shutdown grace
 * period (such as on the 900XLI), the shutdown will delay that long,
 * otherwise the shutdown will happen immediately (the code searches
 * for the smallest possible delay).
 */

#define CFG_FILE		"/etc/ha.d/apcsmart.cfg"

#define MAX_DEVICES		1

#define SERIAL_TIMEOUT		3	/* timeout in sec */
#define SEND_DELAY		50000	/* in microseconds */
#define ENDCHAR			10	/* use LF */
#define MAX_STRING              512
#define MAX_DELAY_STRING        16
#define SWITCH_TO_NEXT_VAL	"-"	/* APC cmd for cycling through
					 * the values
					 */

#define CMD_SMART_MODE          "Y"
#define RSP_SMART_MODE		"SM"
#define CMD_GET_STATUS		"Q"
#define RSP_GET_STATUS		NULL
#define CMD_RESET               "S"	/* turn off & stay off if on battery */
#define CMD_RESET2              "@000"	/* turn off & immediately turn on */
#define RSP_RESET		"*"	/* RESET response from older models */
#define RSP_RESET2		"OK"	/* RESET response from newer models */
#define	RSP_NA			"NA"
#define	CMD_READREG1		"~"
#define CMD_OFF			"Z"
#define CMD_ON			"\016" /* (control-n) */
#define CMD_SHUTDOWN_DELAY	"p"
#define CMD_WAKEUP_DELAY	"r"

#define CR			13

struct pluginDevice {
	StonithPlugin	sp;
	const char *	pluginid; /* of object				*/
	const char *	idinfo;   /* type of device			*/
	char **		hostlist; /* served by the device (only 1)	*/
	int		hostcount;/* of hosts (1)			*/
	char *		upsdev;   /*					*/
	int		upsfd;    /* for serial port			*/
	int		retries;
	char		shutdown_delay[MAX_DELAY_STRING];
	char		old_shutdown_delay[MAX_DELAY_STRING];
	char		wakeup_delay[MAX_DELAY_STRING];
	char		old_wakeup_delay[MAX_DELAY_STRING];
};

/* saving old settings */
/* FIXME!  These should be part of pluginDevice struct above */
static struct termios old_tio;

static int f_serialtimeout;	/* flag for timeout */
static const char *pluginid = "APCSmart-Stonith";
static const char *NOTpluginID = "APCSmart device has been destroyed";

/*
 * stonith prototypes 
 */

#define PIL_PLUGIN              apcsmart
#define PIL_PLUGIN_S            "apcsmart"
#define PIL_PLUGINLICENSE 	LICENSE_LGPL
#define PIL_PLUGINLICENSEURL 	URL_LGPL
#include <pils/plugin.h>

#include "stonith_signal.h"

static StonithPlugin *	apcsmart_new(const char *);
static void		apcsmart_destroy(StonithPlugin *);
static const char * const *	apcsmart_get_confignames(StonithPlugin*);
static int		apcsmart_set_config(StonithPlugin *, StonithNVpair*);
static const char *	apcsmart_get_info(StonithPlugin * s, int InfoType);
static int		apcsmart_status(StonithPlugin * );
static int		apcsmart_reset_req(StonithPlugin * s, int request, const char * host);
static char **		apcsmart_hostlist(StonithPlugin  *);

static struct stonith_ops apcsmartOps ={
	apcsmart_new,		  /* Create new STONITH object		*/
	apcsmart_destroy,	  /* Destroy STONITH object		*/
	apcsmart_get_info,	  /* Return STONITH info string		*/
	apcsmart_get_confignames, /* Return STONITH info string		*/
	apcsmart_set_config,	  /* Get configuration from NVpairs	*/
	apcsmart_status,	  /* Return STONITH device status	*/
	apcsmart_reset_req,	  /* Request a reset 			*/
	apcsmart_hostlist,	  /* Return list of supported hosts	*/
};

PIL_PLUGIN_BOILERPLATE2("1.0", Debug)
static const PILPluginImports*  PluginImports;
static PILPlugin*               OurPlugin;
static PILInterface*		OurInterface;
static StonithImports*		OurImports;
static void*			interfprivate;

PIL_rc
PIL_PLUGIN_INIT(PILPlugin*us, const PILPluginImports* imports);

PIL_rc
PIL_PLUGIN_INIT(PILPlugin*us, const PILPluginImports* imports)
{
	/* Force the compiler to do a little type checking */
	(void)(PILPluginInitFun)PIL_PLUGIN_INIT;

	PluginImports = imports;
	OurPlugin = us;

	/* Register ourself as a plugin */
	imports->register_plugin(us, &OurPIExports);  

	/*  Register our interface implementation */
 	return imports->register_interface(us, PIL_PLUGINTYPE_S
	,	PIL_PLUGIN_S
	,	&apcsmartOps
	,	NULL		/*close */
	,	&OurInterface
	,	(void*)&OurImports
	,	&interfprivate); 
}

#include "stonith_config_xml.h"

static const char *apcsmartXML = 
  XML_PARAMETERS_BEGIN
    XML_TTYDEV_PARM
    XML_HOSTLIST_PARM
  XML_PARAMETERS_END;

/*
 * own prototypes 
 */

int APC_open_serialport(const char *port, speed_t speed);
void APC_close_serialport(const char *port, int upsfd);
void APC_sh_serial_timeout(int sig);
int APC_send_cmd(int upsfd, const char *cmd);
int APC_recv_rsp(int upsfd, char *rsp);
int APC_enter_smartmode(int upsfd);
int APC_set_ups_var(int upsfd, const char *cmd, char *newval);
int APC_get_smallest_delay(int upsfd, const char *cmd, char *smdelay);
int APC_init( struct pluginDevice *ad );
void APC_deinit( struct pluginDevice *ad );

/*
 * Signal handler for serial port timeouts 
 */

void
APC_sh_serial_timeout(int sig)
{
	if (Debug) {
		LOG(PIL_DEBUG, "%s: called.", __FUNCTION__);
	}

	STONITH_IGNORE_SIG(SIGALRM);

	if (Debug) {
		LOG(PIL_DEBUG, "%s: serial port timed out.", __FUNCTION__);
	}

	f_serialtimeout = TRUE;

    return;
}

/*
 * Open serial port and set it to b2400 
 */

int
APC_open_serialport(const char *port, speed_t speed)
{
	struct termios tio;
	int fd;
	int rc;
	int errno_save;
	int fflags;

	if (Debug) {
		LOG(PIL_DEBUG, "%s: called.", __FUNCTION__);
	}

	if ((rc = OurImports->TtyLock(port)) < 0) {
		LOG(PIL_CRIT, "%s: Could not lock tty %s [rc=%d]."
		,	__FUNCTION__, port, rc);
		return -1;
	}

	STONITH_SIGNAL(SIGALRM, APC_sh_serial_timeout);
	alarm(SERIAL_TIMEOUT);
	f_serialtimeout = FALSE;

	fd = open(port, O_RDWR | O_NOCTTY | O_NONBLOCK | O_EXCL);
	errno_save = errno;

	alarm(0);
	STONITH_IGNORE_SIG(SIGALRM);

	if (fd < 0) {
		LOG(PIL_CRIT, "%s: Open of %s %s [%s].", __FUNCTION__
		,	port
		,	f_serialtimeout ? "timed out" : "failed"
		,	strerror(errno_save));
		OurImports->TtyUnlock(port);
		return -1;
	}

	if ((fflags = fcntl(fd, F_GETFL)) < 0
	||	fcntl(fd, F_SETFL, (fflags & ~O_NONBLOCK)) < 0) {
		LOG(PIL_CRIT, "%s: Setting flags on %s failed [%s]."
		,	__FUNCTION__
		,	port
		,	strerror(errno_save));
		close(fd);
		OurImports->TtyUnlock(port);
		return -1;
	}

	if (tcgetattr(fd, &old_tio) < 0) {
		LOG(PIL_CRIT, "%s: tcgetattr of %s failed [%s].", __FUNCTION__
		,	port
		,	strerror(errno));
		close(fd);
		OurImports->TtyUnlock(port);
		return -1;
	}

	memcpy(&tio, &old_tio, sizeof(struct termios));
	tio.c_cflag = CS8 | CLOCAL | CREAD;
	tio.c_iflag = IGNPAR;
	tio.c_oflag = 0;
	tio.c_lflag = 0;
	tio.c_cc[VMIN] = 1;
	tio.c_cc[VTIME] = 0;

	cfsetispeed(&tio, speed);
	cfsetospeed(&tio, speed);

	tcflush(fd, TCIOFLUSH);
	tcsetattr(fd, TCSANOW, &tio);

	return (fd);
}

/*
 * Close serial port and restore old settings 
 */

void
APC_close_serialport(const char *port, int upsfd)
{

	if (Debug) {
		LOG(PIL_DEBUG, "%s: called.", __FUNCTION__);
	}
	if (upsfd < 0) {
		return;
	}

	tcflush(upsfd, TCIFLUSH);
	tcsetattr(upsfd, TCSANOW, &old_tio);
	close(upsfd);
	if (port != NULL) {
		OurImports->TtyUnlock(port);
	}
}

/*
 * Send a command to the ups 
 */

int
APC_send_cmd(int upsfd, const char *cmd)
{
	int i;

	if (Debug) {
		LOG(PIL_DEBUG, "%s(\"%s\")", __FUNCTION__, cmd);
	}

	tcflush(upsfd, TCIFLUSH);
	for (i = strlen(cmd); i > 0; i--) {
		if (write(upsfd, cmd++, 1) != 1) {
			return (S_ACCESS);
		}

		usleep(SEND_DELAY);
	}
	return (S_OK);
}

/*
 * Get the response from the ups 
 */

int
APC_recv_rsp(int upsfd, char *rsp)
{
	char *p = rsp;
	char inp;
	int num = 0;

	if (Debug) {
		LOG(PIL_DEBUG, "%s: called.", __FUNCTION__);
	}

	*p = '\0';

	STONITH_SIGNAL(SIGALRM, APC_sh_serial_timeout);

	alarm(SERIAL_TIMEOUT);

	while (num < MAX_STRING) {

		if (read(upsfd, &inp, 1) == 1) {

	    		/* shutdown sends only a '*' without LF  */
			if ((inp == '*') && (num == 0)) {
				*p++ = inp;
				num++;
				inp = ENDCHAR;
			}

			if (inp == ENDCHAR) {
				alarm(0);
				STONITH_IGNORE_SIG(SIGALRM);

				*p = '\0';
				if (Debug) {
					LOG(PIL_DEBUG, "return(\"%s\")/*%s*/;"
					,	rsp, __FUNCTION__);
				}
				return (S_OK);
			}

			if (inp != CR) {
				*p++ = inp;
				num++;
			}
		}else{
	    		alarm(0);
			STONITH_IGNORE_SIG(SIGALRM);
			*p = '\0';
			LOG(PIL_DEBUG, "%s: %s.", __FUNCTION__,
				f_serialtimeout ? "timeout" :
				"can't access device" );
			return (f_serialtimeout ? S_TIMEOUT : S_ACCESS);
		}
	}
	return (S_ACCESS);
}

/*
 *  Enter smart mode
 */

int
APC_enter_smartmode(int upsfd)
{
    int rc;
    char resp[MAX_STRING];

	if (Debug) {
		LOG(PIL_DEBUG, "%s: called.", __FUNCTION__);
	}

	strcpy(resp, RSP_SMART_MODE);

	if (((rc = APC_send_cmd(upsfd, CMD_SMART_MODE)) == S_OK)
	&&	((rc = APC_recv_rsp(upsfd, resp)) == S_OK)
	&&	(strcmp(RSP_SMART_MODE, resp) == 0)) {
			return (S_OK);
	}

	return (S_ACCESS);
}

/* 
 * Set a value in the hardware using the <cmdchar> '-' (repeat) approach
 */

int
APC_set_ups_var(int upsfd, const char *cmd, char *newval)
{
	char resp[MAX_STRING];
	char orig[MAX_STRING];
	int rc;

	if (Debug) {
		LOG(PIL_DEBUG, "%s: called.", __FUNCTION__);
	}

	if (((rc = APC_enter_smartmode(upsfd)) != S_OK)
	||	((rc = APC_send_cmd(upsfd, cmd)) != S_OK)
	||	((rc = APC_recv_rsp(upsfd, orig)) != S_OK)) {
			return (rc);
	}

	if (Debug) {
		LOG(PIL_DEBUG, "%s: var '%s' original val %s"
		,	__FUNCTION__, cmd, orig);
	}

	if (strcmp(orig, newval) == 0) {
		return (S_OK);		/* already set */
	}

	*resp = '\0';

	while (strcmp(resp, orig) != 0) {
		if (((rc = APC_send_cmd(upsfd, SWITCH_TO_NEXT_VAL)) != S_OK)
		||	((rc = APC_recv_rsp(upsfd, resp)) != S_OK)) {
	    			return (rc);
		}

		if (((rc = APC_enter_smartmode(upsfd)) != S_OK)
		||	((rc = APC_send_cmd(upsfd, cmd)) != S_OK)
		||	((rc = APC_recv_rsp(upsfd, resp)) != S_OK)) {
	    			return (rc);
		}

		if (strcmp(resp, newval) == 0) {
			if (Debug) {
				LOG(PIL_DEBUG, "%s: var '%s' set to %s"
				,	__FUNCTION__, cmd, newval);
			}

			strcpy(newval, orig);	/* return the old value */
			return (S_OK);		/* got it */
		}
	}

	LOG(PIL_CRIT, "%s(): Could not set variable '%s' to %s!"
	,	__FUNCTION__, cmd, newval);
	LOG(PIL_CRIT, "%s(): This UPS may not support STONITH :-("
	,	 __FUNCTION__);

	return (S_OOPS);
}

/* 
 * Query the smallest delay supported by the hardware using the 
 * <cmdchar> '-' (repeat) approach and looping through all possible values,
 * saving the smallest
 */

int
APC_get_smallest_delay(int upsfd, const char *cmd, char *smdelay)
{
	char resp[MAX_DELAY_STRING];
	char orig[MAX_DELAY_STRING];
	int delay, smallest;
	int rc;

	if (Debug) {
		LOG(PIL_DEBUG, "%s: called.", __FUNCTION__);
	}

	if (((rc = APC_enter_smartmode(upsfd)) != S_OK)
	||	((rc = APC_send_cmd(upsfd, cmd)) != S_OK)
	||	((rc = APC_recv_rsp(upsfd, orig)) != S_OK)) {
			return (rc);
	}

	smallest = atoi(orig);
	strcpy(smdelay, orig);

	*resp = '\0';

	/* search for smallest delay; need to loop through all possible
	 * values so that we leave delay the way we found it */
	while (strcmp(resp, orig) != 0) {
		if (((rc = APC_send_cmd(upsfd, SWITCH_TO_NEXT_VAL)) != S_OK)
		||	((rc = APC_recv_rsp(upsfd, resp)) != S_OK)) {
	    			return (rc);
		}

		if (((rc = APC_enter_smartmode(upsfd)) != S_OK)
		||	((rc = APC_send_cmd(upsfd, cmd)) != S_OK)
		||	((rc = APC_recv_rsp(upsfd, resp)) != S_OK)) {
	    			return (rc);
		}

		if ((delay = atoi(resp)) < smallest) {
			smallest = delay;
			strcpy(smdelay, resp);
		}
	}

	return (S_OK);
}

/*
 * Initialize the ups
 */

int
APC_init(struct pluginDevice *ad)
{
	int upsfd;
	char value[MAX_DELAY_STRING];

	if (Debug) {
		LOG(PIL_DEBUG, "%s: called.", __FUNCTION__);
	}

	/* if ad->upsfd != -1 device has already been configured. */
	/* Just enter smart mode again because otherwise a SmartUPS-1000 */
	/*   has been observed to sometimes not respond. */
	if(ad->upsfd >= 0) {
		if(APC_enter_smartmode(ad->upsfd) != S_OK) {
			return(S_OOPS);
		}
		return S_OK;
	}

	/* open serial port and store the fd in ad->upsfd */
	if ((upsfd = APC_open_serialport(ad->upsdev, B2400)) == -1) {
		return S_OOPS;
	}

	/* switch into smart mode */
	if (APC_enter_smartmode(upsfd) != S_OK) {
		APC_close_serialport(ad->upsdev, upsfd);
		ad->upsfd = -1;
		return S_OOPS;
	}

	/* get the smallest possible delays for this particular hardware */
	if (APC_get_smallest_delay(upsfd, CMD_SHUTDOWN_DELAY
		, ad->shutdown_delay) != S_OK
	|| APC_get_smallest_delay(upsfd, CMD_WAKEUP_DELAY
		, ad->wakeup_delay) != S_OK) {
		LOG(PIL_CRIT, "%s: couldn't retrieve smallest delay from UPS"
		,	__FUNCTION__);
		APC_close_serialport(ad->upsdev, upsfd);
		ad->upsfd = -1;
		return S_OOPS;
	}

	/* get the old settings and store them */
	strcpy(value, ad->shutdown_delay);
	if (APC_set_ups_var(upsfd, CMD_SHUTDOWN_DELAY, value) != S_OK) {
		LOG(PIL_CRIT, "%s: couldn't set shutdown delay to %s"
		,	__FUNCTION__, ad->shutdown_delay);
		APC_close_serialport(ad->upsdev, upsfd);
		ad->upsfd = -1;
		return S_OOPS;
	}
	strcpy(ad->old_shutdown_delay, value);
	strcpy(value, ad->wakeup_delay);
	if (APC_set_ups_var(upsfd, CMD_WAKEUP_DELAY, value) != S_OK) {
		LOG(PIL_CRIT, "%s: couldn't set wakeup delay to %s"
		,	__FUNCTION__, ad->wakeup_delay);
		APC_close_serialport(ad->upsdev, upsfd);
		ad->upsfd = -1;
		return S_OOPS;
	}
	strcpy(ad->old_wakeup_delay, value);

	ad->upsfd = upsfd;
	return S_OK;
}

/*
 * Restore original settings and close the port
 */

void
APC_deinit(struct pluginDevice *ad)
{
	APC_enter_smartmode( ad->upsfd );

	APC_set_ups_var(ad->upsfd, CMD_SHUTDOWN_DELAY, ad->old_shutdown_delay);
	APC_set_ups_var(ad->upsfd, CMD_WAKEUP_DELAY, ad->old_wakeup_delay);

	/* close serial port */
	if (ad->upsfd >= 0) {
		APC_close_serialport(ad->upsdev, ad->upsfd);
		ad->upsfd = -1;
	}
}
static const char * const *
apcsmart_get_confignames(StonithPlugin* sp)
{
	static const char * names[] =  {ST_TTYDEV, ST_HOSTLIST, NULL};
	if (Debug) {
		LOG(PIL_DEBUG, "%s: called.", __FUNCTION__);
	}
	return names;
}

/*
 * Stash away the config info we've been given...
 */

static int
apcsmart_set_config(StonithPlugin * s, StonithNVpair* list)
{
	struct pluginDevice *	ad = (struct pluginDevice*)s;
	StonithNamesToGet	namestocopy [] =
	{	{ST_TTYDEV,	NULL}
	,	{ST_HOSTLIST,	NULL}
	,	{NULL,		NULL}
	};
	int			rc;

	if (Debug) {
		LOG(PIL_DEBUG, "%s: called.", __FUNCTION__);
	}
	ERRIFWRONGDEV(s, S_OOPS);

	if ((rc=OurImports->CopyAllValues(namestocopy, list)) != S_OK) {
		return rc;
	}
	ad->upsdev = namestocopy[0].s_value;
	ad->hostlist =	OurImports->StringToHostList(namestocopy[1].s_value);
	FREE(namestocopy[1].s_value);

	if (ad->hostlist == NULL) {
		LOG(PIL_CRIT,"StringToHostList() failed");
		return S_OOPS;
	}
	for (ad->hostcount = 0; ad->hostlist[ad->hostcount]
	;	ad->hostcount++) {
		strdown(ad->hostlist[ad->hostcount]);
	}
	if (access(ad->upsdev, R_OK|W_OK|F_OK) < 0) {
		LOG(PIL_CRIT,"Cannot access tty [%s]", ad->upsdev);
		return S_BADCONFIG;
	}

	return ad->hostcount ? S_OK : S_BADCONFIG;
}

/*
 * return the status for this device 
 */

static int
apcsmart_status(StonithPlugin * s)
{
	struct pluginDevice *ad = (struct pluginDevice *) s;
	char resp[MAX_STRING];
	int rc;

	if (Debug) {
		LOG(PIL_DEBUG, "%s: called.", __FUNCTION__);
	}

	ERRIFNOTCONFIGED(s,S_OOPS);


	/* get status */
	if (((rc = APC_init( ad )) == S_OK)
	&&	((rc = APC_send_cmd(ad->upsfd, CMD_GET_STATUS)) == S_OK)
	&&	((rc = APC_recv_rsp(ad->upsfd, resp)) == S_OK)) {
		return (S_OK);		/* everything ok. */
	}
	if (Debug) {
		LOG(PIL_DEBUG, "%s: failed, rc=%d.", __FUNCTION__, rc);
	}
	return (rc);
}


/*
 * return the list of hosts configured for this device 
 */

static char **
apcsmart_hostlist(StonithPlugin * s)
{
	struct pluginDevice *ad = (struct pluginDevice *) s;

	if (Debug) {
		LOG(PIL_DEBUG, "%s: called.", __FUNCTION__);
	}
	ERRIFNOTCONFIGED(s,NULL);

	return OurImports->CopyHostList((const char **)(void*)ad->hostlist);
}

static gboolean
apcsmart_RegisterBitsSet(struct pluginDevice * ad, int nreg, unsigned bits
,	gboolean* waserr)
{
	const char*	reqregs[4] = {"?", "~", "'", "8"};
	unsigned	regval;
	char		resp[MAX_STRING];

	if (Debug) {
		LOG(PIL_DEBUG, "%s: called.", __FUNCTION__);
	}


	if (APC_enter_smartmode(ad->upsfd) != S_OK
	||	APC_send_cmd(ad->upsfd, reqregs[nreg]) != S_OK
	||	APC_recv_rsp(ad->upsfd, resp) != S_OK
	||	(sscanf(resp, "%02x", &regval) != 1)) {
		if (waserr){
			*waserr = TRUE;
		}
		return FALSE;
	}
	if (waserr){
		*waserr = FALSE;
	}
	return ((regval & bits) == bits);
}

#define	apcsmart_IsPoweredOff(ad, err) apcsmart_RegisterBitsSet(ad,1,0x40,err)
#define	apcsmart_ResetHappening(ad,err) apcsmart_RegisterBitsSet(ad,3,0x08,err)


static int
apcsmart_ReqOnOff(struct pluginDevice * ad, int request)
{
	const char *	cmdstr;
	int		rc;

	if (Debug) {
		LOG(PIL_DEBUG, "%s: called.", __FUNCTION__);
	}
	cmdstr = (request == ST_POWEROFF ? CMD_OFF : CMD_ON);
	/* enter smartmode, send on/off command */
	if ((rc =APC_enter_smartmode(ad->upsfd)) != S_OK
	||	(rc = APC_send_cmd(ad->upsfd, cmdstr)) != S_OK) {
		return rc;
	}
	sleep(2);
	if ((rc = APC_send_cmd(ad->upsfd, cmdstr)) == S_OK) {
		gboolean ison;
		gboolean waserr;
		sleep(1);
		ison = !apcsmart_IsPoweredOff(ad, &waserr);
		if (waserr) {
			return S_RESETFAIL;
		}
		if (request == ST_POWEROFF) {
			return ison ?  S_RESETFAIL : S_OK;
		}else{
			return ison ?  S_OK : S_RESETFAIL;
		}
	}
	return rc;
}

/*
 * reset the host 
 */

static int
apcsmart_ReqGenericReset(struct pluginDevice *ad)
{
	char		resp[MAX_STRING];
	int		rc = S_RESETFAIL;

	if (Debug) {
		LOG(PIL_DEBUG, "%s: called.", __FUNCTION__);
	}

	/* send reset command(s) */
	if (((rc = APC_init(ad)) == S_OK)
	&& ((rc = APC_send_cmd(ad->upsfd, CMD_RESET)) == S_OK)) {
		if (((rc = APC_recv_rsp(ad->upsfd, resp)) == S_OK)
		&& (strcmp(resp, RSP_RESET) == 0
		|| strcmp(resp, RSP_RESET2) == 0)) {
			/* first kind of reset command was accepted */
		} else if (((rc = APC_send_cmd(ad->upsfd, CMD_RESET2)) == S_OK)
		&& ((rc = APC_recv_rsp(ad->upsfd, resp)) == S_OK)
		&& (strcmp(resp, RSP_RESET) == 0
		|| strcmp(resp, RSP_RESET2) == 0)) {
			/* second kind of command was accepted */
		} else {
			if (Debug) {
				LOG(PIL_DEBUG, "APC: neither reset command "
					"was accepted");
			}
			rc = S_RESETFAIL;
		}
	}
	if (rc == S_OK) {
		/* we wait grace period + up to 10 seconds after shutdown */
		int	maxdelay = atoi(ad->shutdown_delay)+10;
		int	j;

		for (j=0; j < maxdelay; ++j) {
			gboolean	err;
			if (apcsmart_ResetHappening(ad, &err)) {
				return err ? S_RESETFAIL : S_OK;
			}
			sleep(1);
		}
		LOG(PIL_CRIT, "%s: timed out waiting for reset to end."
		,	__FUNCTION__);
		return S_RESETFAIL;

	}else{
		if (strcmp(resp, RSP_NA) == 0){
			gboolean iserr;
			/* This means it's currently powered off */
			/* or busy on a previous command... */
			if (apcsmart_IsPoweredOff(ad, &iserr)) {
				if (iserr) {
					LOG(PIL_DEBUG, "%s: power off "
					"detection failed.", __FUNCTION__);
					return S_RESETFAIL;
				}
				if (Debug) {
					LOG(PIL_DEBUG, "APC: was powered off, "
						"powering back on.");
				}
				return apcsmart_ReqOnOff(ad, ST_POWERON);
			}
		}
	}
	strcpy(resp, "?");

	/* reset failed */

	return S_RESETFAIL;
}

static int
apcsmart_reset_req(StonithPlugin * s, int request, const char *host)
{
	char **			hl;
	int			b_found=FALSE;
	struct pluginDevice *	ad = (struct pluginDevice *) s;
	int			rc;

	ERRIFNOTCONFIGED(s, S_OOPS);

	if (host == NULL) {
		LOG(PIL_CRIT, "%s: invalid hostname argument.", __FUNCTION__);
		return (S_INVAL);
	}
    
	/* look through the hostlist */
	hl = ad->hostlist;

	while (*hl && !b_found ) {
		if( strcasecmp( *hl, host ) == 0 ) {
			b_found = TRUE;
			break;
		}else{
        		++hl;
		}
	}

    	/* host not found in hostlist */
	if( !b_found ) {
		LOG(PIL_CRIT, "%s: host '%s' not in hostlist."
		,	__FUNCTION__, host);
		return S_BADHOST;
	}
	if ((rc = APC_init(ad)) != S_OK) {
		return rc;
	}

	if (request == ST_POWERON || request == ST_POWEROFF) {
		return apcsmart_ReqOnOff(ad, request);
	}
	return apcsmart_ReqGenericReset(ad);
}


/*
 * get info about the stonith device 
 */

static const char *
apcsmart_get_info(StonithPlugin * s, int reqtype)
{
	struct pluginDevice *ad = (struct pluginDevice *) s;
	const char *ret;

	if (Debug) {
    		LOG(PIL_DEBUG, "%s: called.", __FUNCTION__);
	}

	ERRIFWRONGDEV(s,NULL);
   

	switch (reqtype) {
    		case ST_DEVICEID:
		ret = ad->idinfo;
		break;

		case ST_DEVICENAME:
		ret = ad->upsdev;
		break;

		case ST_DEVICEDESCR:
		ret = "APC Smart UPS\n"
			" (via serial port - NOT USB!). \n"
			" Works with higher-end APC UPSes, like\n"
			" Back-UPS Pro, Smart-UPS, Matrix-UPS, etc.\n"
			" (Smart-UPS may have to be >= Smart-UPS 700?).\n"
		" See http://www.networkupstools.org/protocols/apcsmart.html\n"
			" for protocol compatibility details.";
			break;

		case ST_DEVICEURL:
			ret = "http://www.apc.com/";
			break;

		case ST_CONF_XML:		/* XML metadata */
			ret = apcsmartXML;
			break;

		default:
			ret = NULL;
			break;
	}
	return (ret);
}

/*
 * APC Stonith destructor... 
 */

static void
apcsmart_destroy(StonithPlugin * s)
{
    struct pluginDevice *ad = (struct pluginDevice *) s;

	if (Debug) {
		LOG(PIL_DEBUG, "%s: called.", __FUNCTION__);
    	}
	VOIDERRIFWRONGDEV(s);

	if (ad->upsfd >= 0 && ad->upsdev) {
		APC_deinit( ad );
	}

	ad->pluginid = NOTpluginID;

	if (ad->hostlist) {
		stonith_free_hostlist(ad->hostlist);
		ad->hostlist = NULL;
	}
	if (ad->upsdev != NULL) {
		FREE(ad->upsdev);
		ad->upsdev = NULL;
	}

	ad->hostcount = -1;
	ad->upsfd = -1;

	FREE(ad);

}

/*
 * Create a new APC Stonith device.  Too bad this function can't be
 * static 
 */

static StonithPlugin *
apcsmart_new(const char *subplugin)
{
    struct pluginDevice *ad = ST_MALLOCT(struct pluginDevice);

	if (Debug) {
		LOG(PIL_DEBUG, "%s: called.", __FUNCTION__);
	}
	if (ad == NULL) {
		LOG(PIL_CRIT, "%s: out of memory.", __FUNCTION__);
		return (NULL);
	}

	memset(ad, 0, sizeof(*ad));

	ad->pluginid = pluginid;
	ad->hostlist = NULL;
	ad->hostcount = -1;
	ad->upsfd = -1;
	ad->idinfo = DEVICE;
	ad->sp.s_ops = &apcsmartOps;

	if (Debug) {
		LOG(PIL_DEBUG, "%s: returning successfully.", __FUNCTION__);
	}
	return &(ad->sp);
}