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