xref: /netbsd-src/usr.sbin/apmd/apmd.c (revision 76dfffe33547c37f8bdd446e3e4ab0f3c16cea4b)
1 /*	$NetBSD: apmd.c,v 1.4 1996/09/25 00:53:49 jtc 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 
401     sock_fd = bind_socket(sockname, mode, uid, gid);
402 
403     FD_ZERO(&devfds);
404     FD_SET(ctl_fd, &devfds);
405     FD_SET(sock_fd, &devfds);
406 
407     for (selcopy = devfds, errno = 0, stv = tv;
408 	 (ready = select(MAX(ctl_fd,sock_fd)+1, &selcopy, 0, 0, &stv)) >= 0 ||
409 	     errno == EINTR;
410 	 selcopy = devfds, errno = 0, stv = tv) {
411 	if (errno == EINTR)
412 	    continue;
413 	if (ready == 0) {
414 	    /* wakeup for timeout: take status */
415 	    power_status(ctl_fd, 0, 0);
416 	}
417 	if (FD_ISSET(ctl_fd, &selcopy)) {
418 	    suspends = standbys = resumes = 0;
419 	    while (ioctl(ctl_fd, APM_IOC_NEXTEVENT, &apmevent) == 0) {
420 		syslog(LOG_DEBUG, "apmevent %04x index %d", apmevent.type,
421 		       apmevent.index);
422 		switch (apmevent.type) {
423 		case APM_SUSPEND_REQ:
424 		case APM_USER_SUSPEND_REQ:
425 		case APM_CRIT_SUSPEND_REQ:
426 		case APM_BATTERY_LOW:
427 		    suspends++;
428 		    break;
429 		case APM_USER_STANDBY_REQ:
430 		case APM_STANDBY_REQ:
431 		    standbys++;
432 		    break;
433 #if 0
434 		case APM_CANCEL:
435 		    suspends = standbys = 0;
436 		    break;
437 #endif
438 		case APM_NORMAL_RESUME:
439 		case APM_CRIT_RESUME:
440 		case APM_SYS_STANDBY_RESUME:
441 		    resumes++;
442 		    break;
443 		case APM_POWER_CHANGE:
444 		    power_status(ctl_fd, 1, 0);
445 		    break;
446 		default:
447 		    break;
448 		}
449 	    }
450 	    if ((standbys || suspends) && noacsleep &&
451 		power_status(ctl_fd, 0, 0)) {
452 		syslog(LOG_DEBUG, "not sleeping cuz AC is connected");
453 	    } else if (suspends) {
454 		suspend(ctl_fd);
455 	    } else if (standbys) {
456 		stand_by(ctl_fd);
457 	    } else if (resumes) {
458 		resume(ctl_fd);
459 		syslog(LOG_NOTICE, "system resumed from APM sleep");
460 	    }
461 	    ready--;
462 	}
463 	if (ready == 0)
464 	    continue;
465 	if (FD_ISSET(sock_fd, &selcopy)) {
466 	    switch (handle_client(sock_fd, ctl_fd)) {
467 	    case NORMAL:
468 		break;
469 	    case SUSPENDING:
470 		suspend(ctl_fd);
471 		break;
472 	    case STANDING_BY:
473 		stand_by(ctl_fd);
474 		break;
475 	    }
476 	}
477     }
478     syslog(LOG_ERR, "select failed: %m");
479     exit(1);
480 }
481 
482 void
483 do_etc_file(const char *file)
484 {
485     pid_t pid;
486     int status;
487     const char *prog;
488 
489     /* If file doesn't exist, do nothing. */
490     if (access(file, X_OK|R_OK)) {
491 	syslog(LOG_DEBUG, "do_etc_file(): cannot access file %s", file);
492 	return;
493     }
494 
495     prog = strrchr(file, '/');
496     if (prog)
497 	prog++;
498     else
499 	prog = file;
500 
501     pid = fork();
502     switch (pid) {
503     case -1:
504 	syslog(LOG_ERR, "failed to fork(): %m");
505 	return;
506     case 0:
507 	/* We are the child. */
508 	execl(file, prog, NULL);
509 	_exit(-1);
510 	/* NOTREACHED */
511     default:
512 	/* We are the parent. */
513 	wait4(pid, &status, 0, 0);
514 	if (WIFEXITED(status))
515 	    syslog(LOG_DEBUG, "%s exited with status %d", file,
516 		   WEXITSTATUS(status));
517 	else {
518 	    syslog(LOG_ERR, "%s exited abnormally.", file);
519 	}
520 	break;
521     }
522 }
523