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