6335d931e8cb4dced2ffffc8cacd1a75052d0f20
[xscreensaver] / driver / xscreensaver-getimage-file
1 #!/usr/bin/perl -w
2 # Copyright © 2001-2018 Jamie Zawinski <jwz@jwz.org>.
3 #
4 # Permission to use, copy, modify, distribute, and sell this software and its
5 # documentation for any purpose is hereby granted without fee, provided that
6 # the above copyright notice appear in all copies and that both that
7 # copyright notice and this permission notice appear in supporting
8 # documentation.  No representations are made about the suitability of this
9 # software for any purpose.  It is provided "as is" without express or 
10 # implied warranty.
11 #
12 # This program chooses a random file from under the given directory, and
13 # prints its name.  The file will be an image file whose dimensions are
14 # larger than a certain minimum size.
15 #
16 # If the directory is a URL, it is assumed to be an RSS or Atom feed.
17 # The images from that feed will be downloaded, cached, and selected from
18 # at random.  The feed will be re-polled periodically, as needed.
19 #
20 # The various xscreensaver hacks that manipulate images ("jigsaw", etc.) get
21 # the image to manipulate by running the "xscreensaver-getimage" program.
22 #
23 # Under X11, the "xscreensaver-getimage" program invokes this script,
24 # depending on the value of the "chooseRandomImages" and "imageDirectory"
25 # settings in the ~/.xscreensaver file (or .../app-defaults/XScreenSaver).
26 # The screen savers invoke "xscreensaver-getimage" via utils/grabclient.c,
27 # which then invokes this script.
28 #
29 # Under Cocoa, this script lives inside the .saver bundle, and is invoked
30 # directly from utils/grabclient.c.
31 #
32 # Created: 12-Apr-01.
33
34 require 5;
35 #use diagnostics;       # Fails on some MacOS 10.5 systems
36 use strict;
37
38 use POSIX;
39 use Fcntl;
40
41 use Fcntl ':flock'; # import LOCK_* constants
42
43 use POSIX ':fcntl_h';                           # S_ISDIR was here in Perl 5.6
44 import Fcntl ':mode' unless defined &S_ISUID;   # but it is here in Perl 5.8
45         # but in Perl 5.10, both of these load, and cause errors!
46         # So we have to check for S_ISUID instead of S_ISDIR?  WTF?
47
48 use Digest::MD5 qw(md5_base64);
49
50 # Some Linux systems don't install LWP by default!
51 # Only error out if we're actually loading a URL instead of local data.
52 BEGIN { eval 'use LWP::Simple;' }
53
54
55 my $progname = $0; $progname =~ s@.*/@@g;
56 my ($version) = ('$Revision: 1.46 $' =~ m/\s(\d[.\d]+)\s/s);
57
58 my $verbose = 0;
59
60 # Whether to use MacOS X's Spotlight to generate the list of files.
61 # When set to -1, uses Spotlight if "mdfind" exists.
62 #
63 # (In my experience, this isn't actually any faster, and might not find
64 # everything if your Spotlight index is out of date, which happens often.)
65 #
66 my $use_spotlight_p = 0;
67
68 # Whether to cache the results of the last run.
69 #
70 my $cache_p = 1;
71
72 # Regenerate the cache if it is older than this many seconds.
73 #
74 my $cache_max_age = 60 * 60 * 3;   # 3 hours
75
76 # Re-poll RSS/Atom feeds when local copy is older than this many seconds.
77 #
78 my $feed_max_age = $cache_max_age;
79
80
81 # This matches files that we are allowed to use as images (case-insensitive.)
82 # Anything not matching this is ignored.  This is so you can point your
83 # imageDirectory at directory trees that have things other than images in
84 # them, but it assumes that you gave your images sensible file extensions.
85 #
86 my @good_extensions = ('jpg', 'jpeg', 'pjpeg', 'pjpg', 'png', 'gif',
87                        'tif', 'tiff', 'xbm', 'xpm');
88 my $good_file_re = '\.(' . join("|", @good_extensions) . ')$';
89
90 # This matches file extensions that might occur in an image directory,
91 # and that are never used in the name of a subdirectory.  This is an
92 # optimization that prevents us from having to stat() those files to
93 # tell whether they are directories or not.  (It speeds things up a
94 # lot.  Don't give your directories stupid names.)
95 #
96 my @nondir_extensions = ('ai', 'bmp', 'bz2', 'cr2', 'crw', 'db',
97    'dmg', 'eps', 'gz', 'hqx', 'htm', 'html', 'icns', 'ilbm', 'mov',
98    'nef', 'pbm', 'pdf', 'php', 'pl', 'ppm', 'ps', 'psd', 'sea', 'sh',
99    'shtml', 'tar', 'tgz', 'thb', 'txt', 'xcf', 'xmp', 'Z', 'zip' );
100 my $nondir_re = '\.(' . join("|", @nondir_extensions) . ')$';
101
102
103 # JPEG, GIF, and PNG files that are are smaller than this are rejected:
104 # this is so that you can use an image directory that contains both big
105 # images and thumbnails, and have it only select the big versions.
106 #
107 my $min_image_width  = 500;
108 my $min_image_height = 500;
109
110 my @all_files = ();         # list of "good" files we've collected
111 my %seen_inodes;            # for breaking recursive symlink loops
112
113 # For diagnostic messages:
114 #
115 my $dir_count = 1;          # number of directories seen
116 my $stat_count = 0;         # number of files/dirs stat'ed
117 my $skip_count_unstat = 0;  # number of files skipped without stat'ing
118 my $skip_count_stat = 0;    # number of files skipped after stat
119
120 sub find_all_files($);
121 sub find_all_files($) {
122   my ($dir) = @_;
123
124   print STDERR "$progname:  + reading dir $dir/...\n" if ($verbose > 1);
125
126   my $dd;
127   if (! opendir ($dd, $dir)) {
128     print STDERR "$progname: couldn't open $dir: $!\n" if ($verbose);
129     return;
130   }
131   my @files = readdir ($dd);
132   closedir ($dd);
133
134   my @dirs = ();
135
136   foreach my $file (@files) {
137     next if ($file =~ m/^\./);      # silently ignore dot files/dirs
138
139     if ($file =~ m/[~%\#]$/) {      # ignore backup files (and dirs...)
140       $skip_count_unstat++;
141       print STDERR "$progname:  - skip file  $file\n" if ($verbose > 1);
142     }
143
144     $file = "$dir/$file";
145
146     if ($file =~ m/$good_file_re/io) {
147       #
148       # Assume that files ending in .jpg exist and are not directories.
149       #
150       push @all_files, $file;
151       print STDERR "$progname:  - found file $file\n" if ($verbose > 1);
152
153     } elsif ($file =~ m/$nondir_re/io) {
154       #
155       # Assume that files ending in .html are not directories.
156       #
157       $skip_count_unstat++;
158       print STDERR "$progname: -- skip file  $file\n" if ($verbose > 1);
159
160     } else {
161       #
162       # Now we need to stat the file to see if it's a subdirectory.
163       #
164       # Note: we could use the trick of checking "nlinks" on the parent
165       # directory to see if this directory contains any subdirectories,
166       # but that would exclude any symlinks to directories.
167       #
168       my @st = stat($file);
169       my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
170           $atime,$mtime,$ctime,$blksize,$blocks) = @st;
171
172       $stat_count++;
173
174       if ($#st == -1) {
175         if ($verbose) {
176           my $ll = readlink $file;
177           if (defined ($ll)) {
178             print STDERR "$progname: + dangling symlink: $file -> $ll\n";
179           } else {
180             print STDERR "$progname: + unreadable: $file\n";
181           }
182         }
183         next;
184       }
185
186       next if ($seen_inodes{"$dev:$ino"}); # break symlink loops
187       $seen_inodes{"$dev:$ino"} = 1;
188
189       if (S_ISDIR($mode)) {
190         push @dirs, $file;
191         $dir_count++;
192         print STDERR "$progname:  + found dir  $file\n" if ($verbose > 1);
193
194       } else {
195         $skip_count_stat++;
196         print STDERR "$progname:  + skip file  $file\n" if ($verbose > 1);
197       }
198     }
199   }
200
201   foreach (@dirs) {
202     find_all_files ($_);
203   }
204 }
205
206
207 sub spotlight_all_files($) {
208   my ($dir) = @_;
209
210   my @terms = ();
211   # "public.image" matches all (indexed) images, including Photoshop, etc.
212 #  push @terms, "kMDItemContentTypeTree == 'public.image'";
213   foreach (@good_extensions) {
214
215     # kMDItemFSName hits the file system every time: much worse than "find".
216 #    push @terms, "kMDItemFSName == '*.$_'";
217
218     # kMDItemDisplayName matches against the name in the Spotlight index,
219     # but won't find files that (for whatever reason) didn't get indexed.
220     push @terms, "kMDItemDisplayName == '*.$_'";
221   }
222
223   $dir =~ s@([^-_/a-z\d.,])@\\$1@gsi;  # quote for sh
224   my $cmd = "mdfind -onlyin $dir \"" . join (' || ', @terms) . "\"";
225
226   print STDERR "$progname: executing: $cmd\n" if ($verbose > 1);
227   @all_files = split (/[\r\n]+/, `$cmd`);
228 }
229
230
231 # If we're using cacheing, read the cache file and return its contents,
232 # if any.  This also holds an exclusive lock on the cache file, which 
233 # has the additional benefit that if two copies of this program are
234 # running at once, one will wait for the other, instead of both of
235 # them spanking the same file system at the same time.
236 #
237 my $cache_fd = undef;
238 my $cache_file_name = undef;
239 my $read_cache_p = 0;
240
241 sub read_cache($) {
242   my ($dir) = @_;
243
244   return () unless ($cache_p);
245
246   my $dd = "$ENV{HOME}/Library/Caches";    # MacOS location
247   if (-d $dd) {
248     $cache_file_name = "$dd/org.jwz.xscreensaver.getimage.cache";
249   } elsif (-d "$ENV{HOME}/.cache") {       # Gnome "FreeDesktop XDG" location
250     $dd = "$ENV{HOME}/.cache/xscreensaver";
251     if (! -d $dd) { mkdir ($dd) || error ("mkdir $dd: $!"); }
252     $cache_file_name = "$dd/xscreensaver-getimage.cache"
253   } elsif (-d "$ENV{HOME}/tmp") {          # If ~/tmp/ exists, use it.
254     $cache_file_name = "$ENV{HOME}/tmp/.xscreensaver-getimage.cache";
255   } else {
256     $cache_file_name = "$ENV{HOME}/.xscreensaver-getimage.cache";
257   }
258
259   print STDERR "$progname: awaiting lock: $cache_file_name\n"
260     if ($verbose > 1);
261
262   my $file = $cache_file_name;
263   open ($cache_fd, '+>>', $file) || error ("unable to write $file: $!");
264   flock ($cache_fd, LOCK_EX)     || error ("unable to lock $file: $!");
265   seek ($cache_fd, 0, 0)         || error ("unable to rewind $file: $!");
266
267   my $mtime = (stat($cache_fd))[9];
268
269   if ($mtime + $cache_max_age < time) {
270     print STDERR "$progname: cache is too old\n" if ($verbose);
271     return ();
272   }
273
274   my $odir = <$cache_fd>;
275   $odir =~ s/[\r\n]+$//s if defined ($odir);
276   if (!defined ($odir) || ($dir ne $odir)) {
277     print STDERR "$progname: cache is for $odir, not $dir\n"
278       if ($verbose && $odir);
279     return ();
280   }
281
282   my @files = ();
283   while (<$cache_fd>) { 
284     s/[\r\n]+$//s;
285     push @files, "$odir/$_";
286   }
287
288   print STDERR "$progname: " . ($#files+1) . " files in cache\n"
289     if ($verbose);
290
291   $read_cache_p = 1;
292   return @files;
293 }
294
295
296 sub write_cache($) {
297   my ($dir) = @_;
298
299   return unless ($cache_p);
300
301   # If we read the cache, just close it without rewriting it.
302   # If we didn't read it, then write it now.
303
304   if (! $read_cache_p) {
305
306     truncate ($cache_fd, 0) ||
307       error ("unable to truncate $cache_file_name: $!");
308     seek ($cache_fd, 0, 0) ||
309       error ("unable to rewind $cache_file_name: $!");
310
311     if ($#all_files >= 0) {
312       print $cache_fd "$dir\n";
313       foreach (@all_files) {
314         my $f = $_; # stupid Perl. do this to avoid modifying @all_files!
315         $f =~ s@^\Q$dir/@@so || die;  # remove $dir from front
316         print $cache_fd "$f\n";
317       }
318     }
319
320     print STDERR "$progname: cached " . ($#all_files+1) . " files\n"
321       if ($verbose);
322   }
323
324   flock ($cache_fd, LOCK_UN) ||
325     error ("unable to unlock $cache_file_name: $!");
326   close ($cache_fd);
327   $cache_fd = undef;
328 }
329
330
331 sub html_unquote($) {
332   my ($h) = @_;
333
334   # This only needs to handle entities that occur in RSS, not full HTML.
335   my %ent = ( 'amp' => '&', 'lt' => '<', 'gt' => '>', 
336               'quot' => '"', 'apos' => "'" );
337   $h =~ s/(&(\#)?([[:alpha:]\d]+);?)/
338     {
339      my ($o, $c) = ($1, $3);
340      if (! defined($2)) {
341        $c = $ent{$c};                   # for &lt;
342      } else {
343        if ($c =~ m@^x([\dA-F]+)$@si) {  # for &#x41;
344          $c = chr(hex($1));
345        } elsif ($c =~ m@^\d+$@si) {     # for &#65;
346          $c = chr($c);
347        } else {
348          $c = undef;
349        }
350      }
351      ($c || $o);
352     }
353    /gexi;
354   return $h;
355 }
356
357
358
359 # Figure out what the proxy server should be, either from environment
360 # variables or by parsing the output of the (MacOS) program "scutil",
361 # which tells us what the system-wide proxy settings are.
362 #
363 sub set_proxy($) {
364   my ($ua) = @_;
365
366   my $proxy_data = `scutil --proxy 2>/dev/null`;
367   foreach my $proto ('http', 'https') {
368     my ($server) = ($proxy_data =~ m/\b${proto}Proxy\s*:\s*([^\s]+)/si);
369     my ($port)   = ($proxy_data =~ m/\b${proto}Port\s*:\s*([^\s]+)/si);
370     my ($enable) = ($proxy_data =~ m/\b${proto}Enable\s*:\s*([^\s]+)/si);
371
372     if ($server && $enable) {
373       # Note: this ignores the "ExceptionsList".
374       my $proto2 = 'http';
375       $ENV{"${proto}_proxy"} = ("${proto2}://" . $server .
376                                 ($port ? ":$port" : "") . "/");
377       print STDERR "$progname: MacOS $proto proxy: " .
378                    $ENV{"${proto}_proxy"} . "\n"
379         if ($verbose > 2);
380     }
381   }
382
383   $ua->env_proxy();
384 }
385
386
387 sub init_lwp() {
388   if (! defined ($LWP::Simple::ua)) {
389     error ("\n\n\tPerl is broken. Do this to repair it:\n" .
390            "\n\tsudo cpan LWP::Simple LWP::Protocol::https Mozilla::CA\n");
391   }
392   set_proxy ($LWP::Simple::ua);
393 }
394
395
396 sub sanity_check_lwp() {
397   my $url1 = 'https://www.mozilla.org/';
398   my $url2 =  'http://www.mozilla.org/';
399   my $body = (LWP::Simple::get($url1) || '');
400   if (length($body) < 10240) {
401     my $err = "";
402     $body = (LWP::Simple::get($url2) || '');
403     if (length($body) < 10240) {
404       $err = "Perl is broken: neither HTTP nor HTTPS URLs work.";
405     } else {
406       $err = "Perl is broken: HTTP URLs work but HTTPS URLs don't.";
407     }
408     $err .= "\nMaybe try: sudo cpan -f Mozilla::CA LWP::Protocol::https";
409     $err =~ s/^/\t/gm;
410     error ("\n\n$err\n");
411   }
412 }
413
414
415 # If the URL does not already end with an extension appropriate for the
416 # content-type, add it after a "#" search.
417 #
418 # This is for when we know the content type of the URL, but the URL is
419 # some crazy thing without an extension. The files on disk need to have
420 # proper extensions.
421 #
422 sub force_extension($$) {
423   my ($url, $ct) = @_;
424   return $url unless (defined($url) && defined($ct));
425   my ($ext) = ($ct =~ m@^image/([-a-z\d]+)@si);
426   return $url unless $ext;
427   $ext = lc($ext);
428   $ext = 'jpg' if ($ext eq 'jpeg');
429   return $url if ($url =~ m/\.$ext$/si);
430   return "$url#.$ext";
431 }
432
433
434 # Returns a list of the image enclosures in the RSS or Atom feed.
435 # Elements of the list are references, [ "url", "guid" ].
436 #
437 sub parse_feed($);
438 sub parse_feed($) {
439   my ($url) = @_;
440
441   init_lwp();
442   $LWP::Simple::ua->agent ("$progname/$version");
443   $LWP::Simple::ua->timeout (10);  # bail sooner than the default of 3 minutes
444
445
446   # Half the time, random Linux systems don't have Mozilla::CA installed,
447   # which results in "Can't verify SSL peers without knowning which
448   # Certificate Authorities to trust".
449   #
450   # In xscreensaver-text we just disabled certificate checks. However,
451   # malicious images really do exist, so for xscreensaver-getimage-file,
452   # let's actually require that SSL be installed properly.
453
454
455   my $body = (LWP::Simple::get($url) || '');
456
457   if ($body !~ m@^\s*<(\?xml|rss)\b@si) {
458     # Not an RSS/Atom feed.  Try RSS autodiscovery.
459
460     # (Great news, everybody: Flickr no longer provides RSS for "Sets",
461     # only for "Photostreams", and only the first 20 images of those.
462     # Thanks, assholes.)
463
464     if ($body =~ m/^\s*$/s) {
465       sanity_check_lwp();
466       error ("null response: $url");
467     }
468
469     error ("not an RSS or Atom feed, or HTML: $url")
470       unless ($body =~ m@<(HEAD|BODY|A|IMG)\b@si);
471
472     # Find the first <link> with RSS or Atom in it, and use that instead.
473
474     $body =~ s@<LINK\s+([^<>]*)>@{
475       my $p = $1;
476       if ($p =~ m! \b REL  \s* = \s* ['"]? alternate \b!six &&
477           $p =~ m! \b TYPE \s* = \s* ['"]? application/(atom|rss) !six &&
478           $p =~ m! \b HREF \s* = \s* ['"]  ( [^<>'"]+ ) !six
479          ) {
480         my $u2 = html_unquote ($1);
481         if ($u2 =~ m!^/!s) {
482           my ($h) = ($url =~ m!^([a-z]+://[^/]+)!si);
483           $u2 = "$h$u2";
484         }
485         print STDERR "$progname: found feed: $u2\n"
486           if ($verbose);
487         return parse_feed ($u2);
488       }
489       '';
490     }@gsexi;
491
492     error ("no RSS or Atom feed for HTML page: $url");
493   }
494
495
496   $body =~ s@(<ENTRY|<ITEM)@\001$1@gsi;
497   my @items = split(/\001/, $body);
498   shift @items;
499
500   my @imgs = ();
501   my %ids;
502
503   foreach my $item (@items) {
504     my $iurl = undef;
505     my $id = undef;
506
507     # First look for <link rel="enclosure" href="...">
508     #
509     if (! $iurl) {
510       foreach my $link ($item =~ m@<LINK[^<>]*>@gsi) {
511         last if $iurl;
512         my ($href) = ($link =~ m/\bHREF\s*=\s*[\"\']([^<>\'\"]+)/si);
513         my ($type) = ($link =~ m/\bTYPE\s*=\s*[\"\']?([^<>\'\"]+)/si);
514         my ($rel)  = ($link =~ m/\bREL\s*=\s*[\"\']?([^<>\'\"]+)/si);
515         $href = undef unless (lc($rel || '') eq 'enclosure');
516         $href = undef if ($type && $type !~ m@^image/@si);  # omit videos
517         $iurl = html_unquote($href) if $href;
518         $iurl = force_extension ($iurl, $type);
519       }
520     }
521
522     # Then look for <media:content url="...">
523     #
524     if (! $iurl) {
525       foreach my $link ($item =~ m@<MEDIA:CONTENT[^<>]*>@gsi) {
526         last if $iurl;
527         my ($href) = ($link =~ m/\bURL\s*=\s*[\"\']([^<>\'\"]+)/si);
528         my ($type) = ($link =~ m/\bTYPE\s*=\s*[\"\']?([^<>\'\"]+)/si);
529         my ($med)  = ($link =~ m/\bMEDIUM\s*=\s*[\"\']?([^<>\'\"]+)/si);
530         $type = 'image/jpeg' if (!$type && lc($med || '') eq 'image');
531         $href = undef if ($type && $type !~ m@^image/@si);  # omit videos
532         $iurl = html_unquote($href) if $href;
533         $iurl = force_extension ($iurl, $type);
534       }
535     }
536
537     # Then look for <enclosure url="..."/> 
538     #
539     if (! $iurl) {
540       foreach my $link ($item =~ m@<ENCLOSURE[^<>]*>@gsi) {
541         last if $iurl;
542         my ($href) = ($link =~ m/\bURL\s*=\s*[\"\']([^<>\'\"]+)/si);
543         my ($type) = ($link =~ m/\bTYPE\s*=\s*[\"\']?([^<>\'\"]+)/si);
544         $href = undef if ($type && $type !~ m@^image/@si);  # omit videos
545         $iurl = html_unquote($href) if ($href);
546         $iurl = force_extension ($iurl, $type);
547       }
548     }
549
550     # Ok, maybe there's an image in the <url> field?
551     #
552     if (! $iurl) {
553       foreach my $link ($item =~ m@<URL\b[^<>]*>([^<>]*)@gsi) {
554         last if $iurl;
555         my $u2 = $1;
556         $iurl = html_unquote($u2) if ($u2 =~ m/$good_file_re/io);
557         if (! $iurl) {
558           my $u3 = $u2;
559           $u3 =~ s/#.*$//gs;
560           $u3 =~ s/[?&].*$//gs;
561           $iurl = html_unquote($u2) if ($u3 =~ m/$good_file_re/io);
562         }
563       }
564     }
565
566     # Then look for <description>... with an <img src="..."> inside.
567     #
568     if (! $iurl) {
569       foreach my $link ($item =~ m@<description[^<>]*>(.*?)</description>@gsi) {
570         last if $iurl;
571         my $desc = html_unquote($1);
572         my ($href) = ($desc =~ m@<IMG[^<>]*\bSRC=[\"\']?([^\"\'<>]+)@si);
573         $iurl = html_unquote($href) if ($href);
574         # If IMG SRC has a bogus extension, pretend it's a JPEG.
575         $iurl = force_extension ($iurl, 'image/jpeg')
576           if ($iurl && $iurl !~ m/$good_file_re/io);
577       }
578     }
579
580     # Could also do <content:encoded>, but the above probably covers all
581     # of the real-world possibilities.
582
583
584     # Find a unique ID for this image, to defeat image farms.
585     # First look for <id>...</id>
586     ($id) = ($item =~ m!<ID\b[^<>]*>\s*([^<>]+?)\s*</ID>!si) unless $id;
587
588     # Then look for <guid isPermaLink=...> ... </guid>
589     ($id) = ($item =~ m!<GUID\b[^<>]*>\s*([^<>]+?)\s*</GUID>!si) unless $id;
590
591     # Then look for <link> ... </link>
592     ($id) = ($item =~ m!<LINK\b[^<>]*>\s*([^<>]+?)\s*</LINK>!si) unless $id;
593
594     # If we only have a GUID or LINK, but it's an image, use that.
595     $iurl = $id if (!$iurl && $id && $id =~ m/$good_file_re/io);
596
597     if ($iurl) {
598       $id = $iurl unless $id;
599       my $o = $ids{$id};
600       if (! $o) {
601         $ids{$id} = $iurl;
602         my @P = ($iurl, $id);
603         push @imgs, \@P;
604       } elsif ($iurl ne $o) {
605         print STDERR "$progname: WARNING: dup ID \"$id\"" .
606                      " for \"$o\" and \"$iurl\"\n";
607       }
608     }
609   }
610
611   return @imgs;
612 }
613
614
615 # Like md5_base64 but uses filename-safe characters.
616 #
617 sub md5_file($) {
618   my ($s) = @_;
619   $s = md5_base64($s);
620   $s =~ s@[/]@_@gs;
621   $s =~ s@[+]@-@gs;
622   return $s;
623 }
624
625
626 # expands the first URL relative to the second.
627 #
628 sub expand_url($$) {
629   my ($url, $base) = @_;
630
631   $url =~ s/^\s+//gs;  # lose whitespace at front and back
632   $url =~ s/\s+$//gs;
633
634   if (! ($url =~ m/^[a-z]+:/)) {
635
636     $base =~ s@(\#.*)$@@;       # strip anchors
637     $base =~ s@(\?.*)$@@;       # strip arguments
638     $base =~ s@/[^/]*$@/@;      # take off trailing file component
639
640     my $tail = '';
641     if ($url =~ s@(\#.*)$@@) { $tail = $1; }         # save anchors
642     if ($url =~ s@(\?.*)$@@) { $tail = "$1$tail"; }  # save arguments
643
644     my $base2 = $base;
645
646     $base2 =~ s@^([a-z]+:/+[^/]+)/.*@$1@        # if url is an absolute path
647       if ($url =~ m@^/@);
648
649     my $ourl = $url;
650
651     $url = $base2 . $url;
652     $url =~ s@/\./@/@g;                         # expand "."
653     1 while ($url =~ s@/[^/]+/\.\./@/@s);       # expand ".."
654
655     $url .= $tail;                              # put anchors/args back
656
657     print STDERR "$progname: relative URL: $ourl --> $url\n"
658       if ($verbose > 1);
659
660   } else {
661     print STDERR "$progname: absolute URL: $url\n"
662       if ($verbose > 2);
663   }
664
665   return $url;
666 }
667
668
669 # Given the URL of an image, download it into the given directory
670 # and return the file name.
671 #
672 sub download_image($$$) {
673   my ($url, $uid, $dir) = @_;
674
675   my $url2 = $url;
676   $url2 =~ s/\#.*$//s;          # Omit search terms after file extension
677   $url2 =~ s/\?.*$//s;
678   my ($ext) = ($url  =~ m@\.([a-z\d]+)$@si);
679      ($ext) = ($url2 =~ m@\.([a-z\d]+)$@si) unless $ext;
680
681   # If the feed hasn't put a sane extension on their URLs, nothing's going
682   # to work. This code assumes that file names have extensions, even the
683   # ones in the cache directory.
684   #
685   if (! $ext) {
686     print STDERR "$progname: skipping extensionless URL: $url\n"
687       if ($verbose > 1);
688     return undef;
689   }
690
691   # Don't bother downloading files that we will reject anyway.
692   #
693   if (! ($url  =~ m/$good_file_re/io ||
694          $url2 =~ m/$good_file_re/io)) {
695     print STDERR "$progname: skipping non-image URL: $url\n"
696       if ($verbose > 1);
697     return undef;
698   }
699
700   my $file = md5_file ($uid);
701   $file .= '.' . lc($ext) if $ext;
702
703   # Don't bother doing If-Modified-Since to see if the URL has changed.
704   # If we have already downloaded it, assume it's good.
705   if (-f "$dir/$file") {
706     print STDERR "$progname: exists: $dir/$file for $uid / $url\n" 
707       if ($verbose > 1);
708     return $file;
709   }
710
711   # Special-case kludge for Flickr:
712   # Their RSS feeds sometimes include only the small versions of the images.
713   # So if the URL ends in one of the "small-size" letters, change it to "b".
714   #
715   #     _o  orig,  1600 +
716   #     _k  large, 2048 max
717   #     _h  large, 1600 max
718   #     _b  large, 1024 max
719   #     _c  medium, 800 max
720   #     _z  medium, 640 max
721   #     ""  medium, 500 max
722   #     _n  small,  320 max
723   #     _m  small,  240 max
724   #     _t  thumb,  100 max
725   #     _q  square, 150x150
726   #     _s  square,  75x75
727   #
728   # Note: if we wanted to get the _k or _o version instead of the _b or _h
729   # version, we'd need to crack the DRM -- which is easy: see crack_secret
730   # in "https://www.jwz.org/hacks/galdown".
731   #
732   $url =~ s@_[sqtmnzc](\.[a-z]+)$@_b$1@si
733     if ($url =~ m@^https?://[^/?#&]*?flickr\.com/@si);
734
735   print STDERR "$progname: downloading: $dir/$file for $uid / $url\n" 
736     if ($verbose > 1);
737   init_lwp();
738   $LWP::Simple::ua->agent ("$progname/$version");
739
740   $url =~ s/\#.*$//s;           # Omit search terms
741   my $status = LWP::Simple::mirror ($url, "$dir/$file");
742   if (!LWP::Simple::is_success ($status)) {
743     print STDERR "$progname: error $status: $url\n";   # keep going
744   }
745
746   return $file;
747 }
748
749
750 sub mirror_feed($) {
751   my ($url) = @_;
752
753   if ($url !~ m/^https?:/si) {   # not a URL: local directory.
754     return (undef, $url);
755   }
756
757   my $dir = "$ENV{HOME}/Library/Caches";    # MacOS location
758   if (-d $dir) {
759     $dir = "$dir/org.jwz.xscreensaver.feeds";
760   } elsif (-d "$ENV{HOME}/.cache") {       # Gnome "FreeDesktop XDG" location
761     $dir = "$ENV{HOME}/.cache/xscreensaver";
762     if (! -d $dir) { mkdir ($dir) || error ("mkdir $dir: $!"); }
763     $dir .= "/feeds";
764     if (! -d $dir) { mkdir ($dir) || error ("mkdir $dir: $!"); }
765   } elsif (-d "$ENV{HOME}/tmp") {          # If ~/tmp/ exists, use it.
766     $dir = "$ENV{HOME}/tmp/.xscreensaver-feeds";
767   } else {
768     $dir = "$ENV{HOME}/.xscreensaver-feeds";
769   }
770
771   if (! -d $dir) {
772     mkdir ($dir) || error ("mkdir $dir: $!");
773     print STDERR "$progname: mkdir $dir/\n" if ($verbose);
774   }
775
776   # MD5 for directory name to use for cache of a feed URL.
777   $dir .= '/' . md5_file ($url);
778
779   if (! -d $dir) {
780     mkdir ($dir) || error ("mkdir $dir: $!");
781     print STDERR "$progname: mkdir $dir/ for $url\n" if ($verbose);
782   }
783
784   # At this point, we have the directory corresponding to this URL.
785   # Now check to see if the files in it are up to date, and download
786   # them if not.
787
788   my $stamp = '.timestamp';
789   my $lock = "$dir/$stamp";
790
791   print STDERR "$progname: awaiting lock: $lock\n"
792     if ($verbose > 1);
793
794   my $mtime = ((stat($lock))[9]) || 0;
795
796   my $lock_fd;
797   open ($lock_fd, '+>>', $lock) || error ("unable to write $lock: $!");
798   flock ($lock_fd, LOCK_EX)     || error ("unable to lock $lock: $!");
799   seek ($lock_fd, 0, 0)         || error ("unable to rewind $lock: $!");
800
801   my $poll_p = ($mtime + $feed_max_age < time);
802
803   # --no-cache cmd line arg means poll again right now.
804   $poll_p = 1 unless ($cache_p);
805
806   # Even if the cache is young, make sure there is at least one file,
807   # and re-check if not.
808   #
809   if (! $poll_p) {
810     my $count = 0;
811     opendir (my $dirh, $dir) || error ("$dir: $!");
812     foreach my $f (readdir ($dirh)) {
813       next if ($f =~ m/^\./s);
814       $count++;
815       last;
816     }
817     closedir $dirh;
818
819     if ($count <= 0) {
820       print STDERR "$progname: no files in cache of $url\n" if ($verbose);
821       $poll_p = 1;
822     }
823   }
824
825   if ($poll_p) {
826
827     print STDERR "$progname: loading $url\n" if ($verbose);
828
829     my %files;
830     opendir (my $dirh, $dir) || error ("$dir: $!");
831     foreach my $f (readdir ($dirh)) {
832       next if ($f eq '.' || $f eq '..');
833       $files{$f} = 0;  # 0 means "file exists, should be deleted"
834     }
835     closedir $dirh;
836
837     $files{$stamp} = 1;
838
839     # Download each image currently in the feed.
840     #
841     my $count = 0;
842     my @urls = parse_feed ($url);
843     print STDERR "$progname: " . ($#urls + 1) . " images\n"
844       if ($verbose > 1);
845     foreach my $p (@urls) {
846       my ($furl, $id) = @$p;
847       $furl = expand_url ($furl, $url);
848       my $f = download_image ($furl, $id, $dir);
849       next unless $f;
850       $files{$f} = 1;    # Got it, don't delete
851       $count++;
852     }
853
854     my $empty_p = ($count <= 0);
855
856     # Now delete any files that are no longer in the feed.
857     # But if there was nothing in the feed (network failure?)
858     # then don't blow away the old files.
859     #
860     my $kept = 0;
861     foreach my $f (keys(%files)) {
862       if ($count <= 0) {
863         $kept++;
864       } elsif ($files{$f}) {
865         $kept++;
866       } else {
867         if (unlink ("$dir/$f")) {
868           print STDERR "$progname: rm $dir/$f\n" if ($verbose > 1);
869         } else {
870           print STDERR "$progname: rm $dir/$f: $!\n";   # don't bail
871         }
872       }
873     }
874
875     # Both feed and cache are empty. No files at all. Bail.
876     error ("empty feed: $url") if ($kept <= 1);
877
878     # Feed is empty, but we have some files from last time. Warn.
879     print STDERR "$progname: empty feed: using cache: $url\n"
880       if ($empty_p);
881
882     $mtime = time();    # update the timestamp
883
884   } else {
885
886     # Not yet time to re-check the URL.
887     print STDERR "$progname: using cache: $url\n" if ($verbose);
888
889   }
890
891   # Unlock and update the write date on the .timestamp file.
892   #
893   truncate ($lock_fd, 0) || error ("unable to truncate $lock: $!");
894   seek ($lock_fd, 0, 0)  || error ("unable to rewind $lock: $!");
895   utime ($mtime, $mtime, $lock_fd) || error ("unable to touch $lock: $!");
896   flock ($lock_fd, LOCK_UN) || error ("unable to unlock $lock: $!");
897   close ($lock_fd);
898   $lock_fd = undef;
899   print STDERR "$progname: unlocked $lock\n" if ($verbose > 1);
900
901   # Don't bother using the imageDirectory cache.  We know that this directory
902   # is flat, and we can assume that an RSS feed doesn't contain 100,000 images
903   # like ~/Pictures/ might.
904   #
905   $cache_p = 0;
906
907   # Return the URL and directory name of the files of that URL's local cache.
908   #
909   return ($url, $dir);
910 }
911
912
913 sub find_random_file($) {
914   my ($dir) = @_;
915
916   if ($use_spotlight_p == -1) {
917     $use_spotlight_p = 0;
918     if (-x '/usr/bin/mdfind') {
919       $use_spotlight_p = 1;
920     }
921   }
922
923   my $url;
924   ($url, $dir) = mirror_feed ($dir);
925
926   if ($url) {
927     $use_spotlight_p = 0;
928     print STDERR "$progname: $dir is cache for $url\n" if ($verbose > 1);
929   }
930
931   @all_files = read_cache ($dir);
932
933   if ($#all_files >= 0) {
934     # got it from the cache...
935
936   } elsif ($use_spotlight_p) {
937     print STDERR "$progname: spotlighting $dir...\n" if ($verbose);
938     spotlight_all_files ($dir);
939     print STDERR "$progname: found " . ($#all_files+1) .
940                  " file" . ($#all_files == 0 ? "" : "s") .
941                  " via Spotlight\n"
942       if ($verbose);
943   } else {
944     print STDERR "$progname: recursively reading $dir...\n" if ($verbose);
945     find_all_files ($dir);
946     print STDERR "$progname: " .
947                  "f=" . ($#all_files+1) . "; " .
948                  "d=$dir_count; " .
949                  "s=$stat_count; " .
950                  "skip=${skip_count_unstat}+$skip_count_stat=" .
951                   ($skip_count_unstat + $skip_count_stat) .
952                  ".\n"
953       if ($verbose);
954   }
955
956   write_cache ($dir);
957
958   if ($#all_files < 0) {
959     print STDERR "$progname: no files in $dir\n";
960     exit 1;
961   }
962
963   my $max_tries = 50;
964   for (my $i = 0; $i < $max_tries; $i++) {
965
966     my $n = int (rand ($#all_files + 1));
967     my $file = $all_files[$n];
968     if (large_enough_p ($file)) {
969       if (! $url) {
970         $file =~ s@^\Q$dir/@@so || die;  # remove $dir from front
971       }
972       return $file;
973     }
974   }
975
976   print STDERR "$progname: no suitable images in $dir " .
977                "(after $max_tries tries)\n";
978
979   # If we got here, blow away the cache.  Maybe it's stale.
980   unlink $cache_file_name if $cache_file_name;
981
982   exit 1;
983 }
984
985
986 sub large_enough_p($) {
987   my ($file) = @_;
988
989   my ($w, $h) = image_file_size ($file);
990
991   if (!defined ($h)) {
992
993     # Nonexistent files are obviously too small!
994     # Already printed $verbose message about the file not existing.
995     return 0 unless -f $file;
996
997     print STDERR "$progname: $file: unable to determine image size\n"
998       if ($verbose);
999     # Assume that unknown files are of good sizes: this will happen if
1000     # they matched $good_file_re, but we don't have code to parse them.
1001     # (This will also happen if the file is junk...)
1002     return 1;
1003   }
1004
1005   if ($w < $min_image_width || $h < $min_image_height) {
1006     print STDERR "$progname: $file: too small ($w x $h)\n" if ($verbose);
1007     return 0;
1008   }
1009
1010   print STDERR "$progname: $file: $w x $h\n" if ($verbose);
1011   return 1;
1012 }
1013
1014
1015
1016 # Given the raw body of a GIF document, returns the dimensions of the image.
1017 #
1018 sub gif_size($) {
1019   my ($body) = @_;
1020   my $type = substr($body, 0, 6);
1021   my $s;
1022   return () unless ($type =~ /GIF8[7,9]a/);
1023   $s = substr ($body, 6, 10);
1024   my ($a,$b,$c,$d) = unpack ("C"x4, $s);
1025   return (($b<<8|$a), ($d<<8|$c));
1026 }
1027
1028 # Given the raw body of a JPEG document, returns the dimensions of the image.
1029 #
1030 sub jpeg_size($) {
1031   my ($body) = @_;
1032   my $i = 0;
1033   my $L = length($body);
1034
1035   my $c1 = substr($body, $i, 1); $i++;
1036   my $c2 = substr($body, $i, 1); $i++;
1037   return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
1038
1039   my $ch = "0";
1040   while (ord($ch) != 0xDA && $i < $L) {
1041     # Find next marker, beginning with 0xFF.
1042     while (ord($ch) != 0xFF) {
1043       return () if (length($body) <= $i);
1044       $ch = substr($body, $i, 1); $i++;
1045     }
1046     # markers can be padded with any number of 0xFF.
1047     while (ord($ch) == 0xFF) {
1048       return () if (length($body) <= $i);
1049       $ch = substr($body, $i, 1); $i++;
1050     }
1051
1052     # $ch contains the value of the marker.
1053     my $marker = ord($ch);
1054
1055     if (($marker >= 0xC0) &&
1056         ($marker <= 0xCF) &&
1057         ($marker != 0xC4) &&
1058         ($marker != 0xCC)) {  # it's a SOFn marker
1059       $i += 3;
1060       return () if (length($body) <= $i);
1061       my $s = substr($body, $i, 4); $i += 4;
1062       my ($a,$b,$c,$d) = unpack("C"x4, $s);
1063       return (($c<<8|$d), ($a<<8|$b));
1064
1065     } else {
1066       # We must skip variables, since FFs in variable names aren't
1067       # valid JPEG markers.
1068       return () if (length($body) <= $i);
1069       my $s = substr($body, $i, 2); $i += 2;
1070       my ($c1, $c2) = unpack ("C"x2, $s);
1071       my $length = ($c1 << 8) | $c2;
1072       return () if ($length < 2);
1073       $i += $length-2;
1074     }
1075   }
1076   return ();
1077 }
1078
1079 # Given the raw body of a PNG document, returns the dimensions of the image.
1080 #
1081 sub png_size($) {
1082   my ($body) = @_;
1083   return () unless ($body =~ m/^\211PNG\r/s);
1084   my ($bits) = ($body =~ m/^.{12}(.{12})/s);
1085   return () unless defined ($bits);
1086   return () unless ($bits =~ /^IHDR/);
1087   my ($ign, $w, $h) = unpack("a4N2", $bits);
1088   return ($w, $h);
1089 }
1090
1091
1092 # Given the raw body of a GIF, JPEG, or PNG document, returns the dimensions
1093 # of the image.
1094 #
1095 sub image_size($) {
1096   my ($body) = @_;
1097   return () if (length($body) < 10);
1098   my ($w, $h) = gif_size ($body);
1099   if ($w && $h) { return ($w, $h); }
1100   ($w, $h) = jpeg_size ($body);
1101   if ($w && $h) { return ($w, $h); }
1102   # #### TODO: need image parsers for TIFF, XPM, XBM.
1103   return png_size ($body);
1104 }
1105
1106 # Returns the dimensions of the image file.
1107 #
1108 sub image_file_size($) {
1109   my ($file) = @_;
1110   my $in;
1111   if (! open ($in, '<:raw', $file)) {
1112     print STDERR "$progname: $file: $!\n" if ($verbose);
1113     return ();
1114   }
1115   my $body = '';
1116   sysread ($in, $body, 1024 * 50);  # The first 50k should be enough.
1117   close $in;                        # (It's not for certain huge jpegs...
1118   return image_size ($body);        # but we know they're huge!)
1119 }
1120
1121
1122 sub error($) {
1123   my ($err) = @_;
1124   print STDERR "$progname: $err\n";
1125   exit 1;
1126 }
1127
1128 sub usage() {
1129   print STDERR "usage: $progname [--verbose] directory-or-feed-url\n\n" .
1130   "       Prints the name of a randomly-selected image file.  The directory\n" .
1131   "       is searched recursively.  Images smaller than " .
1132          "${min_image_width}x${min_image_height} are excluded.\n" .
1133   "\n" .
1134   "       The directory may also be the URL of an RSS/Atom feed.  Enclosed\n" .
1135   "       images will be downloaded and cached locally.\n" .
1136   "\n";
1137   exit 1;
1138 }
1139
1140 sub main() {
1141   my $dir = undef;
1142
1143   while ($_ = $ARGV[0]) {
1144     shift @ARGV;
1145     if    (m/^--?verbose$/s)      { $verbose++; }
1146     elsif (m/^-v+$/s)             { $verbose += length($_)-1; }
1147     elsif (m/^--?name$/s)         { }   # ignored, for compatibility
1148     elsif (m/^--?spotlight$/s)    { $use_spotlight_p = 1; }
1149     elsif (m/^--?no-spotlight$/s) { $use_spotlight_p = 0; }
1150     elsif (m/^--?cache$/s)        { $cache_p = 1; }
1151     elsif (m/^--?no-?cache$/s)    { $cache_p = 0; }
1152     elsif (m/^-./)                { usage; }
1153     elsif (!defined($dir))        { $dir = $_; }
1154     else                          { usage; }
1155   }
1156
1157   usage unless (defined($dir));
1158
1159   $dir =~ s@^feed:@http:@si;
1160
1161   if ($dir =~ m/^https?:/si) {
1162     # ok
1163   } else {
1164     $dir =~ s@^~/@$ENV{HOME}/@s;     # allow literal "~/"
1165     $dir =~ s@/+$@@s;              # omit trailing /
1166
1167     if (! -d $dir) {
1168       print STDERR "$progname: $dir: not a directory or URL\n";
1169       usage;
1170     }
1171   }
1172
1173   my $file = find_random_file ($dir);
1174   print STDOUT "$file\n";
1175 }
1176
1177 main;
1178 exit 0;