/
pwrkeymonitor.c
578 lines (485 loc) · 14.2 KB
/
pwrkeymonitor.c
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
/**
@file pwrkeymonitor.c
@brief Power key monitor plugin for forced poweroff.
Pwrkeymonitor is intended for "fallback poweroff", in case the UI (or other
component) responsible for handling powerkey events has died or become
unresponsible. In reading powerkey status, it currently only supports
evdev interface of the kernel. Currently, the plugin searches for evdev
drivers that can emit KEY_POWER events. It sends a shutdown event when
powerkey has been continously pressed for 5 seconds.
<p>
Copyright (C) 2010 Nokia Corporation.
Copyright (C) 2013-2017 Jolla Ltd.
@author Markus Lehtonen <markus.lehtonen@nokia.com>
@author Simo Piiroinen <simo.piiroinen@jollamobile.com>
This file is part of Dsme.
Dsme is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License
version 2.1 as published by the Free Software Foundation.
Dsme 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with Dsme. If not, see <http://www.gnu.org/licenses/>.
*/
#include "../include/dsme/modulebase.h"
#include "../include/dsme/modules.h"
#include "../include/dsme/logging.h"
#include "../include/dsme/mainloop.h"
#include "../include/dsme/timers.h"
#include "runlevel.h"
#include "state-internal.h"
#include <sys/ioctl.h>
#include <sys/types.h>
#include <linux/input.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <dirent.h>
#include <values.h>
#include <glib.h>
/** How long the the power key must be held before ui-less
* shutdown is started */
#define PWRKEY_TIMER_SECONDS 5
/** Timer for starting shutdown */
static dsme_timer_t pwrkey_timer = 0;
/** Prefix string for logging messages from this module */
#define PFIX "pwrkeymonitor: "
/** Cached module handle for this plugin */
static const module_t *this_module = 0;
/** Predicate for: Operating system update in progress
*
* Determined from presence of update mode flag file.
*/
static bool pwrkey_update_mode_is_active(void)
{
static const char flagfile[] = "/tmp/os-update-running";
return access(flagfile, F_OK) == 0;
}
/** Timer callback function for initiating shutdown
*
* @param data (not used)
*
* @return FALSE to stop the timer from repeating
*/
static int
pwrkey_trigger(void *data)
{
if( !pwrkey_timer )
{
/* Cancelled but got triggered anyway */
return FALSE;
}
/* Invalidate cached timer id */
pwrkey_timer = 0;
/* No shutdown via powerkey while in update mode */
if( pwrkey_update_mode_is_active() )
{
dsme_log(LOG_WARNING, PFIX"ongoing os update; ignoring power key");
// TODO: send a dbus signal (TBD) so that ui side can warn the
// user before some hw specific immediate power off gets
// triggered if power key is kept pressed any longer
return FALSE;
}
dsme_log(LOG_CRIT, PFIX"Timer triggered, initiating shutdown");
#ifdef PWRKEY_SHUTDOWN_MSG_TELINIT
/* Use telinit message */
const char runlevel[] = "SHUTDOWN";
char* buf = NULL;
DSM_MSGTYPE_TELINIT* msg = NULL;
msg = DSME_MSG_NEW_WITH_EXTRA(DSM_MSGTYPE_TELINIT, sizeof(runlevel));
buf = ((char *)msg) + sizeof(DSM_MSGTYPE_TELINIT);
strcpy(buf, runlevel);
modules_broadcast_internally(msg);
free(msg);
#else
/* Use the "normal" shutdown request */
DSM_MSGTYPE_SHUTDOWN_REQ msg = DSME_MSG_INIT(DSM_MSGTYPE_SHUTDOWN_REQ);
modules_broadcast_internally(&msg);
#endif
/* No repeats */
return FALSE;
}
/** Start shutdown timer
*/
static void
start_pwrkey_timer(void)
{
if( pwrkey_timer )
{
dsme_log(LOG_DEBUG, PFIX"Timer already running");
}
else if( !(pwrkey_timer = dsme_create_timer_seconds(PWRKEY_TIMER_SECONDS,
pwrkey_trigger,
NULL)) )
{
dsme_log(LOG_CRIT, PFIX"Timer creation failed!");
}
else
{
dsme_log(LOG_DEBUG, PFIX"Timer started (%d sec to shutdown)",
PWRKEY_TIMER_SECONDS);
}
}
/** Cancel shutdown timer
*/
static void
stop_pwrkey_timer(void)
{
if (pwrkey_timer)
{
dsme_destroy_timer(pwrkey_timer);
pwrkey_timer = 0;
dsme_log(LOG_DEBUG, PFIX"Timer stopped");
}
}
/** Calculate how many elements an array of longs bitmap needs to
* have enough space for bits items */
#define EVDEVBITS_LEN(bits) (((bits)+LONGBITS-1)/LONGBITS)
/** Calculate offset in unsigned long array for given bit */
#define EVDEVBITS_OFFS(bit) ((bit) / LONGBITS)
/** Calculate unsigned long mask for given bit */
#define EVDEVBITS_MASK(bit) (1ul << ((bit) % LONGBITS))
/** Check if the fd is an evdev node that emits power key events
*
* @param fd file descriptor to check
*
* @return true if power key events are emitted, false otherwise
*/
static bool
emits_powerkey_events(int fd)
{
bool res = false;
unsigned long mask_eve[EVDEVBITS_LEN(EV_CNT)];
unsigned long mask_key[EVDEVBITS_LEN(KEY_CNT)];
unsigned long mask_abs[EVDEVBITS_LEN(ABS_CNT)];
memset(mask_eve, 0, sizeof mask_eve);
memset(mask_key, 0, sizeof mask_key);
memset(mask_abs, 0, sizeof mask_abs);
/* Get bitmask of supported event types */
if( ioctl(fd, EVIOCGBIT(0, EV_CNT), mask_eve) == -1 )
{
dsme_log(LOG_DEBUG, PFIX"EVIOCGBIT(%d): %m", fd);
goto EXIT;
}
/* Get bitmask of supported key event codes */
if( mask_eve[EVDEVBITS_OFFS(EV_KEY)] & EVDEVBITS_MASK(EV_KEY) ) {
if( ioctl(fd, EVIOCGBIT(EV_KEY, KEY_CNT), mask_key) == -1 )
dsme_log(LOG_DEBUG, PFIX"EVIOCGBIT(%d): %m", fd);
}
/* Get bitmask of supported abs event codes */
if( mask_eve[EVDEVBITS_OFFS(EV_ABS)] & EVDEVBITS_MASK(EV_ABS) ) {
if( ioctl(fd, EVIOCGBIT(EV_ABS, ABS_CNT), mask_abs) == -1 )
dsme_log(LOG_DEBUG, PFIX"EVIOCGBIT(%d): %m", fd);
}
/* Require: KEY_POWER events are emitted */
if( !(mask_key[EVDEVBITS_OFFS(KEY_POWER)] & EVDEVBITS_MASK(KEY_POWER)) )
goto EXIT;
/* Assume: KEY_POWER from multitouch device is actually double tap */
if( mask_abs[EVDEVBITS_OFFS(ABS_MT_POSITION_X)] &
EVDEVBITS_MASK(ABS_MT_POSITION_X) )
goto EXIT;
res = true;
EXIT:
return res;
}
/** Structure for keeping track of io channels and watches */
typedef struct
{
GIOChannel *chan;
guint watch;
} channel_watch_t;
/** Allocate and initialize an io channel watch structure
*
* @param chan io channel
* @param watch io watch associated with the channel
*
* @return pointer io channel watch structure
*/
static
channel_watch_t *
channel_watch_create(GIOChannel *chan, guint watch)
{
channel_watch_t *self = g_malloc0(sizeof *self);
self->chan = chan;
self->watch = watch;
return self;
}
/** Delete an io channel watch structure and free resources bound to it
*
* @param self pointer io channel watch structure
* @param remove_watch should the io watch be removed too
*/
static
void
channel_watch_delete(channel_watch_t *self, bool remove_watch)
{
if( self )
{
if( remove_watch && self->watch )
{
g_source_remove(self->watch);
}
if( self->chan )
{
g_io_channel_unref(self->chan);
}
g_free(self);
}
}
/** List of io channels and watches tracking power button presses */
static GSList *watchlist = 0;
/** Append an io channel and a watch for it into list of things under tracking
*
* @param chan io channel
* @param watch watch id for the channel
*/
static
void
watchlist_add(GIOChannel *chan, guint watch)
{
watchlist = g_slist_prepend(watchlist, channel_watch_create(chan, watch));
}
/** Remove a io channel from the list of things under tracking
*
* Note: Does not remove the watch id associated with the channel.
*
* @param chan io channel
*/
static
void
watchlist_remove(GIOChannel *chan)
{
GSList **pos = &watchlist;
GSList *now;
while( (now = *pos) )
{
channel_watch_t *cw = now->data;
if( cw->chan != chan )
{
pos = &now->next;
continue;
}
// unlink slot from list and free it
*pos = now->next, now->next = 0;
g_slist_free(now);
channel_watch_delete(cw, false);
break;
}
}
/** Detach from all io channels that are open for powerkey tracking
*/
static
void
watchlist_clear(void)
{
for( GSList *now = watchlist; now; now = now->next )
{
channel_watch_delete(now->data, true);
}
g_slist_free(watchlist), watchlist = 0;
}
/** Process evdev input events
*
* @param chan io channel that has input available
* @param condition bitmask of input/error states
* @param data (not used)
*
* return TRUE to keep the watch alive, or FALSE to remove it
*/
static
gboolean
process_kbevent(GIOChannel* chan, GIOCondition condition, gpointer data)
{
const module_t *caller = modulebase_enter_module(this_module);
gboolean keep_going = TRUE;
struct input_event buf[32];
/* Abandon watch if we get abnorman conditions from glib */
if (condition & ~(G_IO_IN | G_IO_PRI))
{
dsme_log(LOG_ERR, PFIX"I/O error");
keep_going = FALSE;
}
/* Do the actual reading with good old read() syscall */
int fd = g_io_channel_unix_get_fd(chan);
int rc = read(fd, buf, sizeof buf);
if( rc < 0 )
{
switch( errno )
{
case EINTR:
case EAGAIN:
break;
default:
dsme_log(LOG_ERR, PFIX"read: %m");
keep_going = FALSE;
break;
}
}
else if( rc == 0 )
{
dsme_log(LOG_ERR, PFIX"read: EOF");
keep_going = FALSE;
}
else
{
int n = rc / sizeof *buf;
dsme_log(LOG_DEBUG, PFIX"Processing %d events", n);
for( int i = 0; i < n; ++i )
{
const struct input_event *eve = buf + i;
dsme_log(LOG_DEBUG, PFIX"Got event, type: %d code: %d value: %d",
eve->type, eve->code, eve->value);
if( eve->type == EV_KEY && eve->code == KEY_POWER )
{
switch( eve->value )
{
case 1: // pressed
start_pwrkey_timer();
break;
case 0: // released
stop_pwrkey_timer();
break;
default: // repeat ignored
break;
}
}
}
}
if( !keep_going )
{
dsme_log(LOG_WARNING, PFIX"disabling io watch");
/* the watch gets removed as we return FALSE, but
* the channel must be removed from tracking list */
watchlist_remove(chan);
}
modulebase_enter_module(caller);
return keep_going;
}
/** Probe an input device and track it if it can emit powerkey events
*
* @param path path of input device
*
* @return true if tracking was started succesfully, false if it was
* not a powerkey device or tracking could not be started
*/
static
bool
probe_evdev_device(const char *path)
{
bool res = false;
int file = -1;
GIOChannel *chan = 0;
guint watch = 0;
GError *err = 0;
if( (file = open(path, O_RDONLY)) == -1 )
{
dsme_log(LOG_ERR, PFIX"%s: open: %m", path);
goto EXIT;
}
if( !emits_powerkey_events(file) )
{
dsme_log(LOG_DEBUG, PFIX"%s: not a powerkey device", path);
goto EXIT;
}
if( !(chan = g_io_channel_unix_new(file)) )
{
dsme_log(LOG_ERR, PFIX"%s: io channel setup failed", path);
goto EXIT;
}
/* io watch owns the file */
g_io_channel_set_close_on_unref(chan, true), file = -1;
/* Set to NULL encoding so that we can turn off the buffering */
if( g_io_channel_set_encoding(chan, NULL, &err) != G_IO_STATUS_NORMAL )
{
dsme_log(LOG_WARNING, PFIX"%s: unable to set io channel encoding",
path);
if( err )
{
dsme_log(LOG_WARNING, PFIX"%s", err->message);
}
// continue anyway
}
g_io_channel_set_buffered(chan, false);
if( !(watch = g_io_add_watch(chan,
G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
process_kbevent, 0)) )
{
dsme_log(LOG_ERR, PFIX"%s: unable to add io channel watch", path);
goto EXIT;
}
dsme_log(LOG_DEBUG, PFIX"%s: channel=%p, watch=%u", path, chan, watch);
/* watchlist owns the channel and watch */
watchlist_add(chan, watch), chan = 0, watch = 0;
res = true;
EXIT:
g_clear_error(&err);
if( watch != 0 ) g_source_remove(watch);
if( chan != 0 ) g_io_channel_unref(chan);
if( file != -1 ) close(file);
return res;
}
/** Scan and track evdev sources that can emit powerkey events
*/
static bool
start_pwrkey_monitor(void)
{
static const char base[] = "/dev/input";
DIR *dir = 0;
int cnt = 0;
char path[PATH_MAX];
struct dirent *de;
if( !(dir = opendir(base)) )
{
dsme_log(LOG_ERR, PFIX"opendir(%s): %m", base);
goto EXIT;
}
while( (de = readdir(dir)) )
{
if( strncmp(de->d_name, "event", 5) )
{
continue;
}
int rc = snprintf(path, sizeof path, "%s/%s", base, de->d_name);
if( rc < 0 || rc >= sizeof path )
{
/* Skip on error / truncate */
continue;
}
if( probe_evdev_device(path) )
{
cnt += 1;
}
}
EXIT:
if( dir ) closedir(dir);
if( cnt < 1 )
{
dsme_log(LOG_WARNING, PFIX"could not find any powerkey input devices");
}
return cnt > 0;
}
/** Close any io channels still open for powerkey tracking
*/
static void
stop_pwrkey_monitor(void)
{
watchlist_clear();
stop_pwrkey_timer();
}
void
module_init(module_t * handle)
{
this_module = handle;
start_pwrkey_monitor();
dsme_log(LOG_DEBUG, "libpwrkeymonitor.so loaded");
}
void
module_fini(void)
{
stop_pwrkey_monitor();
dsme_log(LOG_DEBUG, "libpwrkeymonitor.so unloaded");
}