Zombie.
[pandora-libraries.git] / apps / pndevmapperd.c
1
2 /* pndevmapperd exists to watch for a few interesting events and to launch scripts when they occur
3  * ie: when the lid closes, should invoke power-mode toggle sh-script
4  */
5
6 // woot for writing code while sick.
7
8 // this code begs a rewrite, but should work fine; its just arranged goofily
9 // -> I mean, why the racial divide between keys and other events
10
11 #include <stdio.h> /* for printf, NULL */
12 #include <stdlib.h> /* for free */
13 #include <string.h> /* for strdup */
14 #include <unistd.h>    // for exit()
15 #include <sys/types.h> // for umask
16 #include <sys/stat.h>  // for umask
17 #include <fcntl.h> // for open(2)
18 #include <errno.h> // for errno
19 #include <time.h> // for time(2)
20 #include <ctype.h> // for isdigit
21 #include <signal.h> // for sigaction
22 #include <sys/wait.h> // for wait
23
24 #include <linux/input.h> // for keys
25 //#include "../../kernel-rip/input.h" // for keys
26
27 #include "pnd_conf.h"
28 #include "pnd_container.h"
29 #include "pnd_apps.h"
30 #include "pnd_discovery.h"
31 #include "pnd_locate.h"
32 #include "pnd_pndfiles.h"
33 #include "pnd_pxml.h"
34 #include "pnd_logger.h"
35 #include "pnd_utility.h"
36 #include "pnd_notify.h"
37
38 // daemon and logging
39 //
40 unsigned char g_daemon_mode = 0;
41 unsigned int g_minimum_separation = 1;
42
43 typedef enum {
44   pndn_debug = 0,
45   pndn_rem,          // will set default log level to here, so 'debug' is omitted
46   pndn_warning,
47   pndn_error,
48   pndn_none
49 } pndnotify_loglevels_e;
50
51 // key/event definition
52 //
53 typedef struct {
54   int keycode;
55   char *keyname;
56 } keycode_t;
57
58 keycode_t keycodes[] = {
59   { KEY_A, "a" },
60   { KEY_MENU, "pandora" },
61   { KEY_POWER, "power" },
62   { -1, NULL }
63 };
64
65 typedef struct {
66   int type;
67   int code;
68   char *name;
69 } generic_event_t;
70
71 generic_event_t generics[] = {
72   { EV_SW, 0, "lid-toggle" }, // expecting value 1 (lid close) or 0 (lid open)
73   { -1, -1, NULL }
74 };
75
76 // event-to-sh mapping
77 //
78 typedef struct {
79
80   unsigned char key_p; // 1 if its a key, otherwise an event
81
82   /* template information
83    */
84   void *reqs;          // scancode/etc for the event in question
85
86   char *script;        // script to invoke
87   //unsigned int hold_min; // minimum hold-time to trigger
88
89   /* state
90    */
91   time_t last_trigger_time;
92   time_t keydown_time;
93
94 } evmap_t;
95
96 #define MAXEVENTS 255
97 evmap_t g_evmap [ MAXEVENTS ];
98 unsigned int g_evmap_max = 0;
99
100 /* get to it
101  */
102 void dispatch_key ( int keycode, int val );
103 void dispatch_event ( int code, int val );
104 void sigchld_handler ( int n );
105
106 static void usage ( char *argv[] ) {
107   printf ( "%s [-d]\n", argv [ 0 ] );
108   printf ( "-d\tDaemon mode; detach from terminal, chdir to /tmp, suppress output. Optional.\n" );
109   printf ( "-l#\tLog-it; -l is 0-and-up (or all), and -l2 means 2-and-up (not all); l[0-3] for now. Log goes to /tmp/pndevmapperd.log\n" );
110   return;
111 }
112
113 int main ( int argc, char *argv[] ) {
114   int i;
115   int logall = -1; // -1 means normal logging rules; >=0 means log all!
116
117   for ( i = 1; i < argc; i++ ) {
118
119     if ( argv [ i ][ 0 ] == '-' && argv [ i ][ 1 ] == 'd' ) {
120       //printf ( "Going daemon mode. Silent running.\n" );
121       g_daemon_mode = 1;
122     } else if ( argv [ i ][ 0 ] == '-' && argv [ i ][ 1 ] == 'l' ) {
123
124       if ( isdigit ( argv [ i ][ 2 ] ) ) {
125         unsigned char x = atoi ( argv [ i ] + 2 );
126         if ( x >= 0 &&
127              x < pndn_none )
128         {
129           logall = x;
130         }
131       } else {
132         logall = 0;
133       }
134     } else {
135       usage ( argv );
136       exit ( 0 );
137     }
138
139   } // for
140
141   /* enable logging?
142    */
143   pnd_log_set_pretext ( "pndevmapperd" );
144   pnd_log_set_flush ( 1 );
145
146   if ( logall == -1 ) {
147     // standard logging; non-daemon versus daemon
148
149     if ( g_daemon_mode ) {
150       // nada
151     } else {
152       pnd_log_set_filter ( pndn_rem );
153       pnd_log_to_stdout();
154     }
155
156   } else {
157     FILE *f;
158
159     f = fopen ( "/tmp/pndevmapperd.log", "w" );
160
161     if ( f ) {
162       pnd_log_set_filter ( logall );
163       pnd_log_to_stream ( f );
164       pnd_log ( pndn_rem, "logall mode - logging to /tmp/pndevmapperd.log\n" );
165     }
166
167     if ( logall == pndn_debug ) {
168       pnd_log_set_buried_logging ( 1 ); // log the shit out of it
169       pnd_log ( pndn_rem, "logall mode 0 - turned on buried logging\n" );
170     }
171
172   } // logall
173
174   pnd_log ( pndn_rem, "%s built %s %s", argv [ 0 ], __DATE__, __TIME__ );
175
176   pnd_log ( pndn_rem, "log level starting as %u", pnd_log_get_filter() );
177
178   // basic daemon set up
179   if ( g_daemon_mode ) {
180
181     // set a CWD somewhere else
182     chdir ( "/tmp" );
183
184     // detach from terminal
185     if ( ( i = fork() ) < 0 ) {
186       pnd_log ( pndn_error, "ERROR: Couldn't fork()\n" );
187       exit ( i );
188     }
189     if ( i ) {
190       exit ( 0 ); // exit parent
191     }
192     setsid();
193
194     // umask
195     umask ( 022 ); // emitted files can be rwxr-xr-x
196     
197   } // set up daemon
198
199   /* hmm, seems to not like working right after boot.. do we depend on another daemon or
200    * on giving kernel time to init something, or ... wtf?
201    * -- lets give the system some time to wake up
202    */
203   { // delay
204
205     // this one works for pndnotifyd, which actually needs INOTIFYH..
206     //
207
208     // check if inotify is awake yet; if not, try waiting for awhile to see if it does
209     pnd_log ( pndn_rem, "Starting INOTIFY test; should be instant, but may take awhile...\n" );
210
211     if ( ! pnd_notify_wait_until_ready ( 120 /* seconds */ ) ) {
212       pnd_log ( pndn_error, "ERROR: INOTIFY refuses to be useful and quite awhile has passed. Bailing out.\n" );
213       return ( -1 );
214     }
215
216     pnd_log ( pndn_rem, "INOTIFY seems to be useful, whew.\n" );
217
218     // pndnotifyd also waits for user to log in .. pretty excessive, especially since
219     // what if user wants to close the lid while at the log in screen? for now play the
220     // odds as thats pretty unliekly usage scenariom but is clearly not acceptible :/
221     //
222
223     // wait for a user to be logged in - we should probably get hupped when a user logs in, so we can handle
224     // log-out and back in again, with SDs popping in and out between..
225     pnd_log ( pndn_rem, "Checking to see if a user is logged in\n" );
226     char tmp_username [ 128 ];
227     while ( 1 ) {
228       if ( pnd_check_login ( tmp_username, 127 ) ) {
229         break;
230       }
231       pnd_log ( pndn_debug, "  No one logged in yet .. spinning.\n" );
232       sleep ( 2 );
233     } // spin
234     pnd_log ( pndn_rem, "Looks like user '%s' is in, continue.\n", tmp_username );
235
236   } // delay
237
238   /* inhale config or die trying
239    */
240   char *configpath;
241
242   // attempt to fetch a sensible default searchpath for configs
243   configpath = pnd_conf_query_searchpath();
244
245   // attempt to fetch the apps config. since it finds us the runscript
246   pnd_conf_handle evmaph;
247
248   evmaph = pnd_conf_fetch_by_id ( pnd_conf_evmap, configpath );
249
250   if ( ! evmaph ) {
251     // couldn't locate conf, just bail
252     pnd_log ( pndn_error, "ERROR: Couldn't locate conf file\n" );
253     exit ( -1 );
254   }
255
256   /* iterate across conf, stocking the event map
257    */
258   void *n = pnd_box_get_head ( evmaph );
259
260   while ( n ) {
261     char *k = pnd_box_get_key ( n );
262     //printf ( "key %s\n", k );
263
264     if ( strncmp ( k, "keys.", 5 ) == 0 ) {
265       k += 5;
266
267       // keys should really push push generic-events onto the table, since they;'re just a special case of them
268       // to make things easier to read
269
270       // figure out which keycode we're talking about
271       keycode_t *p = keycodes;
272       while ( p -> keycode != -1 ) {
273         if ( strcasecmp ( p -> keyname, k ) == 0 ) {
274           break;
275         }
276         p++;
277       }
278
279       if ( p -> keycode != -1 ) {
280         g_evmap [ g_evmap_max ].key_p = 1;    // its a key, not an event
281         g_evmap [ g_evmap_max ].reqs = p;     // note the keycode
282         g_evmap [ g_evmap_max ].script = n;   // note the script to activate in response
283         pnd_log ( pndn_rem, "Registered key %s [%d] to script %s\n", p -> keyname, p -> keycode, (char*) n );
284         g_evmap_max++;
285       } else {
286         pnd_log ( pndn_warning, "WARNING! Key '%s' is not handled by pndevmapperd yet! Skipping.", k );
287       }
288
289     } else if ( strncmp ( k, "events.", 7 ) == 0 ) {
290       k += 7;
291
292       // yes, key events could really be defined in this generic sense, and really we could just let people
293       // put the code and so on right in the conf, but trying to keep it easy on people; maybe should
294       // add a 'generic' section to conf file and just let folks redefine random events that way
295       // Really, it'd be nice if the /dev/input/events could spit out useful text, and just use scripts
296       // to respond without a daemon per se; for that matter, pnd-ls and pnd-map pnd-dotdesktopemitter
297       // should just exist as scripts rather than daemons, but whose counting?
298
299       // figure out which keycode we're talking about
300       generic_event_t *p = generics;
301       while ( p -> code != -1 ) {
302         if ( strcasecmp ( p -> name, k ) == 0 ) {
303           break;
304         }
305         p++;
306       }
307
308       if ( p -> code != -1 ) {
309         g_evmap [ g_evmap_max ].key_p = 0;    // its an event, not a key
310         g_evmap [ g_evmap_max ].reqs = p;     // note the keycode
311         g_evmap [ g_evmap_max ].script = n;   // note the script to activate in response
312         pnd_log ( pndn_rem, "Registered generic event %s [%d] to script %s\n", p -> name, p -> code, (char*) n );
313         g_evmap_max++;
314       } else {
315         pnd_log ( pndn_warning, "WARNING! Generic event '%s' is not handled by pndevmapperd yet! Skipping.", k );
316       }
317
318     } else if ( strncmp ( k, "pndevmapperd.", 7 ) == 0 ) {
319       // not consumed here, skip silently
320
321     } else {
322       // uhhh
323       pnd_log ( pndn_warning, "Unknown config key '%s'; skipping.\n", k );
324     }
325
326     n = pnd_box_get_next ( n );
327   } // while
328
329   if ( pnd_conf_get_as_int ( evmaph, "pndevmapperd.loglevel" ) != PND_CONF_BADNUM ) {
330     pnd_log_set_filter ( pnd_conf_get_as_int ( evmaph, "pndevmapperd.loglevel" ) );
331     pnd_log ( pndn_rem, "config file causes loglevel to change to %u", pnd_log_get_filter() );
332   }
333
334   if ( pnd_conf_get_as_int ( evmaph, "pndevmapperd.minimum_separation" ) != PND_CONF_BADNUM ) {
335     g_minimum_separation = pnd_conf_get_as_int ( evmaph, "pndevmapperd.minimum_separation" );
336     pnd_log ( pndn_rem, "config file causes minimum_separation to change to %u", g_minimum_separation );
337   }
338
339   /* do we have anything to do?
340    */
341   if ( ! g_evmap_max ) {
342     // uuuh, nothing to do?
343     pnd_log ( pndn_warning, "WARNING! No events configured to watch, so just spinning wheels...\n" );
344     exit ( -1 );
345   } // spin
346
347   /* set up sigchld -- don't want zombies all over; well, we do, but not process zombies
348    */
349   sigset_t ss;
350   sigemptyset ( &ss );
351
352   struct sigaction siggy;
353   siggy.sa_handler = sigchld_handler;
354   siggy.sa_mask = ss; /* implicitly blocks the origin signal */
355   siggy.sa_flags = SA_RESTART; /* don't need anything */
356
357   sigaction ( SIGCHLD, &siggy, NULL );
358
359   /* actually try to do something useful
360    */
361
362   // stolen in part from notaz :)
363
364   // try to locate the appropriate devices
365   int id;
366   int fds [ 5 ] = { -1, -1, -1, -1, -1 }; // 0 = keypad, 1 = gpio keys
367   int imaxfd = 0;
368
369   for ( id = 0; ; id++ ) {
370     char fname[64];
371     char name[256] = { 0, };
372     int fd;
373
374     snprintf ( fname, sizeof ( fname ), "/dev/input/event%i", id );
375     fd = open ( fname, O_RDONLY );
376
377     if ( fd == -1 ) {
378       break;
379     }
380
381     ioctl (fd, EVIOCGNAME(sizeof(name)), name );
382
383     if ( strcmp ( name, "omap_twl4030keypad" ) == 0 ) {
384       fds [ 0 ] = fd;
385     } else if ( strcmp ( name, "gpio-keys" ) == 0) {
386       fds [ 1 ] = fd;
387     } else if ( strcmp ( name, "AT Translated Set 2 keyboard" ) == 0) { // for vmware, my dev environment
388       fds [ 0 ] = fd;
389     } else {
390       pnd_log ( pndn_rem, "Ignoring unknown device '%s'\n", name );
391       close ( fd );
392       continue;
393     }
394
395     if (imaxfd < fd) imaxfd = fd;
396   } // for
397
398   if ( fds [ 0 ] == -1 ) {
399     pnd_log ( pndn_warning, "WARNING! Couldn't find keypad device\n" );
400   }
401
402   if ( fds [ 1 ] == -1 ) {
403     pnd_log ( pndn_warning, "WARNING! couldn't find button device\n" );
404   }
405
406   if ( fds [ 0 ] == -1 && fds [ 1 ] == -1 ) {
407     pnd_log ( pndn_error, "ERROR! Couldn't find either device; exiting!\n" );
408     exit ( -2 );
409   }
410
411   /* loop forever, watching for events
412    */
413
414   while ( 1 ) {
415     struct input_event ev[64];
416
417     int fd = -1, rd, ret;
418     fd_set fdset;
419
420     FD_ZERO ( &fdset );
421
422     for (i = 0; i < 2; i++) {
423       if ( fds [ i ] != -1 ) {
424         FD_SET( fds [ i ], &fdset );
425       }
426     }
427
428     ret = select ( imaxfd + 1, &fdset, NULL, NULL, NULL );
429
430     if ( ret == -1 ) {
431       pnd_log ( pndn_error, "ERROR! select(2) failed with: %s\n", strerror ( errno ) );
432       continue; // retry!
433     }
434
435     for ( i = 0; i < 2; i++ ) {
436       if ( fds [ i ] != -1 && FD_ISSET ( fds [ i ], &fdset ) ) {
437         fd = fds [ i ];
438       }
439     }
440
441     /* buttons or keypad */
442     rd = read ( fd, ev, sizeof(struct input_event) * 64 );
443     if ( rd < (int) sizeof(struct input_event) ) {
444       pnd_log ( pndn_error, "ERROR! read(2) input_event failed with: %s\n", strerror ( errno ) );
445       break;
446     }
447
448     for (i = 0; i < rd / sizeof(struct input_event); i++ ) {
449
450       if ( ev[i].type == EV_SYN ) {
451         continue;
452       } else if ( ev[i].type == EV_KEY ) {
453
454         // do we even know about this key at all?
455         keycode_t *p = keycodes;
456         while ( p -> keycode != -1 ) {
457           if ( p -> keycode == ev [ i ].code ) {
458             break;
459           }
460           p++;
461         }
462
463         // if we do, hand it off to dispatcher to look up if we actually do something with it
464         if ( p -> keycode != -1 ) {
465           pnd_log ( pndn_debug, "Key Event: key %s [%d] value %d\n", p -> keyname, p -> keycode, ev [ i ].value );
466           dispatch_key ( p -> keycode, ev [ i ].value );
467         } else {
468           pnd_log ( pndn_warning, "Unknown Key Event: keycode %d value %d\n",  ev [ i ].code, ev [ i ].value );
469         }
470
471       } else if ( ev[i].type == EV_SW ) {
472
473         // do we even know about this event at all?
474         generic_event_t *p = generics;
475         while ( p -> code != -1 ) {
476           if ( p -> code == ev [ i ].code ) {
477             break;
478           }
479           p++;
480         }
481
482         // if we do, hand it off to dispatcher to look up if we actually do something with it
483         if ( p -> code != -1 ) {
484           pnd_log ( pndn_debug, "Generic Event: event %s [%d] value %d\n", p -> name, p -> code, ev [ i ].value );
485           dispatch_event ( p -> code, ev [ i ].value );
486         } else {
487           pnd_log ( pndn_warning, "Unknown Generic Event: code %d value %d\n",  ev [ i ].code, ev [ i ].value );
488         }
489
490       } else {
491         pnd_log ( pndn_debug, "DEBUG: Unexpected event type %i received\n", ev[i].type );
492         continue;
493       } // type?
494
495     } // for
496
497   } // while
498
499   for (i = 0; i < 2; i++) {
500     if ( i != 2 && fds [ i ] != -1 ) {
501       close (fds [ i ] );
502     }
503   }
504
505   return ( 0 );
506 } // main
507
508 // this should really register the keystate and time, and then another func to monitor
509 // time-passage and check the registered list and act on the event..
510 void dispatch_key ( int keycode, int val ) {
511   unsigned int i;
512
513   // val decodes as:
514   // 1 - down (pressed)
515   // 2 - down again (hold)
516   // 0 - up (released)
517
518   for ( i = 0; i < g_evmap_max; i++ ) {
519
520     if ( ( g_evmap [ i ].key_p ) &&
521          ( ((keycode_t*) (g_evmap [ i ].reqs)) -> keycode == keycode ) &&
522          ( g_evmap [ i ].script ) )
523     {
524
525       // is this a keydown or a keyup?
526       if ( val == 1 ) {
527         // keydown
528         g_evmap [ i ].keydown_time = time ( NULL );
529
530       } else if ( val == 0 ) {
531         // keyup
532
533         char holdtime [ 128 ];
534         sprintf ( holdtime, "%d", (int)( time(NULL) - g_evmap [ i ].keydown_time ) );
535
536         if ( time ( NULL ) - g_evmap [ i ].last_trigger_time >= g_minimum_separation ) {
537           int x;
538
539           g_evmap [ i ].last_trigger_time = time ( NULL );
540
541           pnd_log ( pndn_rem, "Will attempt to invoke: %s %s\n", g_evmap [ i ].script, holdtime );
542
543           if ( ( x = fork() ) < 0 ) {
544             pnd_log ( pndn_error, "ERROR: Couldn't fork()\n" );
545             exit ( -3 );
546           }
547
548           if ( x == 0 ) {
549             execl ( g_evmap [ i ].script, g_evmap [ i ].script, holdtime, (char*)NULL );
550             pnd_log ( pndn_error, "ERROR: Couldn't exec(%s)\n", g_evmap [ i ].script );
551             exit ( -4 );
552           }
553
554         } else {
555           pnd_log ( pndn_rem, "Skipping invokation.. falls within minimum_separation threshold\n" );
556         }
557
558       } // key up or down?
559
560       return;
561     } // found matching event for keycode
562
563   } // while
564
565   return;
566 }
567
568 void dispatch_event ( int code, int val ) {
569   unsigned int i;
570
571   // LID val decodes as:
572   // 1 - closing
573   // 0 - opening
574
575   for ( i = 0; i < g_evmap_max; i++ ) {
576
577     if ( ( g_evmap [ i ].key_p == 0 ) &&
578          ( ((generic_event_t*) (g_evmap [ i ].reqs)) -> code == code ) &&
579          ( g_evmap [ i ].script ) )
580     {
581
582       // just hand the code to the script (ie: 0 or 1 to script)
583       if ( time ( NULL ) - g_evmap [ i ].last_trigger_time >= g_minimum_separation ) {
584         int x;
585         char value [ 100 ];
586
587         sprintf ( value, "%d", val );
588
589         g_evmap [ i ].last_trigger_time = time ( NULL );
590
591         pnd_log ( pndn_rem, "Will attempt to invoke: %s %s\n", g_evmap [ i ].script, value );
592
593         if ( ( x = fork() ) < 0 ) {
594           pnd_log ( pndn_error, "ERROR: Couldn't fork()\n" );
595           exit ( -3 );
596         }
597
598         if ( x == 0 ) {
599           execl ( g_evmap [ i ].script, g_evmap [ i ].script, value, (char*)NULL );
600           pnd_log ( pndn_error, "ERROR: Couldn't exec(%s)\n", g_evmap [ i ].script );
601           exit ( -4 );
602         }
603
604       } else {
605         pnd_log ( pndn_rem, "Skipping invokation.. falls within minimum_separation threshold\n" );
606       }
607
608       return;
609     } // found matching event for keycode
610
611   } // while
612
613   return;
614 }
615
616 void sigchld_handler ( int n ) {
617
618   pnd_log ( pndn_rem, "---[ SIGCHLD received ]---\n" );
619
620   int status;
621   wait ( &status );
622
623   pnd_log ( pndn_rem, "     SIGCHLD done ]---\n" );
624
625   return;
626 }