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