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