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