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