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