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