1 /* $NetBSD: apmd.c,v 1.32 2011/11/25 12:51:27 joerg Exp $ */
2
3 /*-
4 * Copyright (c) 1996, 2000 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 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 #include <stdio.h>
33 #include <errno.h>
34 #include <syslog.h>
35 #include <fcntl.h>
36 #include <unistd.h>
37 #include <util.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <signal.h>
41 #include <sys/types.h>
42 #include <pwd.h>
43 #include <grp.h>
44 #include <sys/stat.h>
45 #include <sys/ioctl.h>
46 #include <sys/time.h>
47 #include <sys/socket.h>
48 #include <sys/un.h>
49 #include <sys/wait.h>
50 #include <poll.h>
51 #include <machine/apmvar.h>
52 #include <err.h>
53 #include "pathnames.h"
54 #include "apm-proto.h"
55
56 #define TRUE 1
57 #define FALSE 0
58
59 #define POWER_STATUS_ACON 0x1
60 #define POWER_STATUS_LOWBATTNOW 0x2
61
62 static const char apmdev[] = _PATH_APM_CTLDEV;
63 static const char sockfile[] = _PATH_APM_SOCKET;
64
65 static int debug = 0;
66 static int verbose = 0;
67
68 __dead static void usage (void);
69 static int power_status (int fd, int force, struct apm_power_info *pinfo);
70 static int bind_socket (const char *sn, mode_t mode, uid_t uid, gid_t gid);
71 static enum apm_state handle_client(int sock_fd, int ctl_fd);
72 static void suspend(int ctl_fd);
73 static void stand_by(int ctl_fd);
74 static void resume(int ctl_fd);
75 __dead static void sigexit(int signo);
76 static void make_noise(int howmany);
77 static void do_etc_file(const char *file);
78 static void do_ac_state(int state);
79
80 static void
sigexit(int signo)81 sigexit(int signo)
82 {
83 exit(1);
84 }
85
86 static void
usage(void)87 usage(void)
88 {
89 fprintf(stderr,"usage: %s [-adlqsv] [-t seconds] [-S sockname]\n\t[-m sockmode] [-o sockowner:sockgroup] [-f devname]\n", getprogname());
90 exit(1);
91 }
92
93
94 static int
power_status(int fd,int force,struct apm_power_info * pinfo)95 power_status(int fd, int force, struct apm_power_info *pinfo)
96 {
97 struct apm_power_info bstate;
98 static struct apm_power_info last;
99 int acon = 0;
100 int lowbattnow = 0;
101
102 memset(&bstate, 0, sizeof(bstate));
103 if (ioctl(fd, APM_IOC_GETPOWER, &bstate) == 0) {
104 /* various conditions under which we report status: something changed
105 enough since last report, or asked to force a print */
106 if (bstate.ac_state == APM_AC_ON)
107 acon = 1;
108 if (bstate.battery_state != last.battery_state &&
109 bstate.battery_state == APM_BATT_LOW)
110 lowbattnow = 1;
111 if (force ||
112 bstate.ac_state != last.ac_state ||
113 bstate.battery_state != last.battery_state ||
114 (bstate.minutes_left && bstate.minutes_left < 15) ||
115 abs(bstate.battery_life - last.battery_life) > 20) {
116 if (verbose) {
117 if (bstate.minutes_left)
118 syslog(LOG_NOTICE,
119 "battery status: %s. external power status: %s. "
120 "estimated battery life %d%% (%d minutes)",
121 battstate(bstate.battery_state),
122 ac_state(bstate.ac_state), bstate.battery_life,
123 bstate.minutes_left);
124 else
125 syslog(LOG_NOTICE,
126 "battery status: %s. external power status: %s. "
127 "estimated battery life %d%%",
128 battstate(bstate.battery_state),
129 ac_state(bstate.ac_state), bstate.battery_life);
130 }
131 last = bstate;
132 }
133 if (pinfo)
134 *pinfo = bstate;
135 } else
136 syslog(LOG_ERR, "cannot fetch power status: %m");
137 return ((acon?POWER_STATUS_ACON:0) |
138 (lowbattnow?POWER_STATUS_LOWBATTNOW:0));
139 }
140
141 static char *socketname;
142
143 static void sockunlink(void);
144
145 static void
sockunlink(void)146 sockunlink(void)
147 {
148 if (socketname)
149 (void) remove(socketname);
150 }
151
152 static int
bind_socket(const char * sockname,mode_t mode,uid_t uid,gid_t gid)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 static enum apm_state
handle_client(int sock_fd,int ctl_fd)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 socklen_t 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 static void
make_noise(int howmany)226 make_noise(int howmany)
227 {
228 int spkrfd;
229 int trycnt;
230
231 if (!speaker_ok) /* don't bother after sticky errors */
232 return;
233
234 for (trycnt = 0; trycnt < 3; trycnt++) {
235 spkrfd = open(_PATH_DEV_SPEAKER, O_WRONLY);
236 if (spkrfd == -1) {
237 switch (errno) {
238 case EBUSY:
239 usleep(500000);
240 errno = EBUSY;
241 continue;
242 case ENOENT:
243 case ENODEV:
244 case ENXIO:
245 case EPERM:
246 case EACCES:
247 syslog(LOG_INFO,
248 "speaker device " _PATH_DEV_SPEAKER " unavailable: %m");
249 speaker_ok = FALSE;
250 return;
251 }
252 } else
253 break;
254 }
255 if (spkrfd == -1) {
256 syslog(LOG_WARNING, "cannot open " _PATH_DEV_SPEAKER ": %m");
257 return;
258 }
259 syslog(LOG_DEBUG, "sending %d tones to speaker\n", howmany);
260 write (spkrfd, "o4cc", 2 + howmany);
261 close(spkrfd);
262 return;
263 }
264
265
266 static void
suspend(int ctl_fd)267 suspend(int ctl_fd)
268 {
269 do_etc_file(_PATH_APM_ETC_SUSPEND);
270 sync();
271 make_noise(2);
272 sync();
273 sync();
274 sleep(1);
275 ioctl(ctl_fd, APM_IOC_SUSPEND, 0);
276 }
277
278 static void
stand_by(int ctl_fd)279 stand_by(int ctl_fd)
280 {
281 do_etc_file(_PATH_APM_ETC_STANDBY);
282 sync();
283 make_noise(1);
284 sync();
285 sync();
286 sleep(1);
287 ioctl(ctl_fd, APM_IOC_STANDBY, 0);
288 }
289
290 #define TIMO (10*60) /* 10 minutes */
291
292 static void
resume(int ctl_fd)293 resume(int ctl_fd)
294 {
295 do_etc_file(_PATH_APM_ETC_RESUME);
296 }
297
298 int
main(int argc,char * argv[])299 main(int argc, char *argv[])
300 {
301 const char *fname = apmdev;
302 int ctl_fd, sock_fd, ch, ready;
303 int statonly = 0;
304 struct pollfd set[2];
305 struct apm_event_info apmevent;
306 int suspends, standbys, resumes;
307 int ac_is_off;
308 int noacsleep = 0;
309 int lowbattsleep = 0;
310 mode_t mode = 0660;
311 unsigned long timeout = TIMO;
312 const char *sockname = sockfile;
313 char *user, *group;
314 char *scratch;
315 uid_t uid = 2; /* operator */
316 gid_t gid = 5; /* operator */
317 struct passwd *pw;
318 struct group *gr;
319
320 while ((ch = getopt(argc, argv, "adlqsvf: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 'l':
329 lowbattsleep = 1;
330 break;
331 case 'd':
332 debug = 1;
333 break;
334 case 'v':
335 verbose = 1;
336 break;
337 case 'f':
338 fname = optarg;
339 break;
340 case 'S':
341 sockname = optarg;
342 break;
343 case 't':
344 timeout = strtoul(optarg, 0, 0);
345 if (timeout == 0)
346 usage();
347 break;
348 case 'm':
349 mode = strtoul(optarg, 0, 8);
350 if (mode == 0)
351 usage();
352 break;
353 case 'o':
354 /* (user):(group) */
355 user = optarg;
356 group = strchr(user, ':');
357 if (group)
358 *group++ = '\0';
359 if (*user) {
360 uid = strtoul(user, &scratch, 0);
361 if (*scratch != '\0') {
362 pw = getpwnam(user);
363 if (pw)
364 uid = pw->pw_uid;
365 else
366 errx(1, "user name `%s' unknown", user);
367 }
368 }
369 if (group && *group) {
370 gid = strtoul(group, &scratch, 0);
371 if (*scratch != '\0') {
372 gr = getgrnam(group);
373 if (gr)
374 gid = gr->gr_gid;
375 else
376 errx(1, "group name `%s' unknown", group);
377 }
378 }
379 break;
380 case 's': /* status only */
381 statonly = 1;
382 break;
383 case '?':
384
385 default:
386 usage();
387 }
388 argc -= optind;
389 argv += optind;
390 if (debug) {
391 openlog("apmd", 0, LOG_LOCAL1);
392 } else {
393 daemon(0, 0);
394 openlog("apmd", 0, LOG_DAEMON);
395 setlogmask(LOG_UPTO(LOG_NOTICE));
396 pidfile(NULL);
397 }
398 if ((ctl_fd = open(fname, O_RDWR)) == -1) {
399 syslog(LOG_ERR, "cannot open device file `%s'", fname);
400 exit(1);
401 }
402
403 if (statonly) {
404 power_status(ctl_fd, 1, 0);
405 exit(0);
406 } else {
407 struct apm_power_info pinfo;
408 power_status(ctl_fd, 1, &pinfo);
409 do_ac_state(pinfo.ac_state);
410 ac_is_off = (pinfo.ac_state == APM_AC_OFF);
411 }
412
413 (void) signal(SIGTERM, sigexit);
414 (void) signal(SIGHUP, sigexit);
415 (void) signal(SIGINT, sigexit);
416 (void) signal(SIGPIPE, SIG_IGN);
417
418
419 sock_fd = bind_socket(sockname, mode, uid, gid);
420
421 set[0].fd = ctl_fd;
422 set[0].events = POLLIN;
423 set[1].fd = sock_fd;
424 set[1].events = POLLIN;
425
426
427 for (errno = 0;
428 (ready = poll(set, 2, timeout * 1000)) >= 0 || errno == EINTR;
429 errno = 0) {
430 if (errno == EINTR)
431 continue;
432 if (ready == 0) {
433 int status;
434 /* wakeup for timeout: take status */
435 status = power_status(ctl_fd, 0, 0);
436 if (lowbattsleep && status&POWER_STATUS_LOWBATTNOW) {
437 if (noacsleep && status&POWER_STATUS_ACON) {
438 if (debug)
439 syslog(LOG_DEBUG,
440 "not sleeping because "
441 "AC is connected");
442 } else
443 suspend(ctl_fd);
444 }
445 }
446 if (set[0].revents & POLLIN) {
447 suspends = standbys = resumes = 0;
448 while (ioctl(ctl_fd, APM_IOC_NEXTEVENT, &apmevent) == 0) {
449 if (debug)
450 syslog(LOG_DEBUG, "apmevent %04x index %d", apmevent.type,
451 apmevent.index);
452 switch (apmevent.type) {
453 case APM_SUSPEND_REQ:
454 case APM_USER_SUSPEND_REQ:
455 case APM_CRIT_SUSPEND_REQ:
456 suspends++;
457 break;
458 case APM_BATTERY_LOW:
459 if (lowbattsleep)
460 suspends++;
461 break;
462 case APM_USER_STANDBY_REQ:
463 case APM_STANDBY_REQ:
464 standbys++;
465 break;
466 #if 0
467 case APM_CANCEL:
468 suspends = standbys = 0;
469 break;
470 #endif
471 case APM_NORMAL_RESUME:
472 case APM_CRIT_RESUME:
473 case APM_SYS_STANDBY_RESUME:
474 resumes++;
475 break;
476 case APM_POWER_CHANGE:
477 {
478 struct apm_power_info pinfo;
479 power_status(ctl_fd, 0, &pinfo);
480 /* power status can change without ac status changing */
481 if (ac_is_off != (pinfo.ac_state == APM_AC_OFF)) {
482 do_ac_state(pinfo.ac_state);
483 ac_is_off = (pinfo.ac_state == APM_AC_OFF);
484 }
485 break;
486 }
487 default:
488 break;
489 }
490 }
491 if ((standbys || suspends) && noacsleep &&
492 (power_status(ctl_fd, 0, 0) & POWER_STATUS_ACON)) {
493 if (debug)
494 syslog(LOG_DEBUG, "not sleeping because AC is connected");
495 } else if (suspends) {
496 suspend(ctl_fd);
497 } else if (standbys) {
498 stand_by(ctl_fd);
499 } else if (resumes) {
500 resume(ctl_fd);
501 if (verbose)
502 syslog(LOG_NOTICE, "system resumed from APM sleep");
503 }
504 ready--;
505 }
506 if (ready == 0)
507 continue;
508 if (set[1].revents & POLLIN) {
509 switch (handle_client(sock_fd, ctl_fd)) {
510 case NORMAL:
511 break;
512 case SUSPENDING:
513 suspend(ctl_fd);
514 break;
515 case STANDING_BY:
516 stand_by(ctl_fd);
517 break;
518 }
519 }
520 }
521 syslog(LOG_ERR, "poll failed: %m");
522 exit(1);
523 }
524
525 static void
do_etc_file(const char * file)526 do_etc_file(const char *file)
527 {
528 pid_t pid;
529 int status;
530 const char *prog;
531
532 /* If file doesn't exist, do nothing. */
533 if (access(file, X_OK|R_OK)) {
534 if (debug)
535 syslog(LOG_DEBUG, "do_etc_file(): cannot access file %s", file);
536 return;
537 }
538
539 prog = strrchr(file, '/');
540 if (prog)
541 prog++;
542 else
543 prog = file;
544
545 pid = fork();
546 switch (pid) {
547 case -1:
548 syslog(LOG_ERR, "failed to fork(): %m");
549 return;
550 case 0:
551 /* We are the child. */
552 if (execl(file, prog, NULL) == -1)
553 syslog(LOG_ERR, "could not execute \"%s\": %m", file);
554 _exit(1);
555 /* NOTREACHED */
556 default:
557 /* We are the parent. */
558 wait4(pid, &status, 0, 0);
559 if (WIFEXITED(status)) {
560 if (debug)
561 syslog(LOG_DEBUG, "%s exited with status %d", file,
562 WEXITSTATUS(status));
563 } else
564 syslog(LOG_ERR, "%s exited abnormally.", file);
565 break;
566 }
567 }
568
569 static void
do_ac_state(int state)570 do_ac_state(int state)
571 {
572 switch (state) {
573 case APM_AC_OFF:
574 do_etc_file(_PATH_APM_ETC_BATTERY);
575 break;
576 case APM_AC_ON:
577 case APM_AC_BACKUP:
578 do_etc_file(_PATH_APM_ETC_LINE);
579 break;
580 default:
581 /* Silently ignore */ ;
582 }
583 }
584