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