File: apmd.c

package info (click to toggle)
apmd 3.0beta5-1
  • links: PTS
  • area: main
  • in suites: slink
  • size: 244 kB
  • ctags: 106
  • sloc: ansic: 1,047; sh: 119; makefile: 109
file content (431 lines) | stat: -rw-r--r-- 12,466 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
/* apmd.c -- APM event-monitoring daemon
 * Created: Mon Jan  8 14:29:18 1996 by faith@acm.org
 * Revised: Fri Dec 26 21:38:28 1997 by faith@acm.org
 * Copyright 1996, 1997 Rickard E. Faith (faith@acm.org)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2, or (at your option) any
 * later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * $Id: apmd.c,v 1.14 1999/01/24 05:26:14 apenwarr Exp $
 * 
 * Changes to support pre_suspend, post_resume and low_battery commands
 * based on patches from Bjoern Kriews (bkr@cut.de), 1996/12/24.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <time.h>
#include <syslog.h>
#include <signal.h>
#include <paths.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include "apm.h"


#define PID_FILE _PATH_VARRUN "apmd.pid"

#define DEBUG        0		/* Special debugging: 0 = off; 1 = on */
#define MAX_EVENTS   8		/* Maximum events from APM BIOS */
#define RESUME_HOURS 6		/* How many hours before resume loss calc. */

static int    verbose = 0;
static int    wall    = 0;
static int    utc     = 0;
static time_t then;
static time_t now;
static int    percent_change =  5; /* log every 5 percent change */
static int    warn_level     = 10; /* start warning at 10% remaining */
static char   *pre_suspend_cmd = NULL;
static char   *post_resume_cmd = NULL;
static char   *low_battery_cmd = NULL;
static int    check_power_time = -1; /* seconds between /proc/apm checks */

#ifndef abs
#define abs(a) ((a)<0?(-(a)):(a))
#endif

void usage( void )
{
   fprintf( stderr,
	    "usage: apmd [-VvuW] [-p percent] [-w percent] [-c seconds]\n"
	    "            [-s pre_suspend_cmd] [-r post_resume_cmd]\n"
	    "            [-l low_battery_cmd]\n" );
   exit( 1 );
}

void warn( const char *message )
{
   FILE *str;

   syslog( LOG_ALERT, "%s", message );
   if (wall) {
      str = popen( "wall", "w" );
      fprintf( str, "%s\n", message );
      pclose( str );
   }
}

#define IS_CHARGING(i) ( ((i).battery_status == 3) || ((i).battery_flags & 8) )

char *state( struct apm_info *i )
{
  if (IS_CHARGING((*i))) return "Charge";
  if (i->ac_line_status == 1) return "On-line";
  else return "Battery";
}

#define F_RESUME 1
#define F_LOW 2
#define F_FORCE 4

void check_power( int flags )
{
   apm_info      i;
   time_t        tmp;
   time_t        delta_time;
   int           delta_percentage;
   int           seconds;
   double        rate;
   int           force               = flags & F_FORCE;
   char          buf[512];
   int           len;
   static time_t t;
   static int    percentage;
   static int    charging;
   static int    snap_percentage     = 0;
   static int    initialized         = 0;
   static int    last_percentage     = 0;
   static int    done_full           = 0;
   static int    done_empty          = 0;
   static int    last_battery_status = 0;

   if (apm_read( &i )) {
       syslog( LOG_ERR, "APM read failed\n" );
       return;
   }

   if (i.using_minutes) seconds = i.battery_time * 60;
   else                 seconds = i.battery_time;

   if (!initialized)
      syslog( LOG_INFO, "Version %s (APM BIOS %d.%d, Linux driver %s)",
	      VERSION,
	      i.apm_version_major, i.apm_version_minor,
	      i.driver_version );
   
   if (!initialized
       || (!charging && (IS_CHARGING(i)))
       || (charging && (!IS_CHARGING(i)))) {
      time( &t );
      last_percentage = percentage = i.battery_percentage;
      charging = IS_CHARGING(i);
      syslog( LOG_INFO, "%s: * * * (%d%% %s)",
	      state(&i),
	      i.battery_percentage, apm_time_nosec( seconds ) );
   }
   initialized = 1;

   if (flags & F_RESUME) {
      int percent_change = i.battery_percentage - snap_percentage;
      int seconds_change = now - then;
      
      time( &t );
      last_percentage = percentage = i.battery_percentage;
      charging = IS_CHARGING(i);
      if (then)
	 len = sprintf( buf, "Resume after %s", apm_time( seconds_change ) );
      else
	 len = sprintf( buf, "Resume" );
      if (seconds_change > 60 * 60 * RESUME_HOURS
	  && snap_percentage > 0
	  && percent_change < 0
	  && !charging) {
	 len += sprintf( buf + len, ", %.2f%%/day",
			 ((double)percent_change / (double)seconds_change)
			 * 60.0 * 60.0 * 24.0 );
      }
      sprintf( buf + len, " (%d%%%% %s)",
	      i.battery_percentage, apm_time_nosec( seconds ) );
      syslog( LOG_INFO, buf );
      
   }

   if ((flags & F_LOW)
       || (!charging
	   && i.battery_status != last_battery_status
	   && i.battery_status == 1)) {
      sprintf( buf, "Battery Low Notification from APM BIOS (%d%% %s)",
	       i.battery_percentage, apm_time_nosec( seconds ) );
      warn( buf );
   }

   snap_percentage = i.battery_percentage;
   if (i.battery_percentage < 0) return;
   
   time( &tmp );
   delta_time       = tmp - t;
   delta_percentage = percentage - i.battery_percentage;

#if DEBUG
   printf( "%d %d %d %d %d\n",
	   delta_time, delta_percentage, i.battery_percentage,
	   done_full, force );
#endif
   
   if (!charging && i.battery_percentage <= warn_level
       && (abs( last_percentage - i.battery_percentage ) > 0
	   || !i.battery_percentage)) {
      sprintf( buf, "Battery warning (%d%% %s)",
	       i.battery_percentage, apm_time_nosec( seconds ) );
      warn( buf );
   }
      
   if (!delta_time || !delta_percentage) return;
   if (i.battery_percentage == 100) {
      if (!done_full) ++force;
      done_full = 1;
   } else
      done_full = 0;
   
   if (!i.battery_percentage) {
      if (!done_empty) ++force;
      done_empty = 1;
   } else
      done_empty = 0;

#if DEBUG
   printf( "%d %d %d %d %d\n",
	   delta_time, delta_percentage, i.battery_percentage,
	   done_full, force );
#endif

   if (!force && abs(last_percentage - i.battery_percentage)
       < (percent_change > 1 ? percent_change : 1))
      return;

   last_percentage = i.battery_percentage;
   
   rate = (double)delta_percentage / (double)delta_time;

   len = sprintf( buf, "%s: %.2f%%/min",
		  state(&i),
		  rate * 60.0 );
   
   if ((!charging && percentage == 100) || (charging && percentage == 0))
      len += sprintf( buf + len, " %s", apm_time_nosec( delta_time ) );
   else
      len += sprintf( buf + len, " (%s)", apm_time_nosec( delta_time ) );
   
   if (charging) {
      len += sprintf( buf + len, " %s",
		     apm_time_nosec( (int)((100.0 - i.battery_percentage)
				     / -rate ) ) );
   } else {
      len += sprintf( buf + len, " %s",
		      apm_time_nosec( (int)(i.battery_percentage / rate) ) );
   }

   sprintf( buf + len, " (%d%%%% %s)",
	    i.battery_percentage, apm_time_nosec( seconds ) );
   syslog( LOG_INFO, buf );
}

static void sig_handler( int sig )
{
   syslog( LOG_INFO, "Exiting" );
   unlink( PID_FILE );
   exit( 0 );
}

int main( int argc, char **argv )
{
   int           debug   = 0;
   int           c;
   int           fd;
   int           pid;
   FILE          *str;
   apm_event_t   events[MAX_EVENTS];
   struct option longopts[] = {
      { "verbose",     0, 0, 'v' },
      { "version",     0, 0, 'V' },
      { "utc",         0, 0, 'u' },
      { "debug",       0, 0, 'd' },
      { "percentage",  1, 0, 'p' },
      { "warn",        1, 0, 'w' },
      { "wall",        0, 0, 'W' },
      { "pre_suspend", 1, 0, 's' },
      { "post_resume", 1, 0, 'r' },
      { "low_battery", 1, 0, 'l' },
      { "check",       1, 0, 'c' },
      { NULL,          0, 0, 0 },
   };

   switch (apm_exists()) {
   case 1: fprintf( stderr, "No APM support in kernel\n" );  exit( 1 );
   case 2: fprintf( stderr, "Old APM support in kernel\n" ); exit( 2 );
   }

   if (getuid()) {
      fprintf( stderr, "apmd: must be run as root\n" );
      exit( 1 );
   }

   while ((c = getopt_long( argc, argv, "Vvudp:w:Ws:r:l:c:", longopts, NULL ))
	  != -1)
      switch (c) {
      case 'V':
	 fprintf( stderr, "apmd version %s\n", VERSION );
	 exit( 0 );
	 break;
      case 'v': ++verbose;                         break;
      case 'u': utc = 1;                           break;
      case 'd': ++debug;                           break;
      case 'p': percent_change = atoi( optarg );   break;
      case 'w': warn_level = atoi( optarg );       break;
      case 'W': ++wall;                            break;
      case 's': pre_suspend_cmd = optarg;	   break;
      case 'r': post_resume_cmd = optarg;	   break;
      case 'l': low_battery_cmd = optarg;	   break;
      case 'c': check_power_time = atoi( optarg ); break;
      default:  usage();                           break;
      }

   if (!access( PID_FILE, R_OK )) {
      if ((str = fopen( PID_FILE, "r" ))) {
	 fscanf( str, "%d", &pid );
	 fclose( str );
	 fprintf( stderr, "An apmd is already running as process %d\n", pid );
	 fprintf( stderr,
		  "If it is no longer running, remove %s\n", PID_FILE );
	 exit( 1 );
      }
   }

   openlog( "apmd", (debug?LOG_PERROR:0)|LOG_PID|LOG_CONS, LOG_DAEMON );
   if (signal( SIGINT, SIG_IGN ) != SIG_IGN)  signal( SIGINT, sig_handler );
   if (signal( SIGQUIT, SIG_IGN ) != SIG_IGN) signal( SIGQUIT, sig_handler );
   if (signal( SIGTERM, SIG_IGN ) != SIG_IGN) signal( SIGTERM, sig_handler );
   
   if (!debug) {		/* detach */
      if ((pid = fork())) {	/* parent */
	 if ((str = fopen( PID_FILE, "w" ))) {
	    fprintf( str, "%d\n", pid );
	    fclose( str );
	 }
	 exit( 0 );
      }
				/* child */
      if (pid < 0) {
	 syslog( LOG_INFO, "fork() failed: %m" );
	 unlink( PID_FILE );
	 exit( 1 );
      }
				/* Child.  Follow the daemon rules in
                                   W. Richard Stevens. Advanced Programming
                                   in the UNIX Environment (Addison-Wesley
                                   Publishing Co., 1992). Page 417.). */
      if (setsid() < 0) {
	 syslog( LOG_INFO, "setsid() failed: %m" );
	 unlink( PID_FILE );
	 exit( 1 );
      }
      chdir( "/" );
      umask( 0 );
   }
	    
   if ((fd = apm_open()) < 0) {
      syslog( LOG_INFO, "apm_open() failed: %m" );
      unlink( PID_FILE );
      exit( 1 );
   }

   check_power( 0 );
   for (;;) {
      int n = apm_get_events( fd, check_power_time, events, MAX_EVENTS );
      int i;
      
      if (!n) check_power(0);
      
      for (i = 0; i < n; i++) {
	 if (verbose)
	    syslog( LOG_INFO, "Event 0x%04x: %s",
		    events[i], apm_event_name( events[i] ) );
	 switch (events[i]) {
	 case APM_SYS_STANDBY:
	 case APM_USER_STANDBY:
	    time( &then );
	    apm_standby( fd );
	    break;
	 case APM_SYS_SUSPEND:
	 case APM_USER_SUSPEND:
	    time( &then );
	    if (pre_suspend_cmd)
	       syslog(LOG_INFO, "pre_suspend: '%s' returns %d",
		      pre_suspend_cmd, system(pre_suspend_cmd));
	    sync();
	    sleep(0); /* let syslogd write the message */
	    sync();
	    sleep(1);
	    apm_suspend( fd );
	    break;
	 case APM_CRITICAL_SUSPEND:
	    time( &then );
				/* As fast as possible */
	    ioctl( fd, APM_IOC_SUSPEND, NULL );
	    break;
	 case APM_STANDBY_RESUME:
	    time( &now );
	    check_power( F_RESUME );
	    break;

	 case APM_NORMAL_RESUME:
	    time( &now );
	    check_power( F_RESUME );
	    if (post_resume_cmd)
	       syslog(LOG_INFO, "post_resume: '%s' returns %d", 
		      post_resume_cmd, system(post_resume_cmd));
		      
	    /* fall through */
	    
	 case APM_UPDATE_TIME:
	 case APM_CRITICAL_RESUME:
	    time( &then );
	    if (utc)
	       system( "[ -x /sbin/clock ] && clock -s -u || hwclock -s -u" );
	    else
	       system( "[ -x /sbin/clock ] && clock -s || hwclock -s" );
	    time( &now );
	    check_power( F_RESUME );
	    break;
	 case APM_POWER_STATUS_CHANGE:
	    check_power( F_FORCE );
	    break;
	 case APM_LOW_BATTERY:
	    check_power( F_LOW );
	    if (low_battery_cmd)
	       syslog(LOG_INFO, "low_battery: '%s' returns %d", 
		      low_battery_cmd, system(low_battery_cmd));
	    break;
	 default:
	    syslog(LOG_ERR, "Received unknown event 0x%04x.", i);
	 }
      }
   }
   
   return 0;
}