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