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