Reduce over-icon-generation due to multiapps
[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 #include <stdio.h>     // for stdio
8 #include <unistd.h>    // for exit()
9 #include <stdlib.h>    // for exit()
10 #define __USE_GNU /* for strcasestr */
11 #include <string.h>
12 #include <time.h>      // for time()
13 #include <ctype.h>     // for isdigit()
14 #include <sys/types.h> // for umask
15 #include <sys/stat.h>  // for umask
16 #include <dirent.h>    // for opendir()
17 #include <signal.h>    // for sigaction
18
19 #include "pnd_conf.h"
20 #include "pnd_container.h"
21 #include "pnd_apps.h"
22 #include "pnd_notify.h"
23 #include "../lib/pnd_pathiter.h"
24 #include "pnd_discovery.h"
25 #include "pnd_locate.h"
26 #include "pnd_pxml.h"
27 #include "pnd_utility.h"
28 #include "pnd_desktop.h"
29 #include "pnd_logger.h"
30 #include "pnd_dbusnotify.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 typedef enum {
39   pndn_debug = 0,
40   pndn_rem,          // will set default log level to here, so 'debug' is omitted
41   pndn_warning,
42   pndn_error,
43   pndn_none
44 } pndnotify_loglevels_e;
45
46 // like discotest
47 char *configpath;
48 char *overridespath;
49 // daemon stuff
50 char *searchpath = NULL;
51 char *notifypath = NULL;
52 time_t createtime = 0; // all 'new' .destops are created at or after this time; prev are old.
53 // dotfiles; this used to be a single pai .. now two pairs, a little unwieldy; pnd_box it up?
54 char *desktop_dotdesktoppath = NULL;
55 char *desktop_iconpath = NULL;
56 char *desktop_appspath = NULL;
57 char *menu_dotdesktoppath = NULL;
58 char *menu_iconpath = NULL;
59 char *menu_appspath = NULL;
60 // pnd runscript
61 char *run_searchpath; // searchpath to find pnd_run.sh
62 char *run_script;     // name of pnd_run.sh script from config
63 char *pndrun;         // full path to located pnd_run.sh
64 char *pndhup = NULL;  // full path to located pnd_hup.sh
65 // default username
66 char g_username [ 128 ]; // since we have to wait for login (!!), store username here
67 // notifier handle
68 pnd_notify_handle nh = 0;
69 pnd_dbusnotify_handle dbh = 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 sigint_handler ( int n );
78 void sighup_handler ( int n );
79 void process_discoveries ( pnd_box_handle applist, char *emitdesktoppath, char *emiticonpath );
80 unsigned char perform_discoveries ( char *appspath, char *overridespath,
81                                     char *emitdesktoppath, char *emiticonpath );
82
83 int main ( int argc, char *argv[] ) {
84   // behaviour
85   unsigned char scanonlaunch = 1;
86   unsigned int interval_secs = 5;
87   int logall = -1; // -1 means normal logging rules; >=0 means log all!
88   // misc
89   int i;
90
91   /* iterate across args
92    */
93   for ( i = 1; i < argc; i++ ) {
94
95     if ( argv [ i ][ 0 ] == '-' && argv [ i ][ 1 ] == 'd' ) {
96       //printf ( "Going daemon mode. Silent running.\n" );
97       g_daemon_mode = 1;
98     } else if ( isdigit ( argv [ i ][ 0 ] ) ) {
99       interval_secs = atoi ( argv [ i ] );
100     } else if ( argv [ i ][ 0 ] == '-' && argv [ i ][ 1 ] == 'n' ) {
101       scanonlaunch = 0;
102     } else if ( argv [ i ][ 0 ] == '-' && argv [ i ][ 1 ] == 'l' ) {
103
104       if ( isdigit ( argv [ i ][ 2 ] ) ) {
105         unsigned char x = atoi ( argv [ i ] + 2 );
106         if ( x >= 0 &&
107              x < pndn_none )
108         {
109           logall = x;
110         }
111       } else {
112         logall = 0;
113       }
114
115     } else {
116       printf ( "%s [-d] [##]\n", argv [ 0 ] );
117       printf ( "-d\tDaemon mode; detach from terminal, chdir to /tmp, suppress output. Optional.\n" );
118       printf ( "-n\tDo not scan on launch; default is to run a scan for apps when %s is invoked.\n", argv [ 0 ] );
119       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/pndnotifyd.log\n" );
120       printf ( "##\tA numeric value is interpreted as number of seconds between checking for filesystem changes. Default %u.\n",
121                interval_secs );
122       printf ( "Signal: HUP the process to force reload of configuration and reset the notifier watch paths\n" );
123       exit ( 0 );
124     }
125
126   } // for
127
128   /* enable logging?
129    */
130   pnd_log_set_pretext ( "pndnotifyd" );
131   pnd_log_set_flush ( 1 );
132
133   if ( logall == -1 ) {
134     // standard logging; non-daemon versus daemon
135
136     if ( g_daemon_mode ) {
137       // nada
138     } else {
139       pnd_log_set_filter ( pndn_rem );
140       pnd_log_to_stdout();
141     }
142
143   } else {
144     FILE *f;
145
146     f = fopen ( "/tmp/pndnotifyd.log", "w" );
147
148     if ( f ) {
149       pnd_log_set_filter ( logall );
150       pnd_log_to_stream ( f );
151       pnd_log ( pndn_rem, "logall mode - logging to /tmp/pndnotifyd.log\n" );
152     }
153
154     if ( logall == pndn_debug ) {
155       pnd_log_set_buried_logging ( 1 ); // log the shit out of it
156       pnd_log ( pndn_rem, "logall mode 0 - turned on buried logging\n" );
157     }
158
159   } // logall
160
161   pnd_log ( pndn_rem, "%s built %s %s", argv [ 0 ], __DATE__, __TIME__ );
162
163   pnd_log ( pndn_rem, "log level starting as %u", pnd_log_get_filter() );
164
165   pnd_log ( pndn_rem, "Interval between checks is %u seconds\n", interval_secs );
166
167   // check if inotify is awake yet; if not, try waiting for awhile to see if it does
168   pnd_log ( pndn_rem, "Starting INOTIFY test; should be instant, but may take awhile...\n" );
169
170   if ( ! pnd_notify_wait_until_ready ( 120 /* seconds */ ) ) {
171     pnd_log ( pndn_error, "ERROR: INOTIFY refuses to be useful and quite awhile has passed. Bailing out.\n" );
172     return ( -1 );
173   }
174
175   pnd_log ( pndn_rem, "INOTIFY seems to be useful, whew.\n" );
176
177   // basic daemon set up
178   if ( g_daemon_mode ) {
179
180     // set a CWD somewhere else
181 #if 0
182     chdir ( "/tmp" );
183 #endif
184
185     // detach from terminal
186     if ( ( i = fork() ) < 0 ) {
187       pnd_log ( pndn_error, "ERROR: Couldn't fork()\n" );
188       exit ( i );
189     }
190     if ( i ) {
191       exit ( 0 ); // exit parent
192     }
193     setsid();
194
195     // umask
196     umask ( 022 ); // emitted files can be rwxr-xr-x
197     
198   } // set up daemon
199
200   // wait for a user to be logged in - we should probably get hupped when a user logs in, so we can handle
201   // log-out and back in again, with SDs popping in and out between..
202   pnd_log ( pndn_rem, "Checking to see if a user is logged in\n" );
203   while ( 1 ) {
204     if ( pnd_check_login ( g_username, 127 ) ) {
205       break;
206     }
207     pnd_log ( pndn_debug, "  No one logged in yet .. spinning.\n" );
208     sleep ( 2 );
209   } // spin
210   pnd_log ( pndn_rem, "Looks like user '%s' is in, continue.\n", g_username );
211
212   /* parse configs
213    */
214
215   consume_configuration();
216
217   /* startup
218    */
219
220   pnd_log ( pndn_rem, "PXML overrides searchpath is '%s'\n", overridespath );
221   pnd_log ( pndn_rem, "Notify searchpath is '%s'\n", notifypath );
222
223   pnd_log ( pndn_rem, "Desktop apps ---------------------------------\n" );
224   pnd_log ( pndn_rem, "Apps searchpath is '%s'\n", desktop_appspath );
225   pnd_log ( pndn_rem, ".desktop files emit to '%s'\n", desktop_dotdesktoppath );
226   pnd_log ( pndn_rem, ".desktop icon files emit to '%s'\n", desktop_iconpath );
227
228   pnd_log ( pndn_rem, "Menu apps ---------------------------------\n" );
229   pnd_log ( pndn_rem, "Apps searchpath is '%s'\n", menu_appspath );
230   pnd_log ( pndn_rem, ".desktop files emit to '%s'\n", menu_dotdesktoppath );
231   pnd_log ( pndn_rem, ".desktop icon files emit to '%s'\n", menu_iconpath );
232
233   /* set up signal handler
234    */
235   sigset_t ss;
236   sigemptyset ( &ss );
237
238   struct sigaction siggy;
239   siggy.sa_handler = sighup_handler;
240   siggy.sa_mask = ss; /* implicitly blocks the origin signal */
241   siggy.sa_flags = 0; /* don't need anything */
242
243   sigaction ( SIGHUP, &siggy, NULL );
244
245   siggy.sa_handler = sigint_handler;
246   sigaction ( SIGINT, &siggy, NULL );
247
248   /* set up notifies
249    */
250
251   // if we're gong to scan on launch, it'll set things right up and then set up notifications.
252   // if no scan on launch, we need to set the notif's up now.
253   //if ( ! scanonlaunch ) {
254   setup_notifications();
255   //}
256
257   dbh = pnd_dbusnotify_init();
258
259   /* daemon main loop
260    */
261   unsigned char watch_inotify, watch_dbus;
262   while ( 1 ) {
263
264     watch_dbus = 0;
265     watch_inotify = 0;
266
267     if ( dbh ) {
268       watch_dbus = pnd_dbusnotify_rediscover_p ( dbh );
269     }
270
271     if ( ! watch_dbus && nh ) {
272       watch_inotify = pnd_notify_rediscover_p ( nh );
273     }
274
275     // need to rediscover?
276     if ( scanonlaunch || watch_inotify || watch_dbus ) {
277
278       // by this point, the watched directories have notified us that something of relevent
279       // has occurred; we should be clever, but we're not, so just re-brute force the
280       // discovery and spit out .desktop files..
281       pnd_log ( pndn_rem, "------------------------------------------------------\n" );
282
283       pnd_log ( pndn_rem, "System changes detected in dbus or watched paths .. performing re-discover!\n" );
284
285       // if this was a forced scan, lets not do that next iteration
286       if ( scanonlaunch ) {
287         pnd_log ( pndn_rem, "scan-on-first-launch detected an event\n" );
288         scanonlaunch = 0;
289       }
290
291       if ( watch_inotify ) {
292         pnd_log ( pndn_rem, "inotify detected an event\n" );
293       }
294
295       if ( watch_dbus ) {
296         pnd_log ( pndn_rem, "dbusnotify detected an event\n" );
297         pnd_notify_shutdown ( nh );
298         nh = 0;
299       }
300
301       if ( time ( NULL ) - createtime <= 2 ) {
302         pnd_log ( pndn_rem, "Rediscovery request comes to soon after previous discovery; skipping.\n" );
303         sleep ( interval_secs );
304         continue;
305       }
306
307       pnd_log ( pndn_rem, "------------------------------------------------------\n" );
308
309       createtime = time ( NULL ); // all 'new' .destops are created at or after this time; prev are old.
310
311       /* run the discovery
312        */
313
314       pnd_log ( pndn_rem, "  Scanning desktop paths----------------------------\n" );
315       if ( ! perform_discoveries ( desktop_appspath, overridespath, desktop_dotdesktoppath, desktop_iconpath ) ) {
316         pnd_log ( pndn_rem, "    No applications found in desktop search path\n" );
317       }
318
319       if ( menu_appspath && menu_dotdesktoppath && menu_iconpath ) {
320         pnd_log ( pndn_rem, "  Scanning menu paths----------------------------\n" );
321         if ( ! perform_discoveries ( menu_appspath, overridespath, menu_dotdesktoppath, menu_iconpath ) ) {
322           pnd_log ( pndn_rem, "    No applications found in menu search path\n" );
323         }
324       }
325
326       // if we've got a hup script located, lets invoke it
327       if ( pndhup ) {
328         pnd_log ( pndn_rem, "Invoking hup script '%s'.\n", pndhup );
329         pnd_exec_no_wait_1 ( pndhup, NULL );
330       }
331
332       // since its entirely likely new directories have been found (ie: SD with a directory structure was inserted)
333       // we should re-apply watches to catch all these new directories; ie: user might use on-device browser to
334       // drop in new applications, or use the shell to juggle them around, or any number of activities.
335       if ( watch_dbus ) {
336         setup_notifications();
337       }
338
339     } // need to rediscover?
340
341     // lets not eat up all the CPU
342     // should use an alarm or select() or something -- I mean really, why aren't I putting interval_secs into
343     // the select() call above in pnd_notify_whatsitcalled()? -- but lets not break this right before release shall we
344     // NOTE: Oh right, I remember now -- inotify will spam when a card is inserted, and it will not be instantaneoous..
345     // the events will dribble in over a second. So this sleep is a lame trick that generally works. I really should
346     // do select(), and then when it returns just spin for a couple seconds slurping up events until no more and a thresh-hold
347     // time is hit, but this will do for now. I suck.
348     sleep ( interval_secs );
349
350   } // while
351
352   /* shutdown
353    */
354   pnd_notify_shutdown ( nh );
355   pnd_dbusnotify_shutdown ( dbh );
356
357   return ( 0 );
358 }
359
360 void consume_configuration ( void ) {
361
362   // attempt to fetch a sensible default searchpath for configs
363   configpath = pnd_conf_query_searchpath();
364
365   // attempt to fetch the apps config to pick up a searchpath
366   pnd_conf_handle apph;
367
368   apph = pnd_conf_fetch_by_id ( pnd_conf_apps, configpath );
369
370   if ( apph ) {
371
372     overridespath = pnd_conf_get_as_char ( apph, PND_PXML_OVERRIDE_KEY );
373
374     if ( ! overridespath ) {
375       overridespath = PND_PXML_OVERRIDE_SEARCHPATH;
376     }
377
378     notifypath = pnd_conf_get_as_char ( apph, PND_APPS_NOTIFY_KEY );
379
380     if ( ! notifypath ) {
381       notifypath = PND_APPS_NOTIFYPATH;
382     }
383
384   } else {
385     // couldn't find a useful app search path so use the default
386     overridespath = PND_PXML_OVERRIDE_SEARCHPATH;
387     notifypath = PND_APPS_NOTIFYPATH;
388   }
389
390   // attempt to figure out where to drop dotfiles .. now that we're going
391   // multi-target we see the limit of my rudimentary conf-file parser; should
392   // just parse to an array of targets, rather that hardcoding two, but
393   // on the other hand, don't likely see the need for more than two? (famous
394   // last words.)
395   pnd_conf_handle desktoph;
396
397   desktoph = pnd_conf_fetch_by_id ( pnd_conf_desktop, configpath );
398
399   // for 'desktop' main applications
400   if ( desktoph ) {
401     desktop_dotdesktoppath = pnd_conf_get_as_char ( desktoph, PND_DESKTOP_DOTDESKTOP_PATH_KEY );
402     desktop_iconpath = pnd_conf_get_as_char ( desktoph, PND_DESKTOP_ICONS_PATH_KEY );
403     desktop_appspath = pnd_conf_get_as_char ( desktoph, PND_DESKTOP_SEARCH_KEY );
404   }
405
406   if ( ! desktop_dotdesktoppath ) {
407     desktop_dotdesktoppath = PND_DESKTOP_DOTDESKTOP_PATH_DEFAULT;
408   }
409
410   if ( ! desktop_iconpath ) {
411     desktop_iconpath = PND_DESKTOP_ICONS_PATH_DEFAULT;
412   }
413
414   if ( ! desktop_appspath ) {
415     desktop_appspath = PND_DESKTOP_SEARCH_PATH_DEFAULT;
416   }
417
418   // for 'menu' applications
419   if ( desktoph ) {
420     menu_dotdesktoppath = pnd_conf_get_as_char ( desktoph, PND_MENU_DOTDESKTOP_PATH_KEY );
421     menu_iconpath = pnd_conf_get_as_char ( desktoph, PND_MENU_ICONS_PATH_KEY );
422     menu_appspath = pnd_conf_get_as_char ( desktoph, PND_MENU_SEARCH_KEY );
423   }
424
425   /* try to locate a runscript and optional hupscript
426    */
427
428   if ( apph ) {
429     run_searchpath = pnd_conf_get_as_char ( apph, PND_PNDRUN_SEARCHPATH_KEY );
430     run_script = pnd_conf_get_as_char ( apph, PND_PNDRUN_KEY );
431     pndrun = NULL;
432
433     if ( ! run_searchpath ) {
434       run_searchpath = PND_APPS_SEARCHPATH;
435       run_script = PND_PNDRUN_FILENAME;
436     }
437
438     if ( pnd_conf_get_as_int ( apph, PNDNOTIFYD_LOGLEVEL ) != PND_CONF_BADNUM ) {
439       if ( pnd_log_do_buried_logging() == 0 ) {
440         pnd_log_set_filter ( pnd_conf_get_as_int ( apph, PNDNOTIFYD_LOGLEVEL ) );
441         pnd_log ( pndn_rem, "config file causes loglevel to change to %u", pnd_log_get_filter() );
442       } else {
443         pnd_log ( pndn_rem, "-l command line suppresses log level change in config file\n" );
444       }
445     }
446
447   } else {
448     run_searchpath = NULL;
449     run_script = NULL;
450     pndrun = PND_PNDRUN_DEFAULT;
451   }
452
453   if ( ! pndrun ) {
454     pndrun = pnd_locate_filename ( run_searchpath, run_script );
455
456     if ( pndrun ) {
457       pndrun = strdup ( pndrun ); // so we don't just use the built in buffer; next locate will overwrite it
458     } else {
459       pndrun = PND_PNDRUN_DEFAULT;
460     }
461
462   }
463
464   if ( desktoph && run_searchpath ) {
465     char *t;
466
467     if ( ( t = pnd_conf_get_as_char ( desktoph, PND_PNDHUP_KEY ) ) ) {
468       pndhup = pnd_locate_filename ( run_searchpath, t );
469
470       if ( pndhup ) {
471         pndhup = strdup ( pndhup ); // so we don't just use the built in buffer; next locate will overwrite it
472       }
473
474 #if 0 // don't enable this; if no key in config, we don't want to bother hupping
475     } else {
476       pndhup = pnd_locate_filename ( run_searchpath, PND_PNDHUP_FILENAME );
477 #endif
478     }
479
480   }
481
482   // debug
483   if ( run_searchpath ) pnd_log ( pndn_rem, "Locating pnd run in %s\n", run_searchpath );
484   if ( run_script ) pnd_log ( pndn_rem, "Locating pnd runscript as %s\n", run_script );
485   if ( pndrun ) pnd_log ( pndn_rem, "pndrun is %s\n", pndrun );
486   if ( pndhup ) {
487     pnd_log ( pndn_rem, "pndhup is %s\n", pndhup );
488   } else {
489     pnd_log ( pndn_rem, "No pndhup found (which is fine.)\n" );
490   }
491
492   /* cheap hack, maybe it'll help when pndnotifyd is coming up before the rest of the system and before
493    * the user is formally logged in
494    */
495   pnd_log ( pndn_rem, "Setting a default $HOME to non-root user\n" );
496
497   // first, try to see if known-username maps to a homedir; if so, just use that!
498   // otherwise, pick first non-root homedir and assume .. or we start blaring .desktops
499   // out to all users like idiots
500   unsigned char got_user_homedir = 0;
501
502   if ( g_username [ 0 ] ) {
503     struct stat homedir;
504     char path [ PATH_MAX ];
505
506     sprintf ( path, "/home/%s", g_username );
507
508     // does this made up path exist?
509     if ( stat ( path, &homedir ) == 0 ) {
510
511       // and its a dir?
512       if ( S_ISDIR(homedir.st_mode) ) {
513         pnd_log ( pndn_rem, "  User [%s] matches path [%s], going with '%s'\n", g_username, path, path );
514         setenv ( "HOME", path, 1 /* overwrite */ );
515         got_user_homedir = 1;
516       } // and its a dir?
517
518     } // guessing a homedirname..
519
520   } // got a username?
521
522   // if guessing a path was no good, just try finding one
523   if ( got_user_homedir == 0 ) {
524     DIR *dir;
525
526     if ( ( dir = opendir ( "/home" ) ) ) {
527       struct dirent *dirent;
528
529       while ( ( dirent = readdir ( dir ) ) ) {
530         pnd_log ( pndn_rem, "  Scanning user homedir '%s'\n", dirent -> d_name );
531
532         // file is a .desktop?
533         if ( dirent -> d_name [ 0 ] == '.' ) {
534           continue;
535         } else if ( strcmp ( dirent -> d_name, "root" ) == 0 ) {
536           continue;
537         }
538
539         // a non-root user is found
540         char buffer [ 200 ];
541         sprintf ( buffer, "/home/%s", dirent -> d_name );
542         pnd_log ( pndn_rem, "  Going with '%s'\n", buffer );
543         setenv ( "HOME", buffer, 1 /* overwrite */ );
544         break;
545
546       } // while iterating through dir listing
547
548       closedir ( dir );
549     } // opendir?
550
551   } // scope
552
553   /* handle globbing or variable substitution
554    */
555   desktop_dotdesktoppath = pnd_expand_tilde ( strdup ( desktop_dotdesktoppath ) );
556   desktop_iconpath = pnd_expand_tilde ( strdup ( desktop_iconpath ) );
557   mkdir ( desktop_dotdesktoppath, 0777 );
558   mkdir ( desktop_iconpath, 0777 );
559
560   if ( menu_dotdesktoppath ) {
561     menu_dotdesktoppath = pnd_expand_tilde ( strdup ( menu_dotdesktoppath ) );
562     mkdir ( menu_dotdesktoppath, 0777 );
563   }
564   if ( menu_iconpath ) {
565     menu_iconpath = pnd_expand_tilde ( strdup ( menu_iconpath ) );
566     mkdir ( menu_iconpath, 0777 );
567   }
568
569   // done
570   return;
571 }
572
573 void setup_notifications ( void ) {
574   searchpath = notifypath;
575
576   // if this is first time through, we can just set it up; for subsequent times
577   // through, we need to close existing fd and re-open it, since we're too lame
578   // to store the list of watches and 'rm' them
579 #if 1
580   if ( nh ) {
581     pnd_notify_shutdown ( nh );
582     nh = 0;
583   }
584 #endif
585
586   // set up a new set of notifies
587   if ( ! nh ) {
588     nh = pnd_notify_init();
589   }
590
591   if ( ! nh ) {
592     pnd_log ( pndn_rem, "INOTIFY failed to init.\n" );
593     exit ( -1 );
594   }
595
596 #if 0
597   pnd_log ( pndn_rem, "INOTIFY is up.\n" );
598 #endif
599
600   SEARCHPATH_PRE
601   {
602
603     pnd_log ( pndn_rem, "Watching path '%s' and its descendents.\n", buffer );
604     pnd_notify_watch_path ( nh, buffer, PND_NOTIFY_RECURSE );
605
606     //pnd_notify_watch_path ( nh, buffer, 0 /* no recurse */ );
607
608   }
609   SEARCHPATH_POST
610
611 #if 0
612   sleep ( 1 ); // wait for events to trigger?
613
614   // clear out any notifies we just created
615   while ( pnd_notify_rediscover_p ( nh ) ) {
616     usleep ( 100 ); // spin
617   } // while
618 #endif
619
620   return;
621 }
622
623 void sighup_handler ( int n ) {
624
625   pnd_log ( pndn_rem, "---[ SIGHUP received ]---\n" );
626
627   // reparse config files
628   consume_configuration();
629
630   // re set up the notifier watches
631   setup_notifications();
632
633   return;
634 }
635
636 void sigint_handler ( int n ) {
637
638   pnd_log ( pndn_rem, "---[ SIGINT received ]---\n" );
639
640   if ( dbh ) {
641     pnd_dbusnotify_shutdown ( dbh );
642   }
643
644   if ( nh ) {
645     pnd_notify_shutdown ( nh );
646   }
647
648   return;
649 }
650
651 // This very recently was inline code; just slight refactor to functionize it so that it can be
652 // reused in a couple of places. Simple code with simple design quickly became too large for
653 // its simple design; should revisit a lot of these little things..
654 void process_discoveries ( pnd_box_handle applist, char *emitdesktoppath, char *emiticonpath ) {
655   pnd_disco_t *d = pnd_box_get_head ( applist );
656
657   while ( d ) {
658
659     pnd_log ( pndn_rem, "Found app: %s\n", pnd_box_get_key ( d ) );
660
661     // check if icon already exists (from a previous extraction say); if so, we needn't
662     // do it again
663     char existingpath [ FILENAME_MAX ];
664     sprintf ( existingpath, "%s/%s.png", emiticonpath, d -> unique_id /*, d -> subapp_number */ );
665
666     struct stat dirs;
667     if ( stat ( existingpath, &dirs ) == 0 ) {
668       // icon seems to exist, so just crib the location into the .desktop
669
670       pnd_log ( pndn_rem, "  Found icon already existed, so reusing it! %s\n", existingpath );
671
672       if ( d -> icon ) {
673         free ( d -> icon );
674       }
675       d -> icon = strdup ( existingpath );
676
677     } else {
678       // icon seems unreadable or does not exist; lets try to create it..
679
680       pnd_log ( pndn_debug, "  Icon not already present, so trying to write it! %s\n", existingpath );
681
682       // attempt to create icon files; if successful, alter the disco struct to contain new
683       // path, otherwise leave it alone (since it could be a generic icon reference..)
684       if ( pnd_emit_icon ( emiticonpath, d ) ) {
685         // success; fix up icon path to new one..
686         if ( d -> icon ) {
687           free ( d -> icon );
688         }
689         d -> icon = strdup ( existingpath );
690       } else {
691         pnd_log ( pndn_debug, "  WARN: Couldn't write out icon %s\n", existingpath );
692       }
693
694     } // icon already exists?
695
696     // create the .desktop file
697     if ( pnd_emit_dotdesktop ( emitdesktoppath, pndrun, d ) ) {
698       // add a watch onto the newly created .desktop?
699 #if 0
700       char buffer [ FILENAME_MAX ];
701       sprintf ( buffer, "%s/%s", emitdesktoppath, d -> unique_id );
702       pnd_notify_watch_path ( nh, buffer, PND_NOTIFY_RECURSE );
703 #endif
704     } else {
705       pnd_log ( pndn_rem, "ERROR: Error creating .desktop file for app: %s\n", pnd_box_get_key ( d ) );
706     }
707
708     // does this object request any mkdir's?
709     if ( d -> mkdir_sp ) {
710
711       // it would appear it does! but we have to carefully validate these suckers
712       pnd_log ( pndn_rem, "  App %s requests mkdir: %s\n", d -> object_path, d -> mkdir_sp );
713
714       // for each mkdir requested path, do it...
715       char *searchpath = d -> mkdir_sp;
716
717       SEARCHCHUNK_PRE
718       {
719         /* "buffer" now holds each chunk of the searchpath, expanded */
720
721         // WARN: This whole concept could be flawed; what if they represent '..' in some other obscure way (unicode?)
722         // and we end up allowing mkdir's all over the place? The risk really is limited -- once the pnd is here,
723         // if the user _runs it_, it can go nuts, so creating a few dirs isn't all that dangerous...
724         //   HMRF :/
725         // Perhaps I should have a config setting for pndnotifyd to suppress this whole mkdir behaviour?
726
727         // if not containing ".." we allow it
728         if ( strstr ( buffer, ".." )  == NULL ) {
729
730           // determine mountpoint for the file
731           // - we could deduce this from the path (somewhat risky if we assume leading /media/mmcblk1p1 type notation .. could
732           //   be other distributions entirely
733           // - better to scan through mount-list and figure it out.. *sucks*
734           char mountpoint [ PATH_MAX ];
735           if ( pnd_determine_mountpoint ( d -> object_path, mountpoint, PATH_MAX - strlen ( buffer ) - 1 ) == 1 ) {
736
737             strcat ( mountpoint, "/" );
738             strcat ( mountpoint, buffer );
739
740             struct stat t;
741             if ( stat ( mountpoint, &t ) == 0 ) {
742               pnd_log ( pndn_rem, "    Skipping existing mkdir: %s\n", mountpoint );
743             } else {
744               pnd_log ( pndn_rem, "    Attempting create of non-existant path: %s\n", mountpoint );
745               mkdir ( mountpoint, 0777 );
746             }
747
748           } // if figured out the mountpoint
749
750         } // if valid path
751
752       }
753       SEARCHCHUNK_POST
754
755     } // mkdir request
756
757     // next!
758     d = pnd_box_get_next ( d );
759
760   } // while applist
761
762   return;
763 }
764
765 // returns true if any applications were found
766 unsigned char perform_discoveries ( char *appspath, char *overridespath,              // args to do discovery
767                                     char *emitdesktoppath, char *emiticonpath )       // args to do emitting
768 {
769   pnd_box_handle applist;
770
771   pnd_log ( pndn_rem, "perform discovery - apps: %s, overrides: %s\n", appspath, overridespath );
772   pnd_log ( pndn_rem, "                  - emit desktop: %s, icons: %s\n", emitdesktoppath, emiticonpath );
773
774   // attempt to auto-discover applications in the given path
775   applist = pnd_disco_search ( appspath, overridespath );
776
777   if ( applist ) {
778     process_discoveries ( applist, emitdesktoppath, emiticonpath );
779   }
780
781   // run a clean up, to remove any dotdesktop files that we didn't
782   // just now create (that seem to have been created by pndnotifyd
783   // previously.) This allows SD eject (or .pnd remove) to remove
784   // an app from the launcher
785   //   NOTE: Could opendir and iterate across all .desktop files,
786   // removing any that have Source= something else, and that the
787   // app name is not in the list found in applist box above. But
788   // a cheesy simple way right now is to just remove .desktop files
789   // that have a last mod time prior to the time we stored above.
790   {
791     DIR *dir;
792
793     if ( ( dir = opendir ( emitdesktoppath ) ) ) {
794       struct dirent *dirent;
795       struct stat dirs;
796       char buffer [ FILENAME_MAX ];
797
798       while ( ( dirent = readdir ( dir ) ) ) {
799
800         // file is a .desktop?
801         if ( strstr ( dirent -> d_name, ".desktop" ) == NULL ) {
802           continue;
803         }
804
805         // figure out full path
806         sprintf ( buffer, "%s/%s", emitdesktoppath, dirent -> d_name );
807
808         // file was previously created by libpnd; check Source= line
809         // logic: default to 'yes' (in case we can't open the file for some reason)
810         //        if we can open the file, default to no and look for the source flag we added; if
811         //          that matches then we know its libpnd created, otherwise assume not.
812         unsigned char source_libpnd = 1;
813         {
814           char line [ 256 ];
815           FILE *grep = fopen ( buffer, "r" );
816           if ( grep ) {
817             source_libpnd = 0;
818             while ( fgets ( line, 255, grep ) ) {
819               if ( strcasestr ( line, PND_DOTDESKTOP_SOURCE ) ) {
820                 source_libpnd = 2;
821               }
822             } // while
823             fclose ( grep );
824           }
825         }
826         if ( source_libpnd ) {
827 #if 1
828           pnd_log ( pndn_debug,
829                     "File '%s' appears to have been created by libpnd so candidate for delete: %u\n", buffer, source_libpnd );
830 #endif
831         } else {
832 #if 0
833           pnd_log ( pndn_debug, "File '%s' appears NOT to have been created by libpnd, so leave it alone\n", buffer );
834 #endif
835           continue; // skip deleting it
836         }
837
838         // file is 'new'?
839         if ( stat ( buffer, &dirs ) == 0 ) {
840           if ( dirs.st_mtime >= createtime ) {
841 #if 1
842             pnd_log ( pndn_debug, "File '%s' seems 'new', so leave it alone.\n", buffer );
843 #endif
844             continue; // skip deleting it
845           }
846         }
847
848         // by this point, the .desktop file must be 'old' and created by pndnotifyd
849         // previously, so can remove it
850         pnd_log ( pndn_rem, "File '%s' seems nolonger relevent; removing it.\n", dirent -> d_name );
851         unlink ( buffer );
852
853       } // while getting filenames from dir
854
855       closedir ( dir );
856     }
857
858   } // purge old .desktop files
859
860   //WARN: MEMORY LEAK HERE
861   pnd_log ( pndn_debug, "pndnotifyd - memory leak here - perform_discoveries()\n" );
862   if ( applist ) {
863     pnd_box_delete ( applist ); // does not free the disco_t contents!
864   }
865
866   return ( 1 );
867 }