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