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