14b2e52e3e70baa35377bbf038c8faf785403bdb
[dragonfly.git] / usr.sbin / battd / battd.c
1 /*
2  * Copyright (c) 2003, 2005 The DragonFly Project.  All rights reserved.
3  * 
4  * This code is derived from software contributed to The DragonFly Project
5  * by Liam J. Foy <liamfoy@dragonflybsd.org> 
6  * 
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  * 
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  * 
34  * $DragonFly: src/usr.sbin/battd/battd.c,v 1.3 2005/02/01 19:51:28 liamfoy Exp $
35  */
36
37 #include <sys/file.h>
38 #include <sys/ioctl.h>
39 #include <sys/types.h>
40 #include <sys/wait.h>
41
42 #include <machine/apm_bios.h>
43 #include <limits.h>
44
45 #include <err.h>
46 #include <errno.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <syslog.h>
51 #include <time.h>
52 #include <unistd.h>
53
54 #define APMUNKNOWN      255 /* Unknown value. */
55 #define AC_LINE_IN      1 /* AC Line Status values. */
56 #define AC_OFFLINE      0
57 #define SECONDS         60
58 #define APM_DEVICE      "/dev/apm" /* Default APM Device. */
59 #define ERR_OUT         1  /* Values for error writing. */
60 #define SYSLOG_OUT      0
61 #define DEFAULT_ALERT   10 /* Default alert is 10%. */
62
63 struct battd_conf {
64         int     alert_per;      /* Percentage to alert user on */
65         int     alert_time;     /* User can also alert when there is only X amount of minutes left */
66         int     alert_status;   /* Alert when battery is either high, low, critical */ 
67         const char      *apm_dev;       /* APM Device */
68         const char      *exec_cmd;      /* Command to execute if desired */     
69 };
70
71 static int      check_percent(int);
72 static int      check_stat(int);
73 static int      check_time(int);
74 static int      get_apm_info(struct apm_info *, int, const char *, int);
75 static void     execute_cmd(const char *, int *);
76 static void     write_emerg(const char *, int *);
77 static void     usage(void); __dead2
78
79 static void
80 usage(void)
81 {
82         fprintf(stderr, "usage: battd [-dEhT] [-p percent] [-t minutes] [-s status]\n"
83                         "             [-f device] [-e command] [-c seconds]\n");
84         exit(EXIT_FAILURE);     
85 }
86
87 static int
88 check_percent(int apm_per)
89 {
90         if (apm_per < 0 || apm_per >= APMUNKNOWN || apm_per > 100)
91                 return(1);
92
93         return(0);
94 }
95
96 static int
97 check_time(int apm_time)
98 {
99         if (apm_time == -1)
100                 return(1);
101
102         return(0);
103 }
104
105 static int
106 check_stat(int apm_stat)
107 {
108         if (apm_stat > 3 || apm_stat < 0)
109                 return(1);
110
111         return(0);
112 }
113
114 /* Fetch battery information */
115 static int
116 get_apm_info(struct apm_info *ai, int fp_dev, const char *apm_dev, int err_to)
117 {
118         if (ioctl(fp_dev, APMIO_GETINFO, ai) == -1) {
119                 if (err_to)
120                         err(1, "ioctl(APMIO_GETINFO) Device: %s", apm_dev);
121                 else
122                         syslog(LOG_ERR, "ioctl(APMIO_GETINFO) device: %s : %m ",
123                                 apm_dev);
124
125                 return(1);
126         }
127
128         return(0);
129 }
130
131 /* Execute command. */  
132 static void
133 execute_cmd(const char *exec_cmd, int *exec_cont)
134 {
135         pid_t pid;
136         int status;
137                 
138         if (exec_cmd != NULL) {
139                 if ((pid = fork()) == -1) {
140                         /* Here fork failed */
141                         syslog(LOG_ERR, "fork failed: %m");
142                 } else if (pid == 0) {
143                         execl("/bin/sh", "/bin/sh", "-c", exec_cmd, NULL);
144                         _exit(EXIT_FAILURE);
145                 } else {
146                         while (waitpid(pid, &status, 0) != pid)
147                                 ;
148                         if (WEXITSTATUS(status))
149                                 syslog(LOG_ERR, "child exited with code %d", status);
150                         if (*exec_cont)
151                                 exec_cmd = NULL;
152                 }
153         }
154 }
155
156 /* Write warning. */
157 static void
158 write_emerg(const char *eme_msg, int *warn_cont)
159 {
160         if (*warn_cont == 0) {
161                 openlog("battd", LOG_EMERG, LOG_CONSOLE);
162                 syslog(LOG_ERR, "%s\n", eme_msg);
163                 *warn_cont = 1;
164         }
165 }
166
167 /* Check given numerical arguments. */
168 static int
169 getnum(const char *str)
170 {
171         long val;
172         char *ep;
173
174         errno = 0;
175         val = strtol(str, &ep, 10);
176         if (errno)
177                 err(1, "strtol failed: %s", str);
178
179         if (str == ep || *ep != '\0')
180                 errx(1, "invalid value: %s", str);
181
182         if (val > INT_MAX || val < INT_MIN) {
183                 errno = ERANGE;
184                 errc(1, errno, "getnum failed:");
185         }
186
187         return((int)val);
188 }
189
190 int
191 main(int argc, char **argv)
192 {
193         struct battd_conf battd_options, *opts;
194         struct apm_info ai;
195         int fp_device, exec_cont, f_debug;
196         int per_warn_cont, time_warn_cont, stat_warn_cont;
197         int check_sec, time_def_alert, def_warn_cont;
198         int c, tmp;
199         char msg[1024];
200
201         opts = &battd_options;
202
203         /*
204          * As default, we sleep for 30 seconds before
205          * we next call get_apm_info and do the rounds.
206          * The lower the value, the more accurate. Very
207          * low values could cause a decrease in system
208          * performance. We recommend about 30 seconds.
209          */
210
211         check_sec = 30;
212
213         exec_cont = f_debug = per_warn_cont = stat_warn_cont = 0;
214         time_warn_cont = time_def_alert = def_warn_cont = 0;
215
216         opts->alert_per = 0;
217         opts->alert_time = 0;
218         opts->alert_status = -1;
219         opts->exec_cmd = NULL;
220         opts->apm_dev = APM_DEVICE;
221
222         while ((c = getopt(argc, argv, "de:Ep:s:c:f:ht:T")) != -1) {
223                 switch (c) {
224                 case 'c':
225                         /* Parse the check battery interval. */
226                         check_sec = getnum(optarg);
227                         if (check_sec <= 0)
228                                 errx(1, "the interval for checking battery"
229                                         "status must be greater than 0.");
230                         break;
231                 case 'd':
232                         /* Debug mode. */
233                         f_debug = 1;
234                         break;
235                 case 'e':
236                         /* Command to execute. */
237                         opts->exec_cmd = optarg;
238                         break;
239                 case 'E':
240                         /* Only execute once when any condition has been met. */ 
241                         exec_cont = 1;
242                         break;  
243                 case 'f':
244                         /* Don't use /dev/apm use optarg. */
245                         opts->apm_dev = optarg;
246                         break;
247                 case 'h':
248                         /* Print usage and be done! */
249                         usage();
250                         break;
251                 case 'p':
252                         /*
253                          * Parse percentage to alert on and enable
254                          * battd to monitor the battery percentage.
255                          */
256                         opts->alert_per = getnum(optarg);
257                         if (opts->alert_per <= 0 || opts->alert_per > 100)
258                                 errx(1, "Battery percentage to alert on must be "
259                                         "greater than 0 and less than 100.");
260                         break;
261                 case 's':
262                         /*
263                          * Parse status to alert on and enable
264                          * battd to monitor the battery status.
265                          * We also accept 'high', 'HIGH' or 'HiGh'.
266                          */
267                         if (strcasecmp(optarg, "high") == 0)
268                                 opts->alert_status = 0; /* High */
269                         else if (strcasecmp(optarg, "low") == 0)
270                                 opts->alert_status = 1; /* Low */
271                         else if (strcasecmp(optarg, "critical") == 0)
272                                 opts->alert_status = 2; /* Critical (mental) */
273                         else {
274                                 /* No idea, see what we have. */
275                                 opts->alert_status = getnum(optarg);
276                                 if (opts->alert_status < 0 || opts->alert_status > 2)
277                                         errx(1, "Alert status must be between 0 and 2.");
278                         }
279                         break;
280                 case 't':
281                         /*
282                          * Parse time to alert on and enable
283                          * battd to monitor the time percentage.
284                          */
285                         opts->alert_time = getnum(optarg);
286                         if (opts->alert_time <= 0)
287                                 errx(1, "Alert time must be greater than zero.");
288                         break;
289                 case 'T':
290                         time_def_alert = 1;
291                         break;
292                 default:
293                         usage();
294                 }
295         }
296
297         if ((fp_device = open(opts->apm_dev, O_RDONLY)) < 0)
298                 err(1, "open failed: %s", opts->apm_dev);
299
300         /* 
301          * Before we become a daemon, first check whether
302          * the actual function requested is supported. If
303          * not, exit and let the user know.
304          */
305
306         /* Start test */
307         get_apm_info(&ai, fp_device, opts->apm_dev, ERR_OUT);
308
309         if (opts->alert_per >= 0)
310                 if (check_percent(ai.ai_batt_life))
311                         errx(1, "invalid/unknown percentage(%d) returned from apm device",
312                                 ai.ai_batt_life);
313
314         if (opts->alert_time)
315                 if (check_time(ai.ai_batt_time))
316                         errx(1, "invalid/unknown time(%d) returned from apm device",
317                                 ai.ai_batt_time);
318
319         if (opts->alert_status)
320                 if (check_stat(ai.ai_batt_stat))
321                         errx(1, "invalid/unknown status(%d) returned from apm device",
322                                 ai.ai_batt_stat);
323         /* End test */
324
325         if (f_debug == 0) {
326                 if (daemon(0, 0) == -1) 
327                         err(1, "daemon failed");
328         }
329
330         for (;;) {      
331                 if (get_apm_info(&ai, fp_device, opts->apm_dev,
332                         f_debug ? ERR_OUT : SYSLOG_OUT))
333                         /* Recoverable - sleep for check_sec seconds */
334                         goto sleepy_time;
335
336                 /* If we have power, reset the warning values. */
337                 if (ai.ai_acline == AC_LINE_IN) {
338                         per_warn_cont = 0;
339                         time_warn_cont = 0;
340                         stat_warn_cont = 0;
341                         def_warn_cont = 0;
342                 }
343
344                 /*
345                  * If the battery has main power (AC lead is plugged in)
346                  * we skip and sleep for check_sec seconds.
347                  */
348                 if (ai.ai_acline != AC_LINE_IN) {
349                         /*
350                          * Battery has no mains power. Time to do
351                          * our job!
352                          */
353
354                         /*
355                          * Main Processing loop
356                          * --------------------
357                          * 1. Check battery percentage if enabled.
358                          * 2. Check battery time remaining if enabled.
359                          * 3. Check battery status if enabled.
360                          * 4. Deal with default alerts.
361                          */ 
362
363                         /* 1. Check battery percentage if enabled */
364                         if (opts->alert_per) {
365                                 if (check_percent(ai.ai_batt_life)) {
366                                         if (f_debug) {
367                                                 printf("Invaild percentage (%d) recieved from %s.\n",
368                                                         ai.ai_batt_life, opts->apm_dev);
369                                         } else {
370                                                 syslog(LOG_ERR, "Invaild percentage recieved from %s.",
371                                                         opts->apm_dev);
372                                         }
373                                         continue;
374                                 }
375                         
376                                 if (ai.ai_batt_life <= (u_int)opts->alert_per) {
377                                         tmp = (ai.ai_batt_life == (u_int)opts->alert_per);
378                                         snprintf(msg, sizeof(msg), "battery has %s %d%%\n",
379                                                 tmp ? "reached" : "fell below",
380                                                 opts->alert_per);
381                                         execute_cmd(opts->exec_cmd, &exec_cont);
382                                         write_emerg(msg, &per_warn_cont);
383                                 }
384                         }                                       
385
386                         /* 2. Check battery time remaining if enabled */
387                         if (opts->alert_time) {
388                                 if (check_time(ai.ai_batt_time)) {
389                                         if (f_debug) {
390                                                 printf("Invaild time value (%d) recieved from %s.\n",
391                                                         ai.ai_batt_time, opts->apm_dev);
392                                         } else {
393                                                 syslog(LOG_ERR, "Invaild time value recieved from %s.",
394                                                         opts->apm_dev);
395                                         }
396                                         continue;
397                                 }
398                 
399                                 if (ai.ai_batt_time <= (opts->alert_time * SECONDS)) {
400                                         int h, m, s;
401                                         char tmp_time[sizeof "tt:tt:tt" + 1];
402                                         h = ai.ai_batt_time;
403                                         s = h % 60;
404                                         h /= 60;
405                                         m = h % 60;
406                                         h /= 60;
407                                         snprintf(tmp_time, sizeof(tmp_time), "%d:%d:%d\n", h, m, s);
408                                         tmp = (ai.ai_batt_time == opts->alert_time);
409                                         snprintf(msg, sizeof(msg), "battery has %s %d(%s) minutes"
410                                                 "remaining\n", tmp ? "reached" : "fell below",
411                                                 ai.ai_batt_time / SECONDS, tmp_time);
412                                         execute_cmd(opts->exec_cmd, &exec_cont);
413                                         write_emerg(msg, &time_warn_cont);
414                                 }       
415                         }
416
417                         /* 3. Check battery status if enabled */
418                         if (opts->alert_status != -1) {
419                                 if (check_stat(ai.ai_batt_stat)) {
420                                         if (f_debug) {
421                                                 printf("Invaild status value (%d) recieved from %s.\n",
422                                                         ai.ai_batt_life, opts->apm_dev);
423                                         } else {        
424                                                 syslog(LOG_ERR, "Invaild status value recieved from %s.",
425                                                         opts->apm_dev);
426                                         }
427                                         continue;
428                                 }
429
430                                 if (ai.ai_batt_stat >= (u_int)opts->alert_status) {
431                                         const char *batt_status[] = {"'high'", "'low'", "'critical'"};
432
433                                         tmp = (ai.ai_batt_stat == (u_int)opts->alert_status);
434                                         snprintf(msg, sizeof(msg), "battery has %s '%s' status\n",
435                                                 tmp ? "reached" : "fell below",
436                                                 batt_status[ai.ai_batt_stat]);
437                                         execute_cmd(opts->exec_cmd, &exec_cont);
438                                         write_emerg(msg, &stat_warn_cont);
439                                 }
440                         }
441
442                         /* 4. Deal with default alerts. */ 
443                         if (time_def_alert) {
444                                 if (check_time(ai.ai_batt_time)) {
445                                                 if (ai.ai_batt_time <= DEFAULT_ALERT * SECONDS) {
446                                                         snprintf(msg, sizeof(msg), "WARNING! battery only"
447                                                                  "has roughly %d minutes remaining!\n",
448                                                                 ai.ai_batt_time / SECONDS);
449                                                         write_emerg(msg, NULL); 
450                                                 }
451                                 }
452                         }
453
454                         if (ai.ai_batt_life <= DEFAULT_ALERT) {
455                                 tmp = (ai.ai_batt_life == DEFAULT_ALERT);
456                                 snprintf(msg, sizeof(msg), "WARNING! battery has %s %d%%\n",
457                                         tmp ? "reached" : "fell below",
458                                         DEFAULT_ALERT);
459                                 if (!def_warn_cont)
460                                         execute_cmd(opts->exec_cmd, &exec_cont);
461                                 write_emerg(msg, &def_warn_cont);
462                         }
463
464                 }
465 sleepy_time:
466                 /* Sleep time! Default is 30 seconds */
467                 sleep(check_sec);
468         }
469         return(0);
470 }