xref: /netbsd-src/usr.sbin/apmd/apmd.c (revision d0fed6c87ddc40a8bffa6f99e7433ddfc864dd83)
1 /*	$NetBSD: apmd.c,v 1.5 1997/03/01 19:10:49 jtk 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 REGENTS OR CONTRIBUTORS BE
30  * 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 <stdlib.h>
45 #include <string.h>
46 #include <signal.h>
47 #include <sys/types.h>
48 #include <pwd.h>
49 #include <grp.h>
50 #include <sys/stat.h>
51 #include <sys/ioctl.h>
52 #include <sys/time.h>
53 #include <sys/socket.h>
54 #include <sys/un.h>
55 #include <sys/wait.h>
56 #include <machine/apmvar.h>
57 #include <err.h>
58 #include "pathnames.h"
59 #include "apm-proto.h"
60 
61 #define MAX(a,b) (a > b ? a : b)
62 #define TRUE 1
63 #define FALSE 0
64 
65 const char apmdev[] = _PATH_APM_CTLDEV;
66 const char sockfile[] = _PATH_APM_SOCKET;
67 
68 static int debug = 0;
69 
70 extern char *__progname;
71 extern char *optarg;
72 extern int optind;
73 extern int optopt;
74 extern int opterr;
75 extern int optreset;
76 
77 void usage (void);
78 int power_status (int fd, int force, struct apm_power_info *pinfo);
79 int bind_socket (const char *sn, mode_t mode, uid_t uid, gid_t gid);
80 enum apm_state handle_client(int sock_fd, int ctl_fd);
81 void suspend(int ctl_fd);
82 void stand_by(int ctl_fd);
83 void resume(int ctl_fd);
84 void sigexit(int signo);
85 void make_noise(int howmany);
86 void do_etc_file(const char *file);
87 
88 void
89 sigexit(int signo)
90 {
91     exit(1);
92 }
93 
94 void
95 usage(void)
96 {
97     fprintf(stderr,"usage: %s [-d] [-t timo] [-s] [-a] [-f devfile] [-S sockfile]\n\t[-m sockmode] [-o sockowner]\n", __progname);
98     exit(1);
99 }
100 
101 
102 int
103 power_status(int fd, int force, struct apm_power_info *pinfo)
104 {
105     struct apm_power_info bstate;
106     static struct apm_power_info last;
107     int acon = 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 (force ||
115 	    bstate.ac_state != last.ac_state ||
116 	    bstate.battery_state != last.battery_state ||
117 	    (bstate.minutes_left && bstate.minutes_left < 15) ||
118 	    abs(bstate.battery_life - last.battery_life) > 20) {
119 	    if (bstate.minutes_left)
120 		syslog(LOG_NOTICE,
121 		       "battery status: %s. external power status: %s. "
122 		       "estimated battery life %d%% (%d minutes)",
123 		       battstate(bstate.battery_state),
124 		       ac_state(bstate.ac_state), bstate.battery_life,
125 		       bstate.minutes_left);
126 	    else
127 		syslog(LOG_NOTICE,
128 		       "battery status: %s. external power status: %s. "
129 		       "estimated battery life %d%%",
130 		       battstate(bstate.battery_state),
131 		       ac_state(bstate.ac_state), bstate.battery_life);
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_UNIX, SOCK_STREAM, 0);
159     if (sock == -1)
160 	err(1, "cannot create local socket");
161 
162     s_un.sun_family = AF_UNIX;
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 void
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     mode_t mode = 0660;
311     struct timeval tv = {TIMO, 0}, stv;
312     const char *sockname = sockfile;
313     char *user, *group;
314     char *scratch;
315     uid_t uid = 0;
316     gid_t gid = 0;
317     struct passwd *pw;
318     struct group *gr;
319 
320     while ((ch = getopt(argc, argv, "qadsf:t:S:m:o:")) != -1)
321 	switch(ch) {
322 	case 'q':
323 	    speaker_ok = FALSE;
324 	    break;
325 	case 'a':
326 	    noacsleep = 1;
327 	    break;
328 	case 'd':
329 	    debug = 1;
330 	    break;
331 	case 'f':
332 	    fname = optarg;
333 	    break;
334 	case 'S':
335 	    sockname = optarg;
336 	    break;
337 	case 't':
338 	    tv.tv_sec = strtoul(optarg, 0, 0);
339 	    if (tv.tv_sec == 0)
340 		usage();
341 	    break;
342 	case 'm':
343 	    mode = strtoul(optarg, 0, 8);
344 	    if (mode == 0)
345 		usage();
346 	    break;
347 	case 'o':
348 	    /* (user):(group) */
349 	    user = optarg;
350 	    group = strchr(user, ':');
351 	    if (group)
352 		*group++ = '\0';
353 	    if (*user) {
354 		uid = strtoul(user, &scratch, 0);
355 		if (*scratch != '\0') {
356 		    pw = getpwnam(user);
357 		    if (pw)
358 			uid = pw->pw_uid;
359 		    else
360 			errx(1, "user name `%s' unknown", user);
361 		}
362 	    }
363 	    if (group && *group) {
364 		gid = strtoul(group, &scratch, 0);
365 		if (*scratch != '\0') {
366 		    gr = getgrnam(group);
367 		    if (gr)
368 			gid = gr->gr_gid;
369 		    else
370 			errx(1, "group name `%s' unknown", group);
371 		}
372 	    }
373 	    break;
374 	case 's':			/* status only */
375 	    statonly = 1;
376 	    break;
377 	case '?':
378 
379 	default:
380 	    usage();
381 	}
382     argc -= optind;
383     argv += optind;
384     if ((ctl_fd = open(fname, O_RDWR)) == -1) {
385 	(void)err(1, "cannot open device file `%s'", fname);
386     }
387     if (debug) {
388 	openlog(__progname, LOG_CONS, LOG_LOCAL1);
389     } else {
390 	openlog(__progname, LOG_CONS, LOG_DAEMON);
391 	setlogmask(LOG_UPTO(LOG_NOTICE));
392 	daemon(0, 0);
393     }
394     power_status(ctl_fd, 1, 0);
395     if (statonly)
396 	exit(0);
397     (void) signal(SIGTERM, sigexit);
398     (void) signal(SIGHUP, sigexit);
399     (void) signal(SIGINT, sigexit);
400     (void) signal(SIGPIPE, SIG_IGN);
401 
402     sock_fd = bind_socket(sockname, mode, uid, gid);
403 
404     FD_ZERO(&devfds);
405     FD_SET(ctl_fd, &devfds);
406     FD_SET(sock_fd, &devfds);
407 
408     for (selcopy = devfds, errno = 0, stv = tv;
409 	 (ready = select(MAX(ctl_fd,sock_fd)+1, &selcopy, 0, 0, &stv)) >= 0 ||
410 	     errno == EINTR;
411 	 selcopy = devfds, errno = 0, stv = tv) {
412 	if (errno == EINTR)
413 	    continue;
414 	if (ready == 0) {
415 	    /* wakeup for timeout: take status */
416 	    power_status(ctl_fd, 0, 0);
417 	}
418 	if (FD_ISSET(ctl_fd, &selcopy)) {
419 	    suspends = standbys = resumes = 0;
420 	    while (ioctl(ctl_fd, APM_IOC_NEXTEVENT, &apmevent) == 0) {
421 		syslog(LOG_DEBUG, "apmevent %04x index %d", apmevent.type,
422 		       apmevent.index);
423 		switch (apmevent.type) {
424 		case APM_SUSPEND_REQ:
425 		case APM_USER_SUSPEND_REQ:
426 		case APM_CRIT_SUSPEND_REQ:
427 		case APM_BATTERY_LOW:
428 		    suspends++;
429 		    break;
430 		case APM_USER_STANDBY_REQ:
431 		case APM_STANDBY_REQ:
432 		    standbys++;
433 		    break;
434 #if 0
435 		case APM_CANCEL:
436 		    suspends = standbys = 0;
437 		    break;
438 #endif
439 		case APM_NORMAL_RESUME:
440 		case APM_CRIT_RESUME:
441 		case APM_SYS_STANDBY_RESUME:
442 		    resumes++;
443 		    break;
444 		case APM_POWER_CHANGE:
445 		    power_status(ctl_fd, 1, 0);
446 		    break;
447 		default:
448 		    break;
449 		}
450 	    }
451 	    if ((standbys || suspends) && noacsleep &&
452 		power_status(ctl_fd, 0, 0)) {
453 		syslog(LOG_DEBUG, "not sleeping cuz AC is connected");
454 	    } else if (suspends) {
455 		suspend(ctl_fd);
456 	    } else if (standbys) {
457 		stand_by(ctl_fd);
458 	    } else if (resumes) {
459 		resume(ctl_fd);
460 		syslog(LOG_NOTICE, "system resumed from APM sleep");
461 	    }
462 	    ready--;
463 	}
464 	if (ready == 0)
465 	    continue;
466 	if (FD_ISSET(sock_fd, &selcopy)) {
467 	    switch (handle_client(sock_fd, ctl_fd)) {
468 	    case NORMAL:
469 		break;
470 	    case SUSPENDING:
471 		suspend(ctl_fd);
472 		break;
473 	    case STANDING_BY:
474 		stand_by(ctl_fd);
475 		break;
476 	    }
477 	}
478     }
479     syslog(LOG_ERR, "select failed: %m");
480     exit(1);
481 }
482 
483 void
484 do_etc_file(const char *file)
485 {
486     pid_t pid;
487     int status;
488     const char *prog;
489 
490     /* If file doesn't exist, do nothing. */
491     if (access(file, X_OK|R_OK)) {
492 	syslog(LOG_DEBUG, "do_etc_file(): cannot access file %s", file);
493 	return;
494     }
495 
496     prog = strrchr(file, '/');
497     if (prog)
498 	prog++;
499     else
500 	prog = file;
501 
502     pid = fork();
503     switch (pid) {
504     case -1:
505 	syslog(LOG_ERR, "failed to fork(): %m");
506 	return;
507     case 0:
508 	/* We are the child. */
509 	execl(file, prog, NULL);
510 	_exit(-1);
511 	/* NOTREACHED */
512     default:
513 	/* We are the parent. */
514 	wait4(pid, &status, 0, 0);
515 	if (WIFEXITED(status))
516 	    syslog(LOG_DEBUG, "%s exited with status %d", file,
517 		   WEXITSTATUS(status));
518 	else {
519 	    syslog(LOG_ERR, "%s exited abnormally.", file);
520 	}
521 	break;
522     }
523 }
524