xref: /openbsd-src/usr.sbin/apmd/apmd.c (revision b2ea75c1b17e1a9a339660e7ed45cd24946b230e)
1 /*	$OpenBSD: apmd.c,v 1.16 2001/07/09 07:05:00 deraadt 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 <stdio.h>
33 #include <syslog.h>
34 #include <fcntl.h>
35 #include <unistd.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <signal.h>
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #include <sys/ioctl.h>
42 #include <sys/socket.h>
43 #include <sys/un.h>
44 #include <sys/wait.h>
45 #include <errno.h>
46 #include <err.h>
47 #include <machine/apmvar.h>
48 #include "pathnames.h"
49 #include "apm-proto.h"
50 
51 #define MAX(a,b) (a > b ? a : b)
52 #define TRUE 1
53 #define FALSE 0
54 
55 const char apmdev[] = _PATH_APM_CTLDEV;
56 const char sockfile[] = _PATH_APM_SOCKET;
57 
58 int debug = 0;
59 
60 extern char *__progname;
61 
62 void usage (void);
63 int power_status (int fd, int force, struct apm_power_info *pinfo);
64 int bind_socket (const char *sn);
65 enum apm_state handle_client(int sock_fd, int ctl_fd);
66 void suspend(int ctl_fd);
67 void stand_by(int ctl_fd);
68 void sigexit(int signo);
69 void make_noise(int howmany);
70 void do_etc_file(const char *file);
71 
72 void
73 sigexit(int signo)
74 {
75     _exit(1);
76 }
77 
78 void
79 usage(void)
80 {
81 	fprintf(stderr,
82 	    "usage: %s [-adempqs] [-f devfile] [-S sockfile] [-t timo]\n",
83 	    __progname);
84 	exit(1);
85 }
86 
87 
88 /*
89  * tell the driver if it should display messages or not.
90  */
91 void
92 set_driver_messages(int fd, int mode)
93 {
94 	if (ioctl(fd, APM_IOC_PRN_CTL, &mode) == -1)
95 		syslog(LOG_DEBUG, "can't disable driver messages, error: %m");
96 }
97 
98 int
99 power_status(int fd, int force, struct apm_power_info *pinfo)
100 {
101 	struct apm_power_info bstate;
102 	static struct apm_power_info last;
103 	int acon = 0;
104 
105 	if (ioctl(fd, APM_IOC_GETPOWER, &bstate) == 0) {
106 	/* various conditions under which we report status:  something changed
107 	 * enough since last report, or asked to force a print */
108 		if (bstate.ac_state == APM_AC_ON)
109 			acon = 1;
110 		if (force ||
111 		    bstate.ac_state != last.ac_state ||
112 		    bstate.battery_state != last.battery_state ||
113 		    (bstate.minutes_left && bstate.minutes_left < 15) ||
114 		     abs(bstate.battery_life - last.battery_life) > 20) {
115 			if (bstate.minutes_left)
116 				syslog(LOG_NOTICE, "battery status: %s. "
117 				    "external power status: %s. "
118 				    "estimated battery life %d%% (%u minutes)",
119 				    battstate(bstate.battery_state),
120 				    ac_state(bstate.ac_state),
121 				    bstate.battery_life,
122 				    bstate.minutes_left);
123 			else
124 				syslog(LOG_NOTICE, "battery status: %s. "
125 				    "external power status: %s. "
126 				    "estimated battery life %d%%",
127 				    battstate(bstate.battery_state),
128 				    ac_state(bstate.ac_state),
129 				    bstate.battery_life);
130 			last = bstate;
131 		}
132 		if (pinfo)
133 			*pinfo = bstate;
134 	} else
135 		syslog(LOG_ERR, "cannot fetch power status: %m");
136 
137 	return acon;
138 }
139 
140 char *socketname;
141 
142 void
143 sockunlink(void)
144 {
145 	if (socketname)
146 		remove(socketname);
147 }
148 
149 int
150 bind_socket(const char *sockname)
151 {
152 	struct sockaddr_un s_un;
153 	int sock;
154 
155 	sock = socket(AF_UNIX, SOCK_STREAM, 0);
156 	if (sock == -1)
157 		err(1, "cannot create local socket");
158 
159 	s_un.sun_family = AF_UNIX;
160 	strncpy(s_un.sun_path, sockname, sizeof(s_un.sun_path));
161 	s_un.sun_len = SUN_LEN(&s_un);
162 
163 	/* remove it if present, we're moving in */
164 	(void) remove(sockname);
165 	umask (077);
166 
167 	if (bind(sock, (struct sockaddr *)&s_un, s_un.sun_len) == -1)
168 		err(1, "cannot connect to APM socket");
169 	if (chmod(sockname, 0660) == -1 || chown(sockname, 0, 0) == -1)
170 		err(1, "cannot set socket mode/owner/group to 660/0/0");
171 
172 	listen(sock, 1);
173 	socketname = strdup(sockname);
174 	atexit(sockunlink);
175 
176 	return sock;
177 }
178 
179 enum apm_state
180 handle_client(int sock_fd, int ctl_fd)
181 {
182 	/* accept a handle from the client, process it, then clean up */
183 	int cli_fd;
184 	struct sockaddr_un from;
185 	int fromlen;
186 	struct apm_command cmd;
187 	struct apm_reply reply;
188 
189 	cli_fd = accept(sock_fd, (struct sockaddr *)&from, &fromlen);
190 	if (cli_fd == -1) {
191 		syslog(LOG_INFO, "client accept failure: %m");
192 		return NORMAL;
193 	}
194 
195 	if (recv(cli_fd, &cmd, sizeof(cmd), 0) != sizeof(cmd)) {
196 		(void) close(cli_fd);
197 		syslog(LOG_INFO, "client size botch");
198 		return NORMAL;
199 	}
200 
201 	if (cmd.vno != APMD_VNO) {
202 		close(cli_fd);			/* terminate client */
203 		/* no error message, just drop it. */
204 		return NORMAL;
205 	}
206 
207 	power_status(ctl_fd, 0, &reply.batterystate);
208 	switch (cmd.action) {
209 	case SUSPEND:	reply.newstate = SUSPENDING;	break;
210 	case STANDBY:	reply.newstate = STANDING_BY;	break;
211 	default:	reply.newstate = NORMAL;	break;
212 	}
213 
214 	reply.vno = APMD_VNO;
215 	if (send(cli_fd, &reply, sizeof(reply), 0) != sizeof(reply))
216 		syslog(LOG_INFO, "client reply botch");
217 	close(cli_fd);
218 
219 	return reply.newstate;
220 }
221 
222 int speaker_ok = TRUE;
223 
224 void
225 make_noise(howmany)
226 int howmany;
227 {
228 	int spkrfd = -1;
229 	int trycnt;
230 
231 	if (!speaker_ok)		/* don't bother after sticky errors */
232 		return;
233 
234 	for (trycnt = 0; trycnt < 3; trycnt++) {
235 		spkrfd = open(_PATH_DEV_SPEAKER, O_WRONLY);
236 		if (spkrfd == -1) {
237 			switch (errno) {
238 			case EBUSY:
239 				usleep(500000);
240 				errno = EBUSY;
241 				continue;
242 			case ENOENT:
243 			case ENODEV:
244 			case ENXIO:
245 			case EPERM:
246 			case EACCES:
247 				syslog(LOG_WARNING, "speaker device "
248 				    _PATH_DEV_SPEAKER " unavailable: %m");
249 				speaker_ok = FALSE;
250 				return;
251 			}
252 		} else
253 			break;
254 	}
255 
256 	if (spkrfd == -1) {
257 		syslog(LOG_WARNING, "cannot open " _PATH_DEV_SPEAKER ": %m");
258 		return;
259 	}
260 
261 	syslog(LOG_DEBUG, "sending %d tones to speaker", howmany);
262 	write(spkrfd, "o4cc", 2 + howmany);
263 	close(spkrfd);
264 }
265 
266 void
267 suspend(int ctl_fd)
268 {
269 	do_etc_file(_PATH_APM_ETC_SUSPEND);
270 	sync();
271 	make_noise(2);
272 	sync();
273 	sync();
274 	sleep(1);
275 	ioctl(ctl_fd, APM_IOC_SUSPEND, 0);
276 }
277 
278 void
279 stand_by(int ctl_fd)
280 {
281 	do_etc_file(_PATH_APM_ETC_STANDBY);
282 	sync();
283 	make_noise(1);
284 	sync();
285 	sync();
286 	sleep(1);
287 	ioctl(ctl_fd, APM_IOC_STANDBY, 0);
288 }
289 
290 #define TIMO (10*60)			/* 10 minutes */
291 
292 int
293 main(int argc, char *argv[])
294 {
295 	const char *fname = apmdev;
296 	int ctl_fd, sock_fd, ch, ready, fdsn, suspends, standbys, resumes;
297 	int statonly = 0;
298 	int enableonly = 0;
299 	int pctonly = 0;
300 	int powerstatus = 0, powerbak = 0, powerchange = 0;
301 	int messages = 0;
302 	int noacsleep = 0;
303 	fd_set *devfdsp, *selfdsp;
304 	struct apm_event_info apmevent;
305 	struct timeval tv = {TIMO, 0}, stv;
306 	const char *sockname = sockfile;
307 
308 	while ((ch = getopt(argc, argv, "qadsepmf:t:S:")) != -1)
309 		switch(ch) {
310 		case 'q':
311 			speaker_ok = FALSE;
312 			break;
313 		case 'a':
314 			noacsleep = 1;
315 			break;
316 		case 'd':
317 			debug = 1;
318 			break;
319 		case 'f':
320 			fname = optarg;
321 			break;
322 		case 'S':
323 			sockname = optarg;
324 			break;
325 		case 't':
326 			tv.tv_sec = strtoul(optarg, NULL, 0);
327 			if (tv.tv_sec == 0)
328 				usage();
329 			break;
330 		case 's':	/* status only */
331 			statonly = 1;
332 			break;
333 		case 'e':
334 			enableonly = 1;
335 			break;
336 		case 'p':
337 			pctonly = 1;
338 			break;
339 		case 'm':
340 			messages = 1;
341 			break;
342 		case '?':
343 		default:
344 			usage();
345 		}
346 
347 	argc -= optind;
348 	argv += optind;
349 
350 	if ((ctl_fd = open(fname, O_RDWR)) == -1)
351 		err(1, "cannot open device file `%s'", fname);
352 
353 	if (debug)
354 		openlog(__progname, LOG_CONS, LOG_LOCAL1);
355 	else {
356 		openlog(__progname, LOG_CONS, LOG_DAEMON);
357 		setlogmask(LOG_UPTO(LOG_NOTICE));
358 		daemon(0, 0);
359 	}
360 
361 	power_status(ctl_fd, 1, 0);
362 
363 	if (statonly)
364 		exit(0);
365 
366 	if (enableonly) {
367 		set_driver_messages(ctl_fd, APM_PRINT_ON);
368 		exit(0);
369 	}
370 
371 	if (pctonly) {
372 		set_driver_messages(ctl_fd, APM_PRINT_PCT);
373 		exit(0);
374 	}
375 
376 	if (!messages)
377 		set_driver_messages(ctl_fd, APM_PRINT_OFF);
378 
379 	(void) signal(SIGTERM, sigexit);
380 	(void) signal(SIGHUP, sigexit);
381 	(void) signal(SIGINT, sigexit);
382 
383 	sock_fd = bind_socket(sockname);
384 	fdsn = howmany(MAX(ctl_fd, sock_fd)+1, NFDBITS) * sizeof(fd_mask);
385 	if ((devfdsp = (fd_set *)malloc(fdsn)) == NULL)
386 		err(1, "malloc");
387 
388 	if ((selfdsp = (fd_set *)malloc(fdsn)) == NULL)
389 		err(1, "malloc");
390 
391 	memset(devfdsp, 0, fdsn);
392 	FD_SET(ctl_fd, devfdsp);
393 	FD_SET(sock_fd, devfdsp);
394 
395 	for (;;) {
396 		stv = tv;
397 		memmove(selfdsp, devfdsp, fdsn);
398 
399 		ready = select(MAX(ctl_fd,sock_fd)+1, selfdsp, 0, 0, &stv);
400 		if (ready == -1 && errno != EINTR)
401 			continue;
402 
403 		if (ready == 0) {
404 			/* wakeup for timeout: take status */
405 			powerbak = power_status(ctl_fd, 0, 0);
406 			if (powerstatus != powerbak) {
407 				powerstatus = powerbak;
408 				powerchange = 1;
409 			}
410 		}
411 
412 		if (FD_ISSET(ctl_fd, selfdsp)) {
413 			suspends = standbys = resumes = 0;
414 			while (!ioctl(ctl_fd, APM_IOC_NEXTEVENT, &apmevent)) {
415 
416 				syslog(LOG_DEBUG, "apmevent %04x index %d",
417 				    apmevent.type, apmevent.index);
418 
419 				switch (apmevent.type) {
420 				case APM_SUSPEND_REQ:
421 				case APM_USER_SUSPEND_REQ:
422 				case APM_CRIT_SUSPEND_REQ:
423 				case APM_BATTERY_LOW:
424 					suspends++;
425 					break;
426 				case APM_USER_STANDBY_REQ:
427 				case APM_STANDBY_REQ:
428 					standbys++;
429 					break;
430 #if 0
431 				case APM_CANCEL:
432 					suspends = standbys = 0;
433 					break;
434 #endif
435 				case APM_NORMAL_RESUME:
436 				case APM_CRIT_RESUME:
437 				case APM_SYS_STANDBY_RESUME:
438 					powerbak = power_status(ctl_fd, 0, 0);
439 					if (powerstatus != powerbak) {
440 						powerstatus = powerbak;
441 						powerchange = 1;
442 					}
443 					resumes++;
444 					break;
445 				case APM_POWER_CHANGE:
446 					powerbak = power_status(ctl_fd, 0, 0);
447 					if (powerstatus != powerbak) {
448 						powerstatus = powerbak;
449 						powerchange = 1;
450 					}
451 					break;
452 				default:
453 				}
454 			}
455 
456 			if ((standbys || suspends) && noacsleep &&
457 			    power_status(ctl_fd, 0, 0))
458 				syslog(LOG_DEBUG, "no sleep till brooklyn");
459 			else if (suspends)
460 				suspend(ctl_fd);
461 			else if (standbys)
462 				stand_by(ctl_fd);
463 			else if (resumes) {
464 				do_etc_file(_PATH_APM_ETC_RESUME);
465 				syslog(LOG_NOTICE,
466 				    "system resumed from APM sleep");
467 			}
468 
469 			if (powerchange) {
470 				if (powerstatus)
471 					do_etc_file(_PATH_APM_ETC_POWERUP);
472 				else
473 					do_etc_file(_PATH_APM_ETC_POWERDOWN);
474 				powerchange = 0;
475 			}
476 			ready--;
477 		}
478 
479 		if (ready == 0)
480 			continue;
481 
482 		if (FD_ISSET(sock_fd, selfdsp))
483 			switch (handle_client(sock_fd, ctl_fd)) {
484 			case NORMAL:
485 				break;
486 			case SUSPENDING:
487 				suspend(ctl_fd);
488 				break;
489 			case STANDING_BY:
490 				stand_by(ctl_fd);
491 				break;
492 			}
493 	}
494 	syslog(LOG_ERR, "select failed: %m");
495 
496 	return 1;
497 }
498 
499 void
500 do_etc_file(const char *file)
501 {
502 	pid_t pid;
503 	int status;
504 	const char *prog;
505 
506 	/* If file doesn't exist, do nothing. */
507 	if (access(file, X_OK|R_OK)) {
508 		syslog(LOG_DEBUG, "do_etc_file(): cannot access file %s", file);
509 		return;
510 	}
511 
512 	prog = strrchr(file, '/');
513 	if (prog)
514 		prog++;
515 	else
516 		prog = file;
517 
518 	pid = fork();
519 	switch (pid) {
520 	case -1:
521 		syslog(LOG_ERR, "failed to fork(): %m");
522 		return;
523 	case 0:
524 		/* We are the child. */
525 		execl(file, prog, (char *)NULL);
526 		_exit(1);
527 		/* NOTREACHED */
528 	default:
529 		/* We are the parent. */
530 		wait4(pid, &status, 0, 0);
531 		if (WIFEXITED(status))
532 			syslog(LOG_DEBUG, "%s exited with status %d", file,
533 			    WEXITSTATUS(status));
534 		else
535 			syslog(LOG_ERR, "%s exited abnormally.", file);
536 	}
537 }
538