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