xref: /netbsd-src/usr.sbin/apmd/apmd.c (revision 81b108b45f75f89f1e3ffad9fb6f074e771c0935)
1 /*	$NetBSD: apmd.c,v 1.2 1996/09/13 01:10:15 jtk Exp $	*/
2 /*-
3  * Copyright (c) 1995,1996 John T. Kohl.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS'' AND ANY EXPRESS OR
22  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
24  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
25  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
26  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
29  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
30  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  *
33  */
34 
35 #include <stdio.h>
36 #include <errno.h>
37 #include <syslog.h>
38 #include <fcntl.h>
39 #include <unistd.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <signal.h>
43 #include <sys/types.h>
44 #include <pwd.h>
45 #include <grp.h>
46 #include <sys/stat.h>
47 #include <sys/ioctl.h>
48 #include <sys/time.h>
49 #include <sys/socket.h>
50 #include <sys/un.h>
51 #include <sys/wait.h>
52 #include <machine/apmvar.h>
53 #include <err.h>
54 #include "pathnames.h"
55 #include "apm-proto.h"
56 
57 #define MAX(a,b) (a > b ? a : b)
58 #define TRUE 1
59 #define FALSE 0
60 
61 const char apmdev[] = _PATH_APM_CTLDEV;
62 const char sockfile[] = _PATH_APM_SOCKET;
63 
64 static int debug = 0;
65 
66 extern char *__progname;
67 extern char *optarg;
68 extern int optind;
69 extern int optopt;
70 extern int opterr;
71 extern int optreset;
72 
73 void usage (void);
74 int power_status (int fd, int force, struct apm_power_info *pinfo);
75 int bind_socket (const char *sn, mode_t mode, uid_t uid, gid_t gid);
76 enum apm_state handle_client(int sock_fd, int ctl_fd);
77 void suspend(int ctl_fd);
78 void stand_by(int ctl_fd);
79 void resume(int ctl_fd);
80 void sigexit(int signo);
81 void make_noise(int howmany);
82 void do_etc_file(const char *file);
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_UNIX, SOCK_STREAM, 0);
155     if (sock == -1)
156 	err(1, "cannot create local socket");
157 
158     s_un.sun_family = AF_UNIX;
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;
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 void
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     power_status(ctl_fd, 1, 0);
391     if (statonly)
392 	exit(0);
393     (void) signal(SIGTERM, sigexit);
394     (void) signal(SIGHUP, sigexit);
395     (void) signal(SIGINT, sigexit);
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