Hacked around pndnotifyd so it supports two sets of paths now -- menu path and deskto...
[pandora-libraries.git] / apps / pndnotifyd.c
1
2 /* pndnotifyd - a daemon whose job is to monitor searchpaths for app changes (appearing, disappearing, changing).
3  * If a change is found, the discovery code is invoked and apps registered for the launchers to see
4  *
5  */
6
7 // TODO: Catch HUP and reparse config
8 // TODO: Should perhaps direct all printf's through a vsprintf handler to avoid redundant "if ! g_daemon_mode"
9 // TODO: During daemon mode, should perhaps syslog or log errors
10
11 #include <stdio.h>     // for stdio
12 #include <unistd.h>    // for exit()
13 #include <stdlib.h>    // for exit()
14 #define __USE_GNU /* for strcasestr */
15 #include <string.h>
16 #include <time.h>      // for time()
17 #include <ctype.h>     // for isdigit()
18 #include <sys/types.h> // for umask
19 #include <sys/stat.h>  // for umask
20 #include <dirent.h>    // for opendir()
21 #include <signal.h>    // for sigaction
22
23 #include "pnd_conf.h"
24 #include "pnd_container.h"
25 #include "pnd_apps.h"
26 #include "pnd_notify.h"
27 #include "../lib/pnd_pathiter.h"
28 #include "pnd_discovery.h"
29 #include "pnd_locate.h"
30 #include "pnd_pxml.h"
31 #include "pnd_utility.h"
32 #include "pnd_desktop.h"
33 #include "pnd_logger.h"
34
35 // this piece of code was simpler once; but need to grow it a bit and in a rush
36 // moving all these to globals rather than refactor the code a bit; tsk tsk..
37
38 // op mode; emitting stdout or no?
39 static unsigned char g_daemon_mode = 0;
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 // like discotest
50 char *configpath;
51 char *overridespath;
52 // daemon stuff
53 char *searchpath = NULL;
54 char *notifypath = NULL;
55 time_t createtime = 0; // all 'new' .destops are created at or after this time; prev are old.
56 // dotfiles; this used to be a single pai .. now two pairs, a little unwieldy; pnd_box it up?
57 char *desktop_dotdesktoppath = NULL;
58 char *desktop_iconpath = NULL;
59 char *desktop_appspath = NULL;
60 char *menu_dotdesktoppath = NULL;
61 char *menu_iconpath = NULL;
62 char *menu_appspath = NULL;
63 // pnd runscript
64 char *run_searchpath; // searchpath to find pnd_run.sh
65 char *run_script;     // name of pnd_run.sh script from config
66 char *pndrun;         // full path to located pnd_run.sh
67 char *pndhup = NULL;  // full path to located pnd_hup.sh
68 // notifier handle
69 pnd_notify_handle nh = 0;
70
71 // constants
72 #define PNDNOTIFYD_LOGLEVEL "pndnotifyd.loglevel"
73
74 // decl's
75 void consume_configuration ( void );
76 void setup_notifications ( void );
77 void sighup_handler ( int n );
78 void process_discoveries ( pnd_box_handle applist, char *emitdesktoppath, char *emiticonpath );
79 unsigned char perform_discoveries ( char *appspath, char *overridespath,
80                                     char *emitdesktoppath, char *emiticonpath );
81
82 int main ( int argc, char *argv[] ) {
83   // behaviour
84   unsigned char scanonlaunch = 1;
85   unsigned int interval_secs = 10;
86   // misc
87   int i;
88
89   /* iterate across args
90    */
91   for ( i = 1; i < argc; i++ ) {
92
93     if ( argv [ i ][ 0 ] == '-' && argv [ i ][ 1 ] == 'd' ) {
94       //printf ( "Going daemon mode. Silent running.\n" );
95       g_daemon_mode = 1;
96     } else if ( isdigit ( argv [ i ][ 0 ] ) ) {
97       interval_secs = atoi ( argv [ i ] );
98     } else if ( argv [ i ][ 0 ] == '-' && argv [ i ][ 1 ] == 'n' ) {
99       scanonlaunch = 0;
100     } else {
101       printf ( "%s [-d] [##]\n", argv [ 0 ] );
102       printf ( "-d\tDaemon mode; detach from terminal, chdir to /tmp, suppress output. Optional.\n" );
103       printf ( "-n\tDo not scan on launch; default is to run a scan for apps when %s is invoked.\n", argv [ 0 ] );
104       printf ( "##\tA numeric value is interpreted as number of seconds between checking for filesystem changes. Default %u.\n",
105                interval_secs );
106       printf ( "Signal: HUP the process to force reload of configuration and reset the notifier watch paths\n" );
107       exit ( 0 );
108     }
109
110   } // for
111
112   /* enable logging?
113    */
114   if ( g_daemon_mode ) {
115     // nada
116   } else {
117     pnd_log_set_filter ( pndn_rem );
118     pnd_log_set_pretext ( "pndnotifyd" );
119     pnd_log_to_stdout();
120     pnd_log ( pndn_rem, "log level starting as %u", pnd_log_get_filter() );
121   }
122
123   pnd_log ( pndn_rem, "Interval between checks is %u seconds\n", interval_secs );
124
125   // basic daemon set up
126   if ( g_daemon_mode ) {
127
128     // set a CWD somewhere else
129 #if 0
130     chdir ( "/tmp" );
131 #endif
132
133     // detach from terminal
134     if ( ( i = fork() ) < 0 ) {
135       pnd_log ( pndn_error, "ERROR: Couldn't fork()\n" );
136       exit ( i );
137     }
138     if ( i ) {
139       exit ( 0 ); // exit parent
140     }
141     setsid();
142
143     // umask
144     umask ( 022 ); // emitted files can be rwxr-xr-x
145     
146   } // set up daemon
147
148   /* parse configs
149    */
150
151   consume_configuration();
152
153   /* startup
154    */
155
156   pnd_log ( pndn_rem, "PXML overrides searchpath is '%s'\n", overridespath );
157   pnd_log ( pndn_rem, "Notify searchpath is '%s'\n", notifypath );
158
159   pnd_log ( pndn_rem, "Desktop apps ---------------------------------\n" );
160   pnd_log ( pndn_rem, "Apps searchpath is '%s'\n", desktop_appspath );
161   pnd_log ( pndn_rem, ".desktop files emit to '%s'\n", desktop_dotdesktoppath );
162   pnd_log ( pndn_rem, ".desktop icon files emit to '%s'\n", desktop_iconpath );
163
164   pnd_log ( pndn_rem, "Menu apps ---------------------------------\n" );
165   pnd_log ( pndn_rem, "Apps searchpath is '%s'\n", menu_appspath );
166   pnd_log ( pndn_rem, ".desktop files emit to '%s'\n", menu_dotdesktoppath );
167   pnd_log ( pndn_rem, ".desktop icon files emit to '%s'\n", menu_iconpath );
168
169   /* set up signal handler
170    */
171   sigset_t ss;
172   sigemptyset ( &ss );
173
174   struct sigaction siggy;
175   siggy.sa_handler = sighup_handler;
176   siggy.sa_mask = ss; /* implicitly blocks the origin signal */
177   siggy.sa_flags = 0; /* don't need anything */
178
179   sigaction ( SIGHUP, &siggy, NULL );
180
181   /* set up notifies
182    */
183
184   // if we're gong to scan on launch, it'll set things right up and then set up notifications.
185   // if no scan on launch, we need to set the notif's up now.
186   //if ( ! scanonlaunch ) {
187   setup_notifications();
188   //}
189
190   /* daemon main loop
191    */
192   while ( 1 ) {
193
194     // need to rediscover?
195     if ( scanonlaunch ||
196          pnd_notify_rediscover_p ( nh ) )
197     {
198       createtime = time ( NULL ); // all 'new' .destops are created at or after this time; prev are old.
199
200       // if this was a forced scan, lets not do that next iteration
201       if ( scanonlaunch ) {
202         scanonlaunch = 0;
203       }
204
205       // by this point, the watched directories have notified us that something of relevent
206       // has occurred; we should be clever, but we're not, so just re-brute force the
207       // discovery and spit out .desktop files..
208       pnd_log ( pndn_rem, "------------------------------------------------------\n" );
209       pnd_log ( pndn_rem, "Changes within watched paths .. performing re-discover!\n" );
210
211       /* run the discovery
212        */
213
214       pnd_log ( pndn_rem, "Scanning desktop paths----------------------------\n" );
215       if ( ! perform_discoveries ( desktop_appspath, overridespath, desktop_dotdesktoppath, desktop_iconpath ) ) {
216         pnd_log ( pndn_rem, "No applications found in desktop search path\n" );
217       }
218
219       pnd_log ( pndn_rem, "Scanning menu paths----------------------------\n" );
220       if ( ! perform_discoveries ( menu_appspath, overridespath, menu_dotdesktoppath, menu_iconpath ) ) {
221         pnd_log ( pndn_rem, "No applications found in menu search path\n" );
222       }
223
224       // if we've got a hup script located, lets invoke it
225       if ( pndhup ) {
226         pnd_log ( pndn_rem, "Invoking hup script '%s'.\n", pndhup );
227         pnd_exec_no_wait_1 ( pndhup, NULL );
228       }
229
230       // since its entirely likely new directories have been found (ie: SD with a directory structure was inserted)
231       // we should re-apply watches to catch all these new directories; ie: user might use on-device browser to
232       // drop in new applications, or use the shell to juggle them around, or any number of activities.
233       //setup_notifications();
234
235     } // need to rediscover?
236
237     // lets not eat up all the CPU
238     // should use an alarm or select() or something
239     sleep ( interval_secs );
240
241   } // while
242
243   /* shutdown
244    */
245   pnd_notify_shutdown ( nh );
246
247   return ( 0 );
248 }
249
250 void consume_configuration ( void ) {
251
252   // attempt to fetch a sensible default searchpath for configs
253   configpath = pnd_conf_query_searchpath();
254
255   // attempt to fetch the apps config to pick up a searchpath
256   pnd_conf_handle apph;
257
258   apph = pnd_conf_fetch_by_id ( pnd_conf_apps, configpath );
259
260   if ( apph ) {
261
262     overridespath = pnd_conf_get_as_char ( apph, PND_PXML_OVERRIDE_KEY );
263
264     if ( ! overridespath ) {
265       overridespath = PND_PXML_OVERRIDE_SEARCHPATH;
266     }
267
268     notifypath = pnd_conf_get_as_char ( apph, PND_APPS_NOTIFY_KEY );
269
270     if ( ! notifypath ) {
271       notifypath = PND_APPS_NOTIFYPATH;
272     }
273
274   } else {
275     // couldn't find a useful app search path so use the default
276     overridespath = PND_PXML_OVERRIDE_SEARCHPATH;
277     notifypath = PND_APPS_NOTIFYPATH;
278   }
279
280   // attempt to figure out where to drop dotfiles .. now that we're going
281   // multi-target we see the limit of my rudimentary conf-file parser; should
282   // just parse to an array of targets, rather that hardcoding two, but
283   // on the other hand, don't likely see the need for more than two? (famous
284   // last words.)
285   pnd_conf_handle desktoph;
286
287   desktoph = pnd_conf_fetch_by_id ( pnd_conf_desktop, configpath );
288
289   // for 'desktop' main applications
290   if ( desktoph ) {
291     desktop_dotdesktoppath = pnd_conf_get_as_char ( desktoph, PND_DESKTOP_DOTDESKTOP_PATH_KEY );
292     desktop_iconpath = pnd_conf_get_as_char ( desktoph, PND_DESKTOP_ICONS_PATH_KEY );
293     desktop_appspath = pnd_conf_get_as_char ( desktoph, PND_DESKTOP_SEARCH_KEY );
294   }
295
296   if ( ! desktop_dotdesktoppath ) {
297     desktop_dotdesktoppath = PND_DESKTOP_DOTDESKTOP_PATH_DEFAULT;
298   }
299
300   if ( ! desktop_iconpath ) {
301     desktop_iconpath = PND_DESKTOP_ICONS_PATH_DEFAULT;
302   }
303
304   if ( ! desktop_appspath ) {
305     desktop_appspath = PND_DESKTOP_SEARCH_PATH_DEFAULT;
306   }
307
308   // for 'menu' applications
309   if ( desktoph ) {
310     menu_dotdesktoppath = pnd_conf_get_as_char ( desktoph, PND_MENU_DOTDESKTOP_PATH_KEY );
311     menu_iconpath = pnd_conf_get_as_char ( desktoph, PND_MENU_ICONS_PATH_KEY );
312     menu_appspath = pnd_conf_get_as_char ( desktoph, PND_MENU_SEARCH_KEY );
313   }
314
315   /* try to locate a runscript and optional hupscript
316    */
317
318   if ( apph ) {
319     run_searchpath = pnd_conf_get_as_char ( apph, PND_PNDRUN_SEARCHPATH_KEY );
320     run_script = pnd_conf_get_as_char ( apph, PND_PNDRUN_KEY );
321     pndrun = NULL;
322
323     if ( ! run_searchpath ) {
324       run_searchpath = PND_APPS_SEARCHPATH;
325       run_script = PND_PNDRUN_FILENAME;
326     }
327
328     if ( pnd_conf_get_as_int ( apph, PNDNOTIFYD_LOGLEVEL ) != PND_CONF_BADNUM ) {
329       pnd_log_set_filter ( pnd_conf_get_as_int ( apph, PNDNOTIFYD_LOGLEVEL ) );
330       pnd_log ( pndn_rem, "config file causes loglevel to change to %u", pnd_log_get_filter() );
331     }
332
333   } else {
334     run_searchpath = NULL;
335     run_script = NULL;
336     pndrun = PND_PNDRUN_DEFAULT;
337   }
338
339   if ( ! pndrun ) {
340     pndrun = pnd_locate_filename ( run_searchpath, run_script );
341
342     if ( pndrun ) {
343       pndrun = strdup ( pndrun ); // so we don't just use the built in buffer; next locate will overwrite it
344     } else {
345       pndrun = PND_PNDRUN_DEFAULT;
346     }
347
348   }
349
350   if ( desktoph && run_searchpath ) {
351     char *t;
352
353     if ( ( t = pnd_conf_get_as_char ( desktoph, PND_PNDHUP_KEY ) ) ) {
354       pndhup = pnd_locate_filename ( run_searchpath, t );
355
356       if ( pndhup ) {
357         pndhup = strdup ( pndhup ); // so we don't just use the built in buffer; next locate will overwrite it
358       }
359
360 #if 0 // don't enable this; if no key in config, we don't want to bother hupping
361     } else {
362       pndhup = pnd_locate_filename ( run_searchpath, PND_PNDHUP_FILENAME );
363 #endif
364     }
365
366   }
367
368   // debug
369   if ( run_searchpath ) pnd_log ( pndn_rem, "Locating pnd run in %s\n", run_searchpath );
370   if ( run_script ) pnd_log ( pndn_rem, "Locating pnd runscript as %s\n", run_script );
371   if ( pndrun ) pnd_log ( pndn_rem, "pndrun is %s\n", pndrun );
372   if ( pndhup ) {
373     pnd_log ( pndn_rem, "pndhup is %s\n", pndhup );
374   } else {
375     pnd_log ( pndn_rem, "No pndhup found (which is fine.)\n" );
376   }
377
378   /* handle globbing or variable substitution
379    */
380   desktop_dotdesktoppath = pnd_expand_tilde ( strdup ( desktop_dotdesktoppath ) );
381   desktop_iconpath = pnd_expand_tilde ( strdup ( desktop_iconpath ) );
382   mkdir ( desktop_dotdesktoppath, 0777 );
383   mkdir ( desktop_iconpath, 0777 );
384
385   if ( menu_dotdesktoppath ) {
386     menu_dotdesktoppath = pnd_expand_tilde ( strdup ( menu_dotdesktoppath ) );
387     mkdir ( menu_dotdesktoppath, 0777 );
388   }
389   if ( menu_iconpath ) {
390     menu_iconpath = pnd_expand_tilde ( strdup ( menu_iconpath ) );
391     mkdir ( menu_iconpath, 0777 );
392   }
393
394   // done
395   return;
396 }
397
398 void setup_notifications ( void ) {
399   searchpath = notifypath;
400
401   // if this is first time through, we can just set it up; for subsequent times
402   // through, we need to close existing fd and re-open it, since we're too lame
403   // to store the list of watches and 'rm' them
404 #if 1
405   if ( nh ) {
406     pnd_notify_shutdown ( nh );
407     nh = 0;
408   }
409 #endif
410
411   // set up a new set of notifies
412   if ( ! nh ) {
413     nh = pnd_notify_init();
414   }
415
416   if ( ! nh ) {
417     pnd_log ( pndn_rem, "INOTIFY failed to init.\n" );
418     exit ( -1 );
419   }
420
421 #if 0
422   pnd_log ( pndn_rem, "INOTIFY is up.\n" );
423 #endif
424
425   SEARCHPATH_PRE
426   {
427
428     pnd_log ( pndn_rem, "Watching path '%s' and its descendents.\n", buffer );
429     pnd_notify_watch_path ( nh, buffer, PND_NOTIFY_RECURSE );
430
431   }
432   SEARCHPATH_POST
433
434   return;
435 }
436
437 void sighup_handler ( int n ) {
438
439   pnd_log ( pndn_rem, "---[ SIGHUP received ]---\n" );
440
441   // reparse config files
442   consume_configuration();
443
444   // re set up the notifier watches
445   setup_notifications();
446
447   return;
448 }
449
450 // This very recently was inline code; just slight refactor to functionize it so that it can be
451 // reused in a couple of places. Simple code with simple design quickly became too large for
452 // its simple design; should revisit a lot of these little things..
453 void process_discoveries ( pnd_box_handle applist, char *emitdesktoppath, char *emiticonpath ) {
454   pnd_disco_t *d = pnd_box_get_head ( applist );
455
456   while ( d ) {
457
458     pnd_log ( pndn_rem, "Found app: %s\n", pnd_box_get_key ( d ) );
459
460     // check if icon already exists (from a previous extraction say); if so, we needn't
461     // do it again
462     char existingpath [ FILENAME_MAX ];
463     sprintf ( existingpath, "%s/%s.png", emiticonpath, d -> unique_id );
464
465     struct stat dirs;
466     if ( stat ( existingpath, &dirs ) == 0 ) {
467       // icon seems to exist, so just crib the location into the .desktop
468
469       pnd_log ( pndn_rem, "  Found icon already existed, so reusing it! %s\n", existingpath );
470
471       if ( d -> icon ) {
472         free ( d -> icon );
473       }
474       d -> icon = strdup ( existingpath );
475
476     } else {
477       // icon seems unreadable or does not exist; lets try to create it..
478
479       pnd_log ( pndn_debug, "  Icon not already present, so trying to write it! %s\n", existingpath );
480
481       // attempt to create icon files; if successful, alter the disco struct to contain new
482       // path, otherwise leave it alone (since it could be a generic icon reference..)
483       if ( pnd_emit_icon ( emiticonpath, d ) ) {
484         // success; fix up icon path to new one..
485         if ( d -> icon ) {
486           free ( d -> icon );
487         }
488         d -> icon = strdup ( existingpath );
489       } else {
490         pnd_log ( pndn_debug, "  WARN: Couldn't write out icon %s\n", existingpath );
491       }
492
493     } // icon already exists?
494
495     // create the .desktop file
496     if ( pnd_emit_dotdesktop ( emitdesktoppath, pndrun, d ) ) {
497       // add a watch onto the newly created .desktop?
498 #if 0
499       char buffer [ FILENAME_MAX ];
500       sprintf ( buffer, "%s/%s", emitdesktoppath, d -> unique_id );
501       pnd_notify_watch_path ( nh, buffer, PND_NOTIFY_RECURSE );
502 #endif
503     } else {
504       pnd_log ( pndn_rem, "ERROR: Error creating .desktop file for app: %s\n", pnd_box_get_key ( d ) );
505     }
506
507     // next!
508     d = pnd_box_get_next ( d );
509
510   } // while applist
511
512   return;
513 }
514
515 // returns true if any applications were found
516 unsigned char perform_discoveries ( char *appspath, char *overridespath,              // args to do discovery
517                                     char *emitdesktoppath, char *emiticonpath )       // args to do emitting
518 {
519   pnd_box_handle applist;
520
521   // attempt to auto-discover applications in the given path
522   applist = pnd_disco_search ( appspath, overridespath );
523
524   if ( ! applist ) {
525     return ( 0 );
526   }
527
528   process_discoveries ( applist, emitdesktoppath, emiticonpath );
529
530   // run a clean up, to remove any dotdesktop files that we didn't
531   // just now create (that seem to have been created by pndnotifyd
532   // previously.) This allows SD eject (or .pnd remove) to remove
533   // an app from the launcher
534   //   NOTE: Could opendir and iterate across all .desktop files,
535   // removing any that have Source= something else, and that the
536   // app name is not in the list found in applist box above. But
537   // a cheesy simple way right now is to just remove .desktop files
538   // that have a last mod time prior to the time we stored above.
539   {
540     DIR *dir;
541
542     if ( ( dir = opendir ( emitdesktoppath ) ) ) {
543       struct dirent *dirent;
544       struct stat dirs;
545       char buffer [ FILENAME_MAX ];
546
547       while ( ( dirent = readdir ( dir ) ) ) {
548
549         // file is a .desktop?
550         if ( strstr ( dirent -> d_name, ".desktop" ) == NULL ) {
551           continue;
552         }
553
554         // figure out full path
555         sprintf ( buffer, "%s/%s", emitdesktoppath, dirent -> d_name );
556
557         // file was previously created by libpnd; check Source= line
558         // logic: default to 'yes' (in case we can't open the file for some reason)
559         //        if we can open the file, default to no and look for the source flag we added; if
560         //          that matches then we know its libpnd created, otherwise assume not.
561         unsigned char source_libpnd = 1;
562         {
563           char line [ 256 ];
564           FILE *grep = fopen ( buffer, "r" );
565           if ( grep ) {
566             source_libpnd = 0;
567             while ( fgets ( line, 255, grep ) ) {
568               if ( strcasestr ( line, PND_DOTDESKTOP_SOURCE ) ) {
569                 source_libpnd = 2;
570               }
571             } // while
572             fclose ( grep );
573           }
574         }
575         if ( source_libpnd ) {
576 #if 0
577           pnd_log ( pndn_rem,
578                     "File '%s' appears to have been created by libpnd so candidate for delete: %u\n", buffer, source_libpnd );
579 #endif
580         } else {
581 #if 0
582           pnd_log ( pndn_rem, "File '%s' appears NOT to have been created by libpnd, so leave it alone\n", buffer );
583 #endif
584           continue; // skip deleting it
585         }
586
587         // file is 'new'?
588         if ( stat ( buffer, &dirs ) == 0 ) {
589           if ( dirs.st_mtime >= createtime ) {
590 #if 0
591             pnd_log ( pndn_rem, "File '%s' seems 'new', so leave it alone.\n", buffer );
592 #endif
593             continue; // skip deleting it
594           }
595         }
596
597         // by this point, the .desktop file must be 'old' and created by pndnotifyd
598         // previously, so can remove it
599         pnd_log ( pndn_rem, "File '%s' seems nolonger relevent; removing it.\n", dirent -> d_name );
600         unlink ( buffer );
601
602       } // while getting filenames from dir
603
604       closedir ( dir );
605     }
606
607   } // purge old .desktop files
608
609   //WARN: MEMORY LEAK HERE
610   pnd_log ( pndn_debug, "pndnotifyd - memory leak here - perform_discoveries()\n" );
611   pnd_box_delete ( applist ); // does not free the disco_t contents!
612
613   return ( 1 );
614 }