Home | History | Annotate | Line # | Download | only in apmd
apmd.c revision 1.30.16.1
      1 /*	$NetBSD: apmd.c,v 1.30.16.1 2008/05/18 12:36:14 yamt Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1996, 2000 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by John Kohl.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 #include <stdio.h>
     33 #include <errno.h>
     34 #include <syslog.h>
     35 #include <fcntl.h>
     36 #include <unistd.h>
     37 #include <util.h>
     38 #include <stdlib.h>
     39 #include <string.h>
     40 #include <signal.h>
     41 #include <sys/types.h>
     42 #include <pwd.h>
     43 #include <grp.h>
     44 #include <sys/stat.h>
     45 #include <sys/ioctl.h>
     46 #include <sys/time.h>
     47 #include <sys/socket.h>
     48 #include <sys/un.h>
     49 #include <sys/wait.h>
     50 #include <poll.h>
     51 #include <machine/apmvar.h>
     52 #include <err.h>
     53 #include "pathnames.h"
     54 #include "apm-proto.h"
     55 
     56 #define TRUE 1
     57 #define FALSE 0
     58 
     59 #define POWER_STATUS_ACON	0x1
     60 #define POWER_STATUS_LOWBATTNOW	0x2
     61 
     62 const char apmdev[] = _PATH_APM_CTLDEV;
     63 const char sockfile[] = _PATH_APM_SOCKET;
     64 
     65 static int debug = 0;
     66 static int verbose = 0;
     67 
     68 void usage (void);
     69 int power_status (int fd, int force, struct apm_power_info *pinfo);
     70 int bind_socket (const char *sn, mode_t mode, uid_t uid, gid_t gid);
     71 enum apm_state handle_client(int sock_fd, int ctl_fd);
     72 void suspend(int ctl_fd);
     73 void stand_by(int ctl_fd);
     74 void resume(int ctl_fd);
     75 void sigexit(int signo);
     76 void make_noise(int howmany);
     77 void do_etc_file(const char *file);
     78 void do_ac_state(int state);
     79 
     80 void
     81 sigexit(int signo)
     82 {
     83     exit(1);
     84 }
     85 
     86 void
     87 usage(void)
     88 {
     89     fprintf(stderr,"usage: %s [-adlqsv] [-t seconds] [-S sockname]\n\t[-m sockmode] [-o sockowner:sockgroup] [-f devname]\n", getprogname());
     90     exit(1);
     91 }
     92 
     93 
     94 int
     95 power_status(int fd, int force, struct apm_power_info *pinfo)
     96 {
     97     struct apm_power_info bstate;
     98     static struct apm_power_info last;
     99     int acon = 0;
    100     int lowbattnow = 0;
    101 
    102     memset(&bstate, 0, sizeof(bstate));
    103     if (ioctl(fd, APM_IOC_GETPOWER, &bstate) == 0) {
    104 	/* various conditions under which we report status:  something changed
    105 	   enough since last report, or asked to force a print */
    106 	if (bstate.ac_state == APM_AC_ON)
    107 	    acon = 1;
    108 	if (bstate.battery_state != last.battery_state  &&
    109 	    bstate.battery_state == APM_BATT_LOW)
    110 		lowbattnow = 1;
    111 	if (force ||
    112 	    bstate.ac_state != last.ac_state ||
    113 	    bstate.battery_state != last.battery_state ||
    114 	    (bstate.minutes_left && bstate.minutes_left < 15) ||
    115 	    abs(bstate.battery_life - last.battery_life) > 20) {
    116 	    if (verbose) {
    117 		if (bstate.minutes_left)
    118 		    syslog(LOG_NOTICE,
    119 		           "battery status: %s. external power status: %s. "
    120 		           "estimated battery life %d%% (%d minutes)",
    121 		           battstate(bstate.battery_state),
    122 		           ac_state(bstate.ac_state), bstate.battery_life,
    123 		           bstate.minutes_left);
    124 		else
    125 		    syslog(LOG_NOTICE,
    126 		           "battery status: %s. external power status: %s. "
    127 		           "estimated battery life %d%%",
    128 		           battstate(bstate.battery_state),
    129 		           ac_state(bstate.ac_state), bstate.battery_life);
    130 	    }
    131 	    last = bstate;
    132 	}
    133 	if (pinfo)
    134 	    *pinfo = bstate;
    135     } else
    136 	syslog(LOG_ERR, "cannot fetch power status: %m");
    137     return ((acon?POWER_STATUS_ACON:0) |
    138 	(lowbattnow?POWER_STATUS_LOWBATTNOW:0));
    139 }
    140 
    141 static char *socketname;
    142 
    143 static void sockunlink(void);
    144 
    145 static void
    146 sockunlink(void)
    147 {
    148     if (socketname)
    149 	(void) remove(socketname);
    150 }
    151 
    152 int
    153 bind_socket(const char *sockname, mode_t mode, uid_t uid, gid_t gid)
    154 {
    155     int sock;
    156     struct sockaddr_un s_un;
    157 
    158     sock = socket(AF_LOCAL, SOCK_STREAM, 0);
    159     if (sock == -1)
    160 	err(1, "cannot create local socket");
    161 
    162     s_un.sun_family = AF_LOCAL;
    163     strncpy(s_un.sun_path, sockname, sizeof(s_un.sun_path));
    164     s_un.sun_len = SUN_LEN(&s_un);
    165     /* remove it if present, we're moving in */
    166     (void) remove(sockname);
    167     if (bind(sock, (struct sockaddr *)&s_un, s_un.sun_len) == -1)
    168 	err(1, "cannot create APM socket");
    169     if (chmod(sockname, mode) == -1 || chown(sockname, uid, gid) == -1)
    170 	err(1, "cannot set socket mode/owner/group to %o/%d/%d",
    171 	    mode, uid, gid);
    172     listen(sock, 1);
    173     socketname = strdup(sockname);
    174     atexit(sockunlink);
    175     return sock;
    176 }
    177 
    178 enum apm_state
    179 handle_client(int sock_fd, int ctl_fd)
    180 {
    181     /* accept a handle from the client, process it, then clean up */
    182     int cli_fd;
    183     struct sockaddr_un from;
    184     socklen_t fromlen = sizeof(from);
    185     struct apm_command cmd;
    186     struct apm_reply reply;
    187 
    188     cli_fd = accept(sock_fd, (struct sockaddr *)&from, &fromlen);
    189     if (cli_fd == -1) {
    190 	syslog(LOG_INFO, "client accept failure: %m");
    191 	return NORMAL;
    192     }
    193     if (recv(cli_fd, &cmd, sizeof(cmd), 0) != sizeof(cmd)) {
    194 	(void) close(cli_fd);
    195 	syslog(LOG_INFO, "client size botch");
    196 	return NORMAL;
    197     }
    198     if (cmd.vno != APMD_VNO) {
    199 	close(cli_fd);			/* terminate client */
    200 	/* no error message, just drop it. */
    201 	return NORMAL;
    202     }
    203     power_status(ctl_fd, 0, &reply.batterystate);
    204     switch (cmd.action) {
    205     default:
    206 	reply.newstate = NORMAL;
    207 	break;
    208     case SUSPEND:
    209 	reply.newstate = SUSPENDING;
    210 	break;
    211     case STANDBY:
    212 	reply.newstate = STANDING_BY;
    213 	break;
    214     }
    215     reply.vno = APMD_VNO;
    216     if (send(cli_fd, &reply, sizeof(reply), 0) != sizeof(reply)) {
    217 	syslog(LOG_INFO, "client reply botch");
    218     }
    219     close(cli_fd);
    220     return reply.newstate;
    221 }
    222 
    223 static int speaker_ok = TRUE;
    224 
    225 void
    226 make_noise(howmany)
    227 int howmany;
    228 {
    229     int spkrfd;
    230     int trycnt;
    231 
    232     if (!speaker_ok)		/* don't bother after sticky errors */
    233 	return;
    234 
    235     for (trycnt = 0; trycnt < 3; trycnt++) {
    236 	spkrfd = open(_PATH_DEV_SPEAKER, O_WRONLY);
    237 	if (spkrfd == -1) {
    238 	    switch (errno) {
    239 	    case EBUSY:
    240 		usleep(500000);
    241 		errno = EBUSY;
    242 		continue;
    243 	    case ENOENT:
    244 	    case ENODEV:
    245 	    case ENXIO:
    246 	    case EPERM:
    247 	    case EACCES:
    248 		syslog(LOG_INFO,
    249 		       "speaker device " _PATH_DEV_SPEAKER " unavailable: %m");
    250 		speaker_ok = FALSE;
    251 		return;
    252 	    }
    253 	} else
    254 	    break;
    255     }
    256     if (spkrfd == -1) {
    257 	syslog(LOG_WARNING, "cannot open " _PATH_DEV_SPEAKER ": %m");
    258 	return;
    259     }
    260     syslog(LOG_DEBUG, "sending %d tones to speaker\n", howmany);
    261     write (spkrfd, "o4cc", 2 + howmany);
    262     close(spkrfd);
    263     return;
    264 }
    265 
    266 
    267 void
    268 suspend(int ctl_fd)
    269 {
    270     do_etc_file(_PATH_APM_ETC_SUSPEND);
    271     sync();
    272     make_noise(2);
    273     sync();
    274     sync();
    275     sleep(1);
    276     ioctl(ctl_fd, APM_IOC_SUSPEND, 0);
    277 }
    278 
    279 void
    280 stand_by(int ctl_fd)
    281 {
    282     do_etc_file(_PATH_APM_ETC_STANDBY);
    283     sync();
    284     make_noise(1);
    285     sync();
    286     sync();
    287     sleep(1);
    288     ioctl(ctl_fd, APM_IOC_STANDBY, 0);
    289 }
    290 
    291 #define TIMO (10*60)			/* 10 minutes */
    292 
    293 void
    294 resume(int ctl_fd)
    295 {
    296     do_etc_file(_PATH_APM_ETC_RESUME);
    297 }
    298 
    299 int
    300 main(int argc, char *argv[])
    301 {
    302     const char *fname = apmdev;
    303     int ctl_fd, sock_fd, ch, ready;
    304     int statonly = 0;
    305     struct pollfd set[2];
    306     struct apm_event_info apmevent;
    307     int suspends, standbys, resumes;
    308     int ac_is_off;
    309     int noacsleep = 0;
    310     int lowbattsleep = 0;
    311     mode_t mode = 0660;
    312     unsigned long timeout = TIMO;
    313     const char *sockname = sockfile;
    314     char *user, *group;
    315     char *scratch;
    316     uid_t uid = 2; /* operator */
    317     gid_t gid = 5; /* operator */
    318     struct passwd *pw;
    319     struct group *gr;
    320 
    321     while ((ch = getopt(argc, argv, "adlqsvf:t:S:m:o:")) != -1)
    322 	switch(ch) {
    323 	case 'q':
    324 	    speaker_ok = FALSE;
    325 	    break;
    326 	case 'a':
    327 	    noacsleep = 1;
    328 	    break;
    329 	case 'l':
    330 	    lowbattsleep = 1;
    331 	    break;
    332 	case 'd':
    333 	    debug = 1;
    334 	    break;
    335 	case 'v':
    336 	    verbose = 1;
    337 	    break;
    338 	case 'f':
    339 	    fname = optarg;
    340 	    break;
    341 	case 'S':
    342 	    sockname = optarg;
    343 	    break;
    344 	case 't':
    345 	    timeout = strtoul(optarg, 0, 0);
    346 	    if (timeout == 0)
    347 		usage();
    348 	    break;
    349 	case 'm':
    350 	    mode = strtoul(optarg, 0, 8);
    351 	    if (mode == 0)
    352 		usage();
    353 	    break;
    354 	case 'o':
    355 	    /* (user):(group) */
    356 	    user = optarg;
    357 	    group = strchr(user, ':');
    358 	    if (group)
    359 		*group++ = '\0';
    360 	    if (*user) {
    361 		uid = strtoul(user, &scratch, 0);
    362 		if (*scratch != '\0') {
    363 		    pw = getpwnam(user);
    364 		    if (pw)
    365 			uid = pw->pw_uid;
    366 		    else
    367 			errx(1, "user name `%s' unknown", user);
    368 		}
    369 	    }
    370 	    if (group && *group) {
    371 		gid = strtoul(group, &scratch, 0);
    372 		if (*scratch != '\0') {
    373 		    gr = getgrnam(group);
    374 		    if (gr)
    375 			gid = gr->gr_gid;
    376 		    else
    377 			errx(1, "group name `%s' unknown", group);
    378 		}
    379 	    }
    380 	    break;
    381 	case 's':			/* status only */
    382 	    statonly = 1;
    383 	    break;
    384 	case '?':
    385 
    386 	default:
    387 	    usage();
    388 	}
    389     argc -= optind;
    390     argv += optind;
    391     if (debug) {
    392 	openlog("apmd", 0, LOG_LOCAL1);
    393     } else {
    394 	daemon(0, 0);
    395 	openlog("apmd", 0, LOG_DAEMON);
    396 	setlogmask(LOG_UPTO(LOG_NOTICE));
    397 	pidfile(NULL);
    398     }
    399     if ((ctl_fd = open(fname, O_RDWR)) == -1) {
    400 	syslog(LOG_ERR, "cannot open device file `%s'", fname);
    401 	exit(1);
    402     }
    403 
    404     if (statonly) {
    405         power_status(ctl_fd, 1, 0);
    406 	exit(0);
    407     } else {
    408 	struct apm_power_info pinfo;
    409 	power_status(ctl_fd, 1, &pinfo);
    410 	do_ac_state(pinfo.ac_state);
    411 	ac_is_off = (pinfo.ac_state == APM_AC_OFF);
    412     }
    413 
    414     (void) signal(SIGTERM, sigexit);
    415     (void) signal(SIGHUP, sigexit);
    416     (void) signal(SIGINT, sigexit);
    417     (void) signal(SIGPIPE, SIG_IGN);
    418 
    419 
    420     sock_fd = bind_socket(sockname, mode, uid, gid);
    421 
    422     set[0].fd = ctl_fd;
    423     set[0].events = POLLIN;
    424     set[1].fd = sock_fd;
    425     set[1].events = POLLIN;
    426 
    427 
    428     for (errno = 0;
    429 	 (ready = poll(set, 2, timeout * 1000)) >= 0 || errno == EINTR;
    430 	 errno = 0) {
    431 	if (errno == EINTR)
    432 	    continue;
    433 	if (ready == 0) {
    434 		int status;
    435 		/* wakeup for timeout: take status */
    436 		status = power_status(ctl_fd, 0, 0);
    437 		if (lowbattsleep && status&POWER_STATUS_LOWBATTNOW) {
    438 			if (noacsleep && status&POWER_STATUS_ACON) {
    439 				if (debug)
    440 					syslog(LOG_DEBUG,
    441 					    "not sleeping because "
    442 					    "AC is connected");
    443 			} else
    444 				suspend(ctl_fd);
    445 		}
    446 	}
    447 	if (set[0].revents & POLLIN) {
    448 	    suspends = standbys = resumes = 0;
    449 	    while (ioctl(ctl_fd, APM_IOC_NEXTEVENT, &apmevent) == 0) {
    450 		if (debug)
    451 		    syslog(LOG_DEBUG, "apmevent %04x index %d", apmevent.type,
    452 		           apmevent.index);
    453 		switch (apmevent.type) {
    454 		case APM_SUSPEND_REQ:
    455 		case APM_USER_SUSPEND_REQ:
    456 		case APM_CRIT_SUSPEND_REQ:
    457 		    suspends++;
    458 		    break;
    459 		case APM_BATTERY_LOW:
    460 		    if (lowbattsleep)
    461 			suspends++;
    462 		    break;
    463 		case APM_USER_STANDBY_REQ:
    464 		case APM_STANDBY_REQ:
    465 		    standbys++;
    466 		    break;
    467 #if 0
    468 		case APM_CANCEL:
    469 		    suspends = standbys = 0;
    470 		    break;
    471 #endif
    472 		case APM_NORMAL_RESUME:
    473 		case APM_CRIT_RESUME:
    474 		case APM_SYS_STANDBY_RESUME:
    475 		    resumes++;
    476 		    break;
    477 		case APM_POWER_CHANGE:
    478 		{
    479 		    struct apm_power_info pinfo;
    480 		    power_status(ctl_fd, 0, &pinfo);
    481 		    /* power status can change without ac status changing */
    482 		    if (ac_is_off != (pinfo.ac_state == APM_AC_OFF)) {
    483 		    	do_ac_state(pinfo.ac_state);
    484 			ac_is_off = (pinfo.ac_state == APM_AC_OFF);
    485 		    }
    486 		    break;
    487 		}
    488 		default:
    489 		    break;
    490 		}
    491 	    }
    492 	    if ((standbys || suspends) && noacsleep &&
    493 		(power_status(ctl_fd, 0, 0) & POWER_STATUS_ACON)) {
    494 		if (debug)
    495 		    syslog(LOG_DEBUG, "not sleeping because AC is connected");
    496 	    } else if (suspends) {
    497 		suspend(ctl_fd);
    498 	    } else if (standbys) {
    499 		stand_by(ctl_fd);
    500 	    } else if (resumes) {
    501 		resume(ctl_fd);
    502 		if (verbose)
    503 		    syslog(LOG_NOTICE, "system resumed from APM sleep");
    504 	    }
    505 	    ready--;
    506 	}
    507 	if (ready == 0)
    508 	    continue;
    509 	if (set[1].revents & POLLIN) {
    510 	    switch (handle_client(sock_fd, ctl_fd)) {
    511 	    case NORMAL:
    512 		break;
    513 	    case SUSPENDING:
    514 		suspend(ctl_fd);
    515 		break;
    516 	    case STANDING_BY:
    517 		stand_by(ctl_fd);
    518 		break;
    519 	    }
    520 	}
    521     }
    522     syslog(LOG_ERR, "poll failed: %m");
    523     exit(1);
    524 }
    525 
    526 void
    527 do_etc_file(const char *file)
    528 {
    529     pid_t pid;
    530     int status;
    531     const char *prog;
    532 
    533     /* If file doesn't exist, do nothing. */
    534     if (access(file, X_OK|R_OK)) {
    535 	if (debug)
    536 	    syslog(LOG_DEBUG, "do_etc_file(): cannot access file %s", file);
    537 	return;
    538     }
    539 
    540     prog = strrchr(file, '/');
    541     if (prog)
    542 	prog++;
    543     else
    544 	prog = file;
    545 
    546     pid = fork();
    547     switch (pid) {
    548     case -1:
    549 	syslog(LOG_ERR, "failed to fork(): %m");
    550 	return;
    551     case 0:
    552 	/* We are the child. */
    553 	if (execl(file, prog, NULL) == -1)
    554 		syslog(LOG_ERR, "could not execute \"%s\": %m", file);
    555 	_exit(1);
    556 	/* NOTREACHED */
    557     default:
    558 	/* We are the parent. */
    559 	wait4(pid, &status, 0, 0);
    560 	if (WIFEXITED(status)) {
    561 	    if (debug)
    562 		syslog(LOG_DEBUG, "%s exited with status %d", file,
    563 		       WEXITSTATUS(status));
    564 	} else
    565 	    syslog(LOG_ERR, "%s exited abnormally.", file);
    566 	break;
    567     }
    568 }
    569 
    570 void
    571 do_ac_state(int state)
    572 {
    573 	switch (state) {
    574 	case APM_AC_OFF:
    575 		do_etc_file(_PATH_APM_ETC_BATTERY);
    576 		break;
    577 	case APM_AC_ON:
    578 	case APM_AC_BACKUP:
    579 		do_etc_file(_PATH_APM_ETC_LINE);
    580 		break;
    581 	default:
    582 		/* Silently ignore */ ;
    583 	}
    584 }
    585