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