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