Couple optimizations --
[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 // TODO: Catch HUP and reparse config
8 // TODO: Should perhaps direct all printf's through a vsprintf handler to avoid redundant "if ! g_daemon_mode"
9 // TODO: During daemon mode, should perhaps syslog or log errors
10 // TODO: Removing stale .desktop checks that .desktop was created by libpnd; see 'TBD' below
11
12 #include <stdio.h>     // for stdio
13 #include <unistd.h>    // for exit()
14 #include <stdlib.h>    // for exit()
15 #define __USE_GNU /* for strcasestr */
16 #include <string.h>
17 #include <time.h>      // for time()
18 #include <ctype.h>     // for isdigit()
19 #include <sys/types.h> // for umask
20 #include <sys/stat.h>  // for umask
21 #include <dirent.h>    // for opendir()
22
23 #include "pnd_conf.h"
24 #include "pnd_container.h"
25 #include "pnd_apps.h"
26 #include "pnd_notify.h"
27 #include "../lib/pnd_pathiter.h"
28 #include "pnd_discovery.h"
29 #include "pnd_locate.h"
30
31 static unsigned char g_daemon_mode = 0;
32
33 int main ( int argc, char *argv[] ) {
34   pnd_notify_handle nh;
35   // like discotest
36   char *configpath;
37   char *appspath;
38   char *overridespath;
39   // daemon stuff
40   char *searchpath = NULL;
41   char *dotdesktoppath = NULL;
42   // behaviour
43   unsigned char scanonlaunch = 1;
44   unsigned int interval_secs = 20;
45   // pnd runscript
46   char *run_searchpath;
47   char *run_script;
48   char *pndrun;
49   // misc
50   int i;
51
52   /* iterate across args
53    */
54   for ( i = 1; i < argc; i++ ) {
55
56     if ( argv [ i ][ 0 ] == '-' && argv [ i ][ 1 ] == 'd' ) {
57       //printf ( "Going daemon mode. Silent running.\n" );
58       g_daemon_mode = 1;
59     } else if ( isdigit ( argv [ i ][ 0 ] ) ) {
60       interval_secs = atoi ( argv [ i ] );
61     } else if ( argv [ i ][ 0 ] == '-' && argv [ i ][ 1 ] == 'n' ) {
62       scanonlaunch = 0;
63     } else {
64       printf ( "%s [-d] [##]\n", argv [ 0 ] );
65       printf ( "-d\tDaemon mode; detach from terminal, chdir to /tmp, suppress output. Optional.\n" );
66       printf ( "-n\tDo not scan on launch; default is to run a scan for apps when %s is invoked.\n", argv [ 0 ] );
67       printf ( "##\tA numeric value is interpreted as number of seconds between checking for filesystem changes. Default %u.\n",
68                interval_secs );
69       exit ( 0 );
70     }
71
72   }
73
74   if ( ! g_daemon_mode ) {
75     printf ( "Interval between checks is %u seconds\n", interval_secs );
76   }
77
78   // basic daemon set up
79   if ( g_daemon_mode ) {
80
81     // set a CWD somewhere else
82 #if 0
83     chdir ( "/tmp" );
84 #endif
85
86     // detach from terminal
87     if ( ( i = fork() ) < 0 ) {
88       printf ( "ERROR: Couldn't fork()\n" );
89       exit ( i );
90     }
91     if ( i ) {
92       exit ( 0 ); // exit parent
93     }
94     setsid();
95
96     // umask
97     umask ( 022 ); // emitted files can be rwxr-xr-x
98     
99   } // set up daemon
100
101   /* parse configs
102    */
103
104   // attempt to fetch a sensible default searchpath for configs
105   configpath = pnd_conf_query_searchpath();
106
107   // attempt to fetch the apps config to pick up a searchpath
108   pnd_conf_handle apph;
109
110   apph = pnd_conf_fetch_by_id ( pnd_conf_apps, configpath );
111
112   if ( apph ) {
113     appspath = pnd_conf_get_as_char ( apph, PND_APPS_KEY );
114
115     if ( ! appspath ) {
116       appspath = PND_APPS_SEARCHPATH;
117     }
118
119     overridespath = pnd_conf_get_as_char ( apph, PND_PXML_OVERRIDE_KEY );
120
121     if ( ! overridespath ) {
122       overridespath = PND_PXML_OVERRIDE_SEARCHPATH;
123     }
124
125   } else {
126     // couldn't find a useful app search path so use the default
127     appspath = PND_APPS_SEARCHPATH;
128     overridespath = PND_PXML_OVERRIDE_SEARCHPATH;
129   }
130
131   // attempt to figure out where to drop dotfiles
132   pnd_conf_handle desktoph;
133
134   desktoph = pnd_conf_fetch_by_id ( pnd_conf_desktop, configpath );
135
136   if ( desktoph ) {
137     dotdesktoppath = pnd_conf_get_as_char ( desktoph, PND_DOTDESKTOP_KEY );
138
139     if ( ! dotdesktoppath ) {
140       dotdesktoppath = PND_DOTDESKTOP_DEFAULT;
141     }
142
143   } else {
144     dotdesktoppath = PND_DOTDESKTOP_DEFAULT;
145   }
146
147   // try to locate a runscript
148
149   if ( apph ) {
150     run_searchpath = pnd_conf_get_as_char ( apph, PND_PNDRUN_SEARCHPATH_KEY );
151     run_script = pnd_conf_get_as_char ( apph, PND_PNDRUN_KEY );
152     pndrun = NULL;
153
154     if ( ! run_searchpath ) {
155       run_searchpath = PND_APPS_SEARCHPATH;
156       run_script = PND_PNDRUN_FILENAME;
157     }
158
159   } else {
160     run_searchpath = NULL;
161     run_script = NULL;
162     pndrun = PND_PNDRUN_DEFAULT;
163   }
164
165   if ( ! pndrun ) {
166     pndrun = pnd_locate_filename ( run_searchpath, run_script );
167
168     if ( ! pndrun ) {
169       pndrun = PND_PNDRUN_DEFAULT;
170     }
171
172   }
173
174   if ( ! g_daemon_mode ) {
175     if ( run_searchpath ) printf ( "Locating pnd run in %s\n", run_searchpath );
176     if ( run_script ) printf ( "Locating pnd runscript as %s\n", run_script );
177     if ( pndrun ) printf ( "Default pndrun is %s\n", pndrun );
178   }
179
180   /* startup
181    */
182
183   if ( ! g_daemon_mode ) {
184     printf ( "Apps searchpath is '%s'\n", appspath );
185     printf ( "PXML overrides searchpath is '%s'\n", overridespath );
186     printf ( ".desktop files emit to '%s'\n", dotdesktoppath );
187   }
188
189   /* set up notifies
190    */
191   searchpath = appspath;
192
193   nh = pnd_notify_init();
194
195   if ( ! nh ) {
196     if ( ! g_daemon_mode ) {
197       printf ( "INOTIFY failed to init.\n" );
198     }
199     exit ( -1 );
200   }
201
202   if ( ! g_daemon_mode ) {
203     printf ( "INOTIFY is up.\n" );
204   }
205
206   SEARCHPATH_PRE
207   {
208
209     if ( ! g_daemon_mode ) {
210       printf ( "Watching path '%s' and its descendents.\n", buffer );
211     }
212
213     pnd_notify_watch_path ( nh, buffer, PND_NOTIFY_RECURSE );
214
215   }
216   SEARCHPATH_POST
217
218   /* daemon main loop
219    */
220   while ( 1 ) {
221
222     // need to rediscover?
223     if ( scanonlaunch ||
224          pnd_notify_rediscover_p ( nh ) )
225     {
226       pnd_box_handle applist;
227       time_t createtime = time ( NULL ); // all 'new' .destops are created at or after this time; prev are old.
228
229       // if this was a forced scan, lets not do that next iteration
230       if ( scanonlaunch ) {
231         scanonlaunch = 0;
232       }
233
234       // by this point, the watched directories have notified us that something of relevent
235       // has occurred; we should be clever, but we're not, so just re-brute force the
236       // discovery and spit out .desktop files..
237       if ( ! g_daemon_mode ) {
238         printf ( "Changes within watched paths .. performing re-discover!\n" );
239         printf ( "Path to emit .desktop files to: '%s'\n", dotdesktoppath );
240       }
241
242       // run the discovery
243       applist = pnd_disco_search ( appspath, overridespath );
244
245       // list the found apps (if any)
246       if ( applist ) {
247         pnd_disco_t *d = pnd_box_get_head ( applist );
248
249         while ( d ) {
250
251           if ( ! g_daemon_mode ) {
252             printf ( "Found app: %s\n", pnd_box_get_key ( d ) );
253           }
254
255           // check if icon already exists (from a previous extraction say); if so, we needn't
256           // do it again
257           char existingpath [ FILENAME_MAX ];
258           sprintf ( existingpath, "%s/%s.png", dotdesktoppath, d -> unique_id );
259
260           struct stat dirs;
261           if ( stat ( existingpath, &dirs ) == 0 ) {
262             // icon seems to exist, so just crib the location into the .desktop
263
264             if ( ! g_daemon_mode ) {
265               printf ( "  Found icon already existed, so reusing it! %s\n", existingpath );
266             }
267
268             if ( d -> icon ) {
269               free ( d -> icon );
270             }
271             d -> icon = strdup ( existingpath );
272
273           } else {
274             // icon seems unreadable or does not exist; lets try to create it..
275
276             if ( ! g_daemon_mode ) {
277               printf ( "  Icon not already present, so trying to write it! %s\n", existingpath );
278             }
279
280             // attempt to create icon files; if successful, alter the disco struct to contain new
281             // path, otherwise leave it alone (since it could be a generic icon reference..)
282             if ( pnd_emit_icon ( dotdesktoppath, d ) ) {
283               // success; fix up icon path to new one..
284               if ( d -> icon ) {
285                 free ( d -> icon );
286               }
287               d -> icon = strdup ( existingpath );
288             }
289
290           } // icon already exists?
291
292           // create the .desktop file
293           if ( pnd_emit_dotdesktop ( dotdesktoppath, pndrun, d ) ) {
294             // add a watch onto the newly created .desktop?
295 #if 0
296             char buffer [ FILENAME_MAX ];
297             sprintf ( buffer, "%s/%s", dotdesktoppath, d -> unique_id );
298             pnd_notify_watch_path ( nh, buffer, PND_NOTIFY_RECURSE );
299 #endif
300           } else {
301             if ( ! g_daemon_mode ) {
302               printf ( "ERROR: Error creating .desktop file for app: %s\n", pnd_box_get_key ( d ) );
303             }
304           }
305
306           // next!
307           d = pnd_box_get_next ( d );
308
309         } // while applist
310
311       } else {
312
313         if ( ! g_daemon_mode ) {
314           printf ( "No applications found in search path\n" );
315         }
316
317       } // got apps?
318
319       // run a clean up, to remove any dotdesktop files that we didn't
320       // just now create (that seem to have been created by pndnotifyd
321       // previously.) This allows SD eject (or .pnd remove) to remove
322       // an app from the launcher
323       //   NOTE: Could opendir and iterate across all .desktop files,
324       // removing any that have Source= something else, and that the
325       // app name is not in the list found in applist box above. But
326       // a cheesy simple way right now is to just remove .desktop files
327       // that have a last mod time prior to the time we stored above.
328       {
329         DIR *dir;
330
331         if ( ( dir = opendir ( dotdesktoppath ) ) ) {
332           struct dirent *dirent;
333           struct stat dirs;
334           char buffer [ FILENAME_MAX ];
335
336           while ( ( dirent = readdir ( dir ) ) ) {
337
338             // file is a .desktop?
339             if ( strstr ( dirent -> d_name, ".desktop" ) == NULL ) {
340               continue;
341             }
342
343             // figure out full path
344             sprintf ( buffer, "%s/%s", dotdesktoppath, dirent -> d_name );
345
346             // file was previously created by libpnd; check Source= line
347             // logic: default to 'yes' (in case we can't open the file for some reason)
348             //        if we can open the file, default to no and look for the source flag we added; if
349             //          that matches then we know its libpnd created, otherwise assume not.
350             unsigned char source_libpnd = 1;
351             {
352               char line [ 256 ];
353               FILE *grep = fopen ( buffer, "r" );
354               if ( grep ) {
355                 source_libpnd = 0;
356                 while ( fgets ( line, 255, grep ) ) {
357                   if ( strcasestr ( line, PND_DOTDESKTOP_SOURCE ) ) {
358                     source_libpnd = 2;
359                   }
360                 } // while
361                 fclose ( grep );
362               }
363             }
364             if ( source_libpnd ) {
365               if ( ! g_daemon_mode ) {
366                 printf ( "File '%s' appears to have been created by libpnd so candidate for delete: %u\n", buffer, source_libpnd );
367               }
368             } else {
369               if ( ! g_daemon_mode ) {
370                 printf ( "File '%s' appears NOT to have been created by libpnd, so leave it alone\n", buffer );
371               }
372               continue; // skip deleting it
373             }
374
375             // file is 'new'?
376             if ( stat ( buffer, &dirs ) == 0 ) {
377               if ( dirs.st_mtime >= createtime ) {
378                 if ( ! g_daemon_mode ) {
379                   printf ( "File '%s' seems 'new', so leave it alone.\n", buffer );
380                 }
381                 continue; // skip deleting it
382               }
383             }
384
385             // by this point, the .desktop file must be 'old' and created by pndnotifyd
386             // previously, so can remove it
387             if ( ! g_daemon_mode ) {
388               printf ( "File '%s' seems to not belong; removing it.\n", dirent -> d_name );
389             }
390             unlink ( buffer );
391
392           } // while getting filenames from dir
393
394           closedir ( dir );
395         }
396
397       } // purge old .desktop files
398
399     } // need to rediscover?
400
401     // lets not eat up all the CPU
402     // should use an alarm or select() or something
403     sleep ( interval_secs );
404
405   } // while
406
407   /* shutdown
408    */
409   pnd_notify_shutdown ( nh );
410
411   return ( 0 );
412 }