ftp://updates.redhat.com/enterprise/2.1AS/en/os/SRPMS/xscreensaver-3.33-4.rhel21...
[xscreensaver] / hacks / webcollage
1 #!/usr/bin/perl -w
2 #
3 # webcollage, Copyright (c) 1999-2001 by Jamie Zawinski <jwz@jwz.org>
4 # This program decorates the screen with random images from the web.
5 # One satisfied customer described it as "a nonstop pop culture brainbath."
6 #
7 # Permission to use, copy, modify, distribute, and sell this software and its
8 # documentation for any purpose is hereby granted without fee, provided that
9 # the above copyright notice appear in all copies and that both that
10 # copyright notice and this permission notice appear in supporting
11 # documentation.  No representations are made about the suitability of this
12 # software for any purpose.  It is provided "as is" without express or 
13 # implied warranty.
14
15 # To run this as a display mode with xscreensaver, add this to `programs':
16 #
17 #   default-n:  webcollage -root                                        \n\
18 #   default-n:  webcollage -root -filter 'vidwhacker -stdin -stdout'    \n\
19
20
21 require 5;
22 use strict;
23
24 # We can't "use diagnostics" here, because that library malfunctions if
25 # you signal and catch alarms: it says "Uncaught exception from user code"
26 # and exits, even though I damned well AM catching it!
27 #use diagnostics;
28
29
30 use Socket;
31 require Time::Local;
32 require POSIX;
33 use Fcntl ':flock'; # import LOCK_* constants
34 use POSIX qw(strftime);
35
36
37 my $progname = $0; $progname =~ s@.*/@@g;
38 my $version = q{ $Revision: 1.77 $ }; $version =~ s/^[^0-9]+([0-9.]+).*$/$1/;
39 my $copyright = "WebCollage $version, Copyright (c) 1999-2001" .
40     " Jamie Zawinski <jwz\@jwz.org>\n" .
41     "            http://www.jwz.org/xscreensaver/\n";
42
43
44
45 my @search_methods = (  35, "imagevista", \&pick_from_alta_vista_images,
46                         33, "altavista",  \&pick_from_alta_vista_text,
47                         20, "yahoorand",  \&pick_from_yahoo_random_link,
48                          2, "yahoonews",  \&pick_from_yahoo_news_text,
49                         10, "lycos",      \&pick_from_lycos_text,
50
51                      # Hotbot gives me "no matches" just about every time.
52                      # Then I try the same URL again, and it works.  I guess
53                      # it caches searches, and webcollage always busts its
54                      # cache and time out?  Or it just sucks.
55                      #   0, "hotbot",     \&pick_from_hotbot_text,
56                       );
57
58 #@search_methods=(100, "lycos",     \&pick_from_lycos_text);
59
60 # programs we can use to write to the root window (tried in ascending order.)
61 #
62 my @root_displayers = ( 
63   "xloadimage -quiet -onroot -center -border black",
64   "xli        -quiet -onroot -center -border black",
65   "xv         -root -quit -viewonly +noresetroot -rmode 5" .
66   "           -rfg black -rbg black",
67   "chbg       -once -xscreensaver",
68
69 # this lame program wasn't built with vroot.h:
70 # "xsri       -scale -keep-aspect -center-horizontal -center-vertical",
71 );
72
73
74 # Some sites need cookies to work properly.   These are they.
75 #
76 my %cookies = (
77   "www.altavista.com"  =>  "AV_ALL=1",   # request uncensored searches
78   "web.altavista.com"  =>  "AV_ALL=1",
79
80                                          # log in as "cpunks"
81   "www.nytimes.com"    =>  "NYT-S=104nv1sChNnnWAvTLGx6eiDhzQcbSoN" .
82                                  "6zOMB7s0Qm8MlMaa8It.2/BlXTrpbBk" .
83                                  "jinV68IcqxOvAABDyKdciIJ8O000",
84 );
85
86
87 # Some sites have  managed to poison the search engines.  These are they.
88 # (We auto-detect sites that have poisoned the search engines via excessive
89 # keywords or dictionary words,  but these are ones that slip through
90 # anyway.)
91 #
92 # This can contain full host names, or 2 or 3 component domains.
93 #
94 my %poisoners = (
95   "die.net"                 => 1,  # 'l33t h4ck3r d00dz.
96   "genforum.genealogy.com"  => 1,  # Cluttering altavista with human names.
97   "rootsweb.com"            => 1,  # Cluttering altavista with human names.
98   "akamai.net"              => 1,  # Lots of sites have their images on Akamai.
99                                    # But those are pretty much all banners.
100                                    # Since Akamai is super-expensive, let's
101                                    # go out on a limb and assume that all of
102                                    # their customers are rich-and-boring.
103 );
104
105
106 # When verbosity is turned on, we warn about sites that we seem to be hitting
107 # a lot: usually this means some new poisoner has made it into the search
108 # engines.  But sometimes, the warning is just because that site has a lot
109 # of stuff on it.  So these are the sites that are immune to the "frequent
110 # site" diagnostic message.
111 #
112 my %warningless_sites = (
113   "home.earthlink.net"      => 1,  # Lots of home pages here.
114   "www.geocities.com"       => 1,
115   "www.angelfire.com"       => 1,
116   "members.aol.com"         => 1,
117
118   "yimg.com"                => 1,  # This is where dailynews.yahoo.com stores
119   "eimg.com"                => 1,  # its images, so pick_from_yahoo_news_text()
120                                    # hits this every time.
121 );
122
123
124 ##############################################################################
125 #
126 # Various global flags set by command line parameters, or computed
127 #
128 ##############################################################################
129
130
131 my $current_state = "???";      # for diagnostics
132 my $load_method;
133 my $last_search;
134 my $image_succeeded = -1;
135 my $suppress_audit = 0;
136
137 my $verbose_imgmap = 0;         # print out rectangles and URLs only (stdout)
138 my $verbose_warnings = 0;       # print out warnings when things go wrong
139 my $verbose_load = 0;           # diagnostics about loading of URLs
140 my $verbose_filter = 0;         # diagnostics about page selection/rejection
141 my $verbose_net = 0;            # diagnostics about network I/O
142 my $verbose_pbm = 0;            # diagnostics about PBM pipelines
143 my $verbose_http = 0;           # diagnostics about all HTTP activity
144 my $verbose_exec = 0;           # diagnostics about executing programs
145
146 my $report_performance_interval = 60 * 15;  # print some stats every 15 minutes
147
148 my $http_proxy = undef;
149 my $http_timeout = 30;
150 my $cvt_timeout = 10;
151
152 my $min_width = 50;
153 my $min_height = 50;
154 my $min_ratio = 1/5;
155
156 my $no_output_p = 0;
157 my $urls_only_p = 0;
158
159 my $wordlist = "/usr/dict/words";
160
161 if (!-r $wordlist) {
162   $wordlist = "/usr/share/dict/words";          # BSD
163 }
164 if (!-r $wordlist) {
165   $wordlist = "/usr/share/lib/dict/words";      # Irix
166 }
167 die "$progname: $wordlist doesn't exist!\n" unless (-r $wordlist);
168
169 my %rejected_urls;
170 my @tripwire_words = ("aberrate", "abode", "amorphous", "antioch",
171                       "arrhenius", "arteriole", "blanket", "brainchild",
172                       "burdensome", "carnival", "cherub", "chord", "clever",
173                       "dedicate", "dilogarithm", "dolan", "dryden",
174                       "eggplant");
175
176
177 ##############################################################################
178 #
179 # Retrieving URLs
180 #
181 ##############################################################################
182
183 # returns three values: the HTTP response line; the document headers;
184 # and the document body.
185 #
186 sub get_document_1 {
187   my ( $url, $referer, $timeout ) = @_;
188
189   if (!defined($timeout)) { $timeout = $http_timeout; }
190   if ($timeout > $http_timeout) { $timeout = $http_timeout; }
191
192   if ($timeout <= 0) {
193     LOG (($verbose_net || $verbose_load), "timed out for $url");
194     return ();
195   }
196
197   LOG ($verbose_net, "get_document_1 $url " . ($referer ? $referer : ""));
198
199   if (! ($url =~ m@^http://@i)) {
200     LOG ($verbose_net, "not an HTTP URL: $url");
201     return ();
202   }
203
204   my ($url_proto, $dummy, $serverstring, $path) = split(/\//, $url, 4);
205   $path = "" unless $path;
206
207   my ($them,$port) = split(/:/, $serverstring);
208   $port = 80 unless $port;
209
210   my $them2 = $them;
211   my $port2 = $port;
212   if ($http_proxy) {
213     $serverstring = $http_proxy if $http_proxy;
214     ($them2,$port2) = split(/:/, $serverstring);
215     $port2 = 80 unless $port2;
216   }
217
218   my ($remote, $iaddr, $paddr, $proto, $line);
219   $remote = $them2;
220   if ($port2 =~ /\D/) { $port2 = getservbyname($port2, 'tcp') }
221   if (!$port2) {
222     LOG (($verbose_net || $verbose_load), "unrecognised port in $url");
223     return ();
224   }
225   $iaddr   = inet_aton($remote);
226   if (!$iaddr) {
227     LOG (($verbose_net || $verbose_load), "host not found: $remote");
228     return ();
229   }
230   $paddr   = sockaddr_in($port2, $iaddr);
231
232
233   my $head = "";
234   my $body = "";
235
236   @_ =
237     eval {
238       local $SIG{ALRM} = sub {
239         LOG (($verbose_net || $verbose_load), "timed out ($timeout) for $url");
240         die "alarm\n";
241       };
242       alarm $timeout;
243
244       $proto   = getprotobyname('tcp');
245       if (!socket(S, PF_INET, SOCK_STREAM, $proto)) {
246         LOG (($verbose_net || $verbose_load), "socket: $!");
247         return ();
248       }
249       if (!connect(S, $paddr)) {
250         LOG (($verbose_net || $verbose_load), "connect($serverstring): $!");
251         return ();
252       }
253
254       select(S); $| = 1; select(STDOUT);
255
256       my $cookie = $cookies{$them};
257
258       my $hdrs = "GET " . ($http_proxy ? $url : "/$path") . " HTTP/1.0\r\n" .
259                  "Host: $them\r\n" .
260                  "User-Agent: $progname/$version\r\n";
261       if ($referer) {
262         $hdrs .= "Referer: $referer\r\n";
263       }
264       if ($cookie) {
265         foreach (split(/\r?\n/, $cookie)) {
266           $hdrs .= "Cookie: $_\r\n";
267         }
268       }
269       $hdrs .= "\r\n";
270
271       foreach (split('\r?\n', $hdrs)) {
272         LOG ($verbose_http, "  ==> $_");
273       }
274       print S $hdrs;
275       my $http = <S>;
276
277       $_  = $http;
278       s/[\r\n]+$//s;
279       LOG ($verbose_http, "  <== $_");
280
281       while (<S>) {
282         $head .= $_;
283         s/[\r\n]+$//s;
284         last if m@^$@;
285         LOG ($verbose_http, "  <== $_");
286
287         if (m@^Set-cookie:\s*([^;\r\n]+)@i) {
288           set_cookie($them, $1)
289         }
290       }
291
292       my $lines = 0;
293       while (<S>) {
294         $body .= $_;
295         $lines++;
296       }
297
298       LOG ($verbose_http,
299            "  <== [ body ]: $lines lines, " . length($body) . " bytes");
300
301       close S;
302
303       if (!$http) {
304         LOG (($verbose_net || $verbose_load), "null response: $url");
305         return ();
306       }
307
308       return ( $http, $head, $body );
309     };
310   die if ($@ && $@ ne "alarm\n");       # propagate errors
311   if ($@) {
312     # timed out
313     $head = undef;
314     $body = undef;
315     $suppress_audit = 1;
316     return ();
317   } else {
318     # didn't
319     alarm 0;
320     return @_;
321   }
322 }
323
324
325 # returns two values: the document headers; and the document body.
326 # if the given URL did a redirect, returns the redirected-to document.
327 #
328 sub get_document {
329   my ( $url, $referer, $timeout ) = @_;
330   my $start = time;
331
332   my $orig_url = $url;
333   my $loop_count = 0;
334   my $max_loop_count = 4;
335
336   do {
337     if (defined($timeout) && $timeout <= 0) {
338       LOG (($verbose_net || $verbose_load), "timed out for $url");
339       $suppress_audit = 1;
340       return ();
341     }
342
343     my ( $http, $head, $body ) = get_document_1 ($url, $referer, $timeout);
344
345     if (defined ($timeout)) {
346       my $now = time;
347       my $elapsed = $now - $start;
348       $timeout -= $elapsed;
349       $start = $now;
350     }
351
352     return () unless $http; # error message already printed
353
354     $http =~ s/[\r\n]+$//s;
355
356     if ( $http =~ m@^HTTP/[0-9.]+ 30[123]@ ) {
357       $_ = $head;
358       my ( $location ) = m@^location:[ \t]*(.*)$@im;
359       if ( $location ) {
360         $location =~ s/[\r\n]$//;
361
362         LOG ($verbose_net, "redirect from $url to $location");
363         $referer = $url;
364         $url = $location;
365
366         if ($url =~ m@^/@) {
367           $referer =~ m@^(http://[^/]+)@i;
368           $url = $1 . $url;
369         } elsif (! ($url =~ m@^[a-z]+:@i)) {
370           $_ = $referer;
371           s@[^/]+$@@g if m@^http://[^/]+/@i;
372           $_ .= "/" if m@^http://[^/]+$@i;
373           $url = $_ . $url;
374         }
375
376       } else {
377         LOG ($verbose_net, "no Location with \"$http\"");
378         return ( $url, $body );
379       }
380
381       if ($loop_count++ > $max_loop_count) {
382         LOG ($verbose_net,
383              "too many redirects ($max_loop_count) from $orig_url");
384         $body = undef;
385         return ();
386       }
387
388     } elsif ( $http =~ m@^HTTP/[0-9.]+ ([4-9][0-9][0-9].*)$@ ) {
389
390       LOG (($verbose_net || $verbose_load), "failed: $1 ($url)");
391
392       # http errors -- return nothing.
393       $body = undef;
394       return ();
395
396     } elsif (!$body) {
397
398       LOG (($verbose_net || $verbose_load), "document contains no data: $url");
399       return ();
400
401     } else {
402
403       # ok!
404       return ( $url, $body );
405     }
406
407   } while (1);
408 }
409
410 # If we already have a cookie defined for this site, and the site is trying
411 # to overwrite that very same cookie, let it do so.  This is because nytimes
412 # expires its cookies - it lets you upgrade to a new cookie without logging
413 # in again, but you have to present the old cookie to get the new cookie.
414 # So, by doing this, the built-in cypherpunks cookie will never go "stale".
415 #
416 sub set_cookie {
417   my ($host, $cookie) = @_;
418   my $oc = $cookies{$host};
419   return unless $oc;
420   $_ = $oc;
421   my ($oc_name, $oc_value) = m@^([^= \t\r\n]+)=(.*)$@;
422   $_ = $cookie;
423   my ($nc_name, $nc_value) = m@^([^= \t\r\n]+)=(.*)$@;
424
425   if ($oc_name eq $nc_name &&
426       $oc_value ne $nc_value) {
427     $cookies{$host} = $cookie;
428     LOG ($verbose_net, "overwrote ${host}'s $oc_name cookie");
429   }
430 }
431
432
433 ############################################################################
434 #
435 # Extracting image URLs from HTML
436 #
437 ############################################################################
438
439 # given a URL and the body text at that URL, selects and returns a random
440 # image from it.  returns () if no suitable images found.
441 #
442 sub pick_image_from_body {
443   my ( $url, $body ) = @_;
444
445   my $base = $url;
446   $_ = $url;
447
448   # if there's at least one slash after the host, take off the last
449   # pathname component
450   if ( m@^http://[^/]+/@io ) {
451     $base =~ s@[^/]+$@@go;
452   }
453
454   # if there are no slashes after the host at all, put one on the end.
455   if ( m@^http://[^/]+$@io ) {
456     $base .= "/";
457   }
458
459   $_ = $body;
460
461   # strip out newlines, compress whitespace
462   s/[\r\n\t ]+/ /go;
463
464   # nuke comments
465   s/<!--.*?-->//go;
466
467
468   # There are certain web sites that list huge numbers of dictionary
469   # words in their bodies or in their <META NAME=KEYWORDS> tags (surprise!
470   # Porn sites tend not to be reputable!)
471   #
472   # I do not want webcollage to filter on content: I want it to select
473   # randomly from the set of images on the web.  All the logic here for
474   # rejecting some images is really a set of heuristics for rejecting
475   # images that are not really images: for rejecting *text* that is in
476   # GIF/JPEG form.  I don't want text, I want pictures, and I want the
477   # content of the pictures to be randomly selected from among all the
478   # available content.
479   #
480   # So, filtering out "dirty" pictures by looking for "dirty" keywords
481   # would be wrong: dirty pictures exist, like it or not, so webcollage
482   # should be able to select them.
483   #
484   # However, picking a random URL is a hard thing to do.  The mechanism I'm
485   # using is to search for a selection of random words.  This is not
486   # perfect, but works ok most of the time.  The way it breaks down is when
487   # some URLs get precedence because their pages list *every word* as
488   # related -- those URLs come up more often than others.
489   #
490   # So, after we've retrieved a URL, if it has too many keywords, reject
491   # it.  We reject it not on the basis of what those keywords are, but on
492   # the basis that by having so many, the page has gotten an unfair
493   # advantage against our randomizer.
494   #
495   my $trip_count = 0;
496   foreach my $trip (@tripwire_words) {
497     $trip_count++ if m/$trip/i;
498   }
499
500   if ($trip_count >= $#tripwire_words - 2) {
501     LOG (($verbose_filter || $verbose_load),
502          "there is probably a dictionary in \"$url\": rejecting.");
503     $rejected_urls{$url} = -1;
504     $body = undef;
505     $_ = undef;
506     return ();
507   }
508
509
510   my @urls;
511   my %unique_urls;
512
513   foreach (split(/ *</)) {
514     if ( m/^meta /i ) {
515
516       # Likewise, reject any web pages that have a KEYWORDS meta tag
517       # that is too long.
518       #
519       if (m/name ?= ?\"?keywords\"?/i &&
520           m/content ?= ?\"([^\"]+)\"/) {
521         my $L = length($1);
522         if ($L > 1000) {
523           LOG (($verbose_filter || $verbose_load),
524                "excessive keywords ($L bytes) in $url: rejecting.");
525           $rejected_urls{$url} = $L;
526           $body = undef;
527           $_ = undef;
528           return ();
529         } else {
530           LOG ($verbose_filter, "  keywords ($L bytes) in $url (ok)");
531         }
532       }
533
534     } elsif ( m/^(img|a) .*(src|href) ?= ?\"? ?(.*?)[ >\"]/io ) {
535
536       my $was_inline = ( "$1" eq "a" || "$1" eq "A" );
537       my $link = $3;
538       my ( $width )  = m/width ?=[ \"]*(\d+)/oi;
539       my ( $height ) = m/height ?=[ \"]*(\d+)/oi;
540       $_ = $link;
541
542       if ( m@^/@o ) {
543         my $site;
544         ( $site = $base ) =~ s@^(http://[^/]*).*@$1@gio;
545         $_ = "$site$link";
546       } elsif ( ! m@^[^/:?]+:@ ) {
547         $_ = "$base$link";
548         s@/\./@/@g;
549         while (s@/\.\./@/@g) {
550         }
551       }
552
553       # skip non-http
554       if ( ! m@^http://@io ) {
555         next;
556       }
557
558       # skip non-image
559       if ( ! m@[.](gif|jpg|jpeg|pjpg|pjpeg)$@io ) {
560         next;
561       }
562
563       # skip really short or really narrow images
564       if ( $width && $width < $min_width) {
565         if (!$height) { $height = "?"; }
566         LOG ($verbose_filter, "  skip narrow image $_ (${width}x$height)");
567         next;
568       }
569
570       if ( $height && $height < $min_height) {
571         if (!$width) { $width = "?"; }
572         LOG ($verbose_filter, "  skip short image $_ (${width}x$height)");
573         next;
574       }
575
576       # skip images with ratios that make them look like banners.
577       if ($min_ratio && $width && $height &&
578           ($width * $min_ratio ) > $height) {
579         if (!$height) { $height = "?"; }
580         LOG ($verbose_filter, "  skip bad ratio $_ (${width}x$height)");
581         next;
582       }
583
584       my $url = $_;
585
586       if ($unique_urls{$url}) {
587         LOG ($verbose_filter, "  skip duplicate image $_");
588         next;
589       }
590
591       LOG ($verbose_filter,
592            "  image $url" . 
593            ($width && $height ? " (${width}x${height})" : "") .
594            ($was_inline ? " (inline)" : ""));
595
596       $urls[++$#urls] = $url;
597       $unique_urls{$url}++;
598
599       # jpegs are preferable to gifs.
600       $_ = $url;
601       if ( ! m@[.]gif$@io ) {
602         $urls[++$#urls] = $url;
603       }
604
605       # pointers to images are preferable to inlined images.
606       if ( ! $was_inline ) {
607         $urls[++$#urls] = $url;
608         $urls[++$#urls] = $url;
609       }
610     }
611   }
612
613   my $fsp = ($body =~ m@<frameset@i);
614
615   $_ = undef;
616   $body = undef;
617
618   if ( $#urls < 0 ) {
619     LOG ($verbose_load, "no images on $base" . ($fsp ? " (frameset)" : ""));
620     return ();
621   }
622
623   @urls = depoison (@urls);
624
625   # pick a random element of the table
626   my $i = int(rand($#urls+1));
627   $url = $urls[$i];
628
629   LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#urls+1) . ": $url");
630
631   return $url;
632 }
633
634
635 \f
636 ############################################################################
637 #
638 # Subroutines for getting pages and images out of search engines
639 #
640 ############################################################################
641
642
643 # returns a random word from the dictionary
644 #
645 sub random_word {
646     
647     my $word = 0;
648     if (open (IN, "<$wordlist")) {
649         my $size = (stat(IN))[7];
650         my $pos = rand $size;
651         if (seek (IN, $pos, 0)) {
652             $word = <IN>;   # toss partial line
653             $word = <IN>;   # keep next line
654         }
655         if (!$word) {
656           seek( IN, 0, 0 );
657           $word = <IN>;
658         }
659         close (IN);
660     }
661
662     return 0 if (!$word);
663
664     $word =~ s/^[ \t\n\r]+//;
665     $word =~ s/[ \t\n\r]+$//;
666     $word =~ s/ys$/y/;
667     $word =~ s/ally$//;
668     $word =~ s/ly$//;
669     $word =~ s/ies$/y/;
670     $word =~ s/ally$/al/;
671     $word =~ s/izes$/ize/;
672     $word =~ tr/A-Z/a-z/;
673
674     if ( $word =~ s/[ \t\n\r]/\+/g ) {  # convert intra-word spaces to "+".
675       $word = "\%22$word\%22";          # And put quotes (%22) around it.
676     }
677
678     return $word;
679 }
680
681 sub random_words {
682   return (random_word . "%20" .
683           random_word . "%20" .
684           random_word . "%20" .
685           random_word . "%20" .
686           random_word);
687 }
688
689
690 # Loads the given URL (a search on some search engine) and returns:
691 # - the total number of hits the search engine claimed it had;
692 # - a list of URLs from the page that the search engine returned;
693 # Note that this list contains all kinds of internal search engine
694 # junk URLs too -- caller must prune them.
695 #
696 sub pick_from_search_engine {
697   my ( $timeout, $search_url, $words ) = @_;
698
699   $_ = $words;
700   s/%20/ /g;
701
702   print STDERR "\n\n" if ($verbose_load);
703
704   LOG ($verbose_load, "words: $_");
705   LOG ($verbose_load, "URL: $search_url");
706
707   $last_search = $search_url;   # for warnings
708
709   my $start = time;
710   my ( $base, $body ) = get_document ($search_url, undef, $timeout);
711   if (defined ($timeout)) {
712     $timeout -= (time - $start);
713     if ($timeout <= 0) {
714       $body = undef;
715       LOG (($verbose_net || $verbose_load),
716            "timed out (late) for $search_url");
717       $suppress_audit = 1;
718       return ();
719     }
720   }
721
722   return () if (! $body);
723
724
725   my @subpages;
726
727   my $search_count = "?";
728   if ($body =~ m@found (approximately |about )?(<B>)?(\d+)(</B>)? image@) {
729     $search_count = $3;
730   } elsif ($body =~ m@<NOBR>((\d{1,3})(,\d{3})*)&nbsp;@i) {
731     $search_count = $1;
732   } elsif ($body =~ m@found ((\d{1,3})(,\d{3})*|\d+) Web p@) {
733     $search_count = $1;
734   } elsif ($body =~ m@found about ((\d{1,3})(,\d{3})*|\d+) results@) {
735     $search_count = $1;
736   } elsif ($body =~ m@\b\d+ - \d+ of (\d+)\b@i) { # imagevista
737     $search_count = $1;
738   } elsif ($body =~ m@About ((\d{1,3})(,\d{3})*) images@i) { # imagevista
739     $search_count = $1;
740   } elsif ($body =~ m@WEB.*?RESULTS.*?\b((\d{1,3})(,\d{3})*)\b.*?Matches@i) {
741     $search_count = $1;                          # hotbot
742   } elsif ($body =~ m@no photos were found containing@i) { # imagevista
743     $search_count = "0";
744   } elsif ($body =~ m@found no document matching@i) { # altavista
745     $search_count = "0";
746   }
747   1 while ($search_count =~ s/^(\d+)(\d{3})/$1,$2/);
748
749 #  if ($search_count eq "?" || $search_count eq "0") {
750 #    local *OUT;
751 #    my $file = "/tmp/wc.html";
752 #    open(OUT, ">$file") || error ("writing $file: $!");
753 #    print OUT $body;
754 #    close OUT;
755 #    print STDERR  blurb() . "###### wrote $file\n";
756 #  }
757
758
759   my $length = length($body);
760   my $href_count = 0;
761
762   $_ = $body;
763
764   s/[\r\n\t ]+/ /g;
765
766
767   s/(<A )/\n$1/gi;
768   foreach (split(/\n/)) {
769     $href_count++;
770     my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
771     next unless $u;
772
773     if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; }   # quoted string
774     elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; }  # or token
775
776     if ( $rejected_urls{$u} ) {
777       LOG ($verbose_filter, "  pre-rejecting candidate: $u");
778       next;
779     }
780
781     LOG ($verbose_http, "    HREF: $u");
782
783     $subpages[++$#subpages] = $u;
784   }
785
786   if ( $#subpages < 0 ) {
787     LOG ($verbose_filter,
788          "found nothing on $base ($length bytes, $href_count links).");
789     return ();
790   }
791
792   LOG ($verbose_filter, "" . $#subpages+1 . " links on $search_url");
793
794   return ($search_count, @subpages);
795 }
796
797
798 sub depoison {
799   my (@urls) = @_;
800   my @urls2 = ();
801   foreach (@urls) {
802     my ($h) = m@^http://([^/: \t\r\n]+)@i;
803
804     next unless defined($h);
805
806     if ($poisoners{$h}) {
807       LOG (($verbose_filter), "  rejecting poisoner: $_");
808       next;
809     }
810     if ($h =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
811         $poisoners{$1}) {
812       LOG (($verbose_filter), "  rejecting poisoner: $_");
813       next;
814     }
815     if ($h =~ m@([^.]+\.[^.]+)$@ &&
816         $poisoners{$1}) {
817       LOG (($verbose_filter), "  rejecting poisoner: $_");
818       next;
819     }
820
821     push @urls2, $_;
822   }
823   return @urls2;
824 }
825
826
827 # given a list of URLs, picks one at random; loads it; and returns a
828 # random image from it.
829 # returns the url of the page loaded; the url of the image chosen;
830 # and a debugging description string.
831 #
832 sub pick_image_from_pages {
833   my ($base, $total_hit_count, $unfiltered_link_count, $timeout, @pages) = @_;
834
835   $total_hit_count = "?" unless defined($total_hit_count);
836
837   @pages = depoison (@pages);
838   LOG ($verbose_load,
839        "" . ($#pages+1) . " candidates of $unfiltered_link_count links" .
840        " ($total_hit_count total)");
841
842   return () if ($#pages < 0);
843
844   my $i = int(rand($#pages+1));
845   my $page = $pages[$i];
846
847   LOG ($verbose_load, "picked page $page");
848
849   $suppress_audit = 1;
850
851   my ( $base2, $body2 ) = get_document ($page, $base, $timeout);
852
853   if (!$base2 || !$body2) {
854     $body2 = undef;
855     return ();
856   }
857
858   my $img = pick_image_from_body ($base2, $body2);
859   $body2 = undef;
860
861   if ($img) {
862     return ($base2, $img);
863   } else {
864     return ();
865   }
866 }
867
868 \f
869 ############################################################################
870 #
871 # Pick images from random pages returned by the Yahoo Random Link
872 #
873 ############################################################################
874
875 # yahoorand
876 my $yahoo_random_link = "http://random.yahoo.com/bin/ryl";
877
878
879 # Picks a random page; picks a random image on that page;
880 # returns two URLs: the page containing the image, and the image.
881 # Returns () if nothing found this time.
882 #
883 sub pick_from_yahoo_random_link {
884   my ( $timeout ) = @_;
885
886   print STDERR "\n\n" if ($verbose_load);
887   LOG ($verbose_load, "URL: $yahoo_random_link");
888
889   $last_search = $yahoo_random_link;   # for warnings
890
891   $suppress_audit = 1;
892
893   my ( $base, $body ) = get_document ($yahoo_random_link, undef, $timeout);
894   if (!$base || !$body) {
895     $body = undef;
896     return;
897   }
898
899   LOG ($verbose_load, "redirected to: $base"); 
900
901   my $img = pick_image_from_body ($base, $body);
902   $body = undef;
903
904   if ($img) {
905     return ($base, $img);
906   } else {
907     return ();
908   }
909 }
910
911 \f
912 ############################################################################
913 #
914 # Pick images by feeding random words into Alta Vista Image Search
915 #
916 ############################################################################
917
918
919 my $alta_vista_images_url = "http://www.altavista.com/cgi-bin/query" .
920                             "?ipht=1" .       # photos
921                             "&igrph=1" .      # graphics
922                             "&iclr=1" .       # color
923                             "&ibw=1" .        # b&w
924                             "&micat=1" .      # no partner sites
925                             "&imgset=1" .     # no partner sites
926                             "&stype=simage" . # do image search
927                             "&mmW=1" .        # unknown, but required
928                             "&q=";
929
930
931 # imagevista
932 sub pick_from_alta_vista_images {
933   my ( $timeout ) = @_;
934
935   my $words = random_words;
936   my $page = (int(rand(9)) + 1);
937   my $search_url = $alta_vista_images_url . $words;
938
939   if ($page > 1) {
940     $search_url .= "&pgno=" . $page;            # page number
941     $search_url .= "&stq=" . (($page-1) * 12);  # first hit result on page
942   }
943
944   my ($search_hit_count, @subpages) =
945     pick_from_search_engine ($timeout, $search_url, $words);
946
947   my @candidates = ();
948   foreach my $u (@subpages) {
949     next unless ($u =~ m@^http://@i);    #  skip non-HTTP or relative URLs
950     next if ($u =~ m@[/.]altavista\.com\b@i);     # skip altavista builtins
951     next if ($u =~ m@[/.]doubleclick\.net\b@i);   # you cretins
952     next if ($u =~ m@[/.]clicktomarket\.com\b@i); # more cretins
953
954     next if ($u =~ m@[/.]viewimages\.com\b@i);    # stacked deck
955     next if ($u =~ m@[/.]gettyimages\.com\b@i);
956
957     LOG ($verbose_filter, "  candidate: $u");
958     push @candidates, $u;
959   }
960
961   return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
962                                 $timeout, @candidates);
963 }
964
965
966 \f
967 ############################################################################
968 #
969 # Pick images by feeding random words into Alta Vista Text Search
970 #
971 ############################################################################
972
973
974 my $alta_vista_url = "http://www.altavista.com/cgi-bin/query?pg=q" .
975                      "&text=yes&kl=XX&stype=stext&q=";
976
977 # altavista
978 sub pick_from_alta_vista_text {
979   my ( $timeout ) = @_;
980
981   my $words = random_words;
982   my $page = (int(rand(9)) + 1);
983   my $search_url = $alta_vista_url . $words;
984
985   if ($page > 1) {
986     $search_url .= "&pgno=" . $page;
987     $search_url .= "&stq=" . (($page-1) * 10);
988   }
989
990   my ($search_hit_count, @subpages) =
991     pick_from_search_engine ($timeout, $search_url, $words);
992
993   my @candidates = ();
994   foreach my $u (@subpages) {
995
996     # Those altavista fuckers are playing really nasty redirection games
997     # these days: the filter your clicks through their site, but use
998     # onMouseOver to make it look like they're not!  Well, it makes it
999     # easier for us to identify search results...
1000     #
1001     next unless ($u =~ m@^/r\?ck_sm=[a-zA-Z0-9]+\&ref=[a-zA-Z0-9]+\&r=(.*)@);
1002     $u = $1;
1003
1004     LOG ($verbose_filter, "  candidate: $u");
1005     push @candidates, $u;
1006   }
1007
1008   return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1009                                 $timeout, @candidates);
1010 }
1011
1012
1013 \f
1014 ############################################################################
1015 #
1016 # Pick images by feeding random words into Hotbot
1017 #
1018 ############################################################################
1019
1020 my $hotbot_search_url = "http://hotbot.lycos.com/" .
1021                         "?SM=SC" .
1022                         "&DV=0" .
1023                         "&LG=any" .
1024                         "&FVI=1" .
1025                         "&DC=100" .
1026                         "&DE=0" .
1027                         "&SQ=1" .
1028                         "&TR=13" .
1029                         "&AM1=MC" .
1030                         "&MT=";
1031
1032 sub pick_from_hotbot_text {
1033   my ( $timeout ) = @_;
1034
1035   my $words = random_words;
1036   my $search_url = $hotbot_search_url . $words;
1037
1038   my ($search_hit_count, @subpages) =
1039     pick_from_search_engine ($timeout, $search_url, $words);
1040
1041   my @candidates = ();
1042   foreach my $u (@subpages) {
1043
1044     # Hotbot plays redirection games too
1045     next unless ($u =~ m@^/director.asp\?target=([^&]+)@);
1046     $u = url_decode($1);
1047
1048     LOG ($verbose_filter, "  candidate: $u");
1049     push @candidates, $u;
1050   }
1051
1052   return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1053                                 $timeout, @candidates);
1054 }
1055
1056
1057 \f
1058 ############################################################################
1059 #
1060 # Pick images by feeding random words into Lycos
1061 #
1062 ############################################################################
1063
1064 my $lycos_search_url = "http://lycospro.lycos.com/srchpro/" .
1065                        "?lpv=1" .
1066                        "&t=any" .
1067                        "&query=";
1068
1069 sub pick_from_lycos_text {
1070   my ( $timeout ) = @_;
1071
1072   my $words = random_words;
1073   my $start = int(rand(8)) * 10 + 1;
1074   my $search_url = $lycos_search_url . $words . "&start=$start";
1075
1076   my ($search_hit_count, @subpages) =
1077     pick_from_search_engine ($timeout, $search_url, $words);
1078
1079   my @candidates = ();
1080   foreach my $u (@subpages) {
1081
1082     # Lycos plays exact the same redirection game as hotbot.
1083     # Note that "id=0" is used for internal advertising links,
1084     # and 1+ are used for  search results.
1085     next unless ($u =~ m@^http://click.hotbot.com/director.asp\?id=[1-9]\d*&target=([^&]+)@);
1086     $u = url_decode($1);
1087
1088     LOG ($verbose_filter, "  candidate: $u");
1089     push @candidates, $u;
1090   }
1091
1092   return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1093                                 $timeout, @candidates);
1094 }
1095
1096
1097 \f
1098 ############################################################################
1099 #
1100 # Pick images by feeding random words into news.yahoo.com
1101 #
1102 ############################################################################
1103
1104 my $yahoo_news_url = "http://search.news.yahoo.com/search/news_photos?" .
1105                      "&z=&n=100&o=o&2=&3=&p=";
1106
1107 # yahoonews
1108 sub pick_from_yahoo_news_text {
1109   my ( $timeout ) = @_;
1110
1111   my $words = random_words;
1112   my $search_url = $yahoo_news_url . $words;
1113
1114   my ($search_hit_count, @subpages) =
1115     pick_from_search_engine ($timeout, $search_url, $words);
1116
1117   my @candidates = ();
1118   foreach my $u (@subpages) {
1119     # only accept URLs on Yahoo's news site
1120     next unless ($u =~ m@^http://dailynews.yahoo.com/@i);
1121
1122     LOG ($verbose_filter, "  candidate: $u");
1123     push @candidates, $u;
1124   }
1125
1126   return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1127                                 $timeout, @candidates);
1128 }
1129
1130
1131
1132 \f
1133 ############################################################################
1134 #
1135 # Pick a random image in a random way
1136 #
1137 ############################################################################
1138
1139
1140 # Picks a random image on a random page, and returns two URLs:
1141 # the page containing the image, and the image. 
1142 # Returns () if nothing found this time.
1143 # Uses the url-randomizer 1 time in 5, else the image randomizer.
1144 #
1145
1146 sub pick_image {
1147   my ( $timeout ) = @_;
1148
1149   $current_state = "select";
1150   $load_method = "none";
1151
1152   my $n = int(rand(100));
1153   my $fn = undef;
1154   my $total = 0;
1155   my @rest = @search_methods;
1156
1157   while (@rest) {
1158     my $pct  = shift @rest;
1159     my $name = shift @rest;
1160     my $tfn  = shift @rest;
1161     $total += $pct;
1162     if ($total > $n && !defined($fn)) {
1163       $fn = $tfn;
1164       $current_state = $name;
1165       $load_method = $current_state;
1166     }
1167   }
1168
1169   if ($total != 100) {
1170     error ("internal error: \@search_methods totals to $total%!");
1171   }
1172
1173   record_attempt ($current_state);
1174   return $fn->($timeout);
1175 }
1176
1177
1178 \f
1179 ############################################################################
1180 #
1181 # Statistics and logging
1182 #
1183 ############################################################################
1184
1185 sub timestr {
1186   return strftime ("%H:%M:%S: ", localtime);
1187 }
1188
1189 sub blurb {
1190   return "$progname: " . timestr() . "$current_state: ";
1191 }
1192
1193 sub error {
1194   ($_) = @_;
1195   print STDERR blurb() . "$_\n";
1196   exit 1;
1197 }
1198
1199
1200 my $lastlog = "";
1201
1202 sub clearlog {
1203   $lastlog = "";
1204 }
1205
1206 sub showlog {
1207   my $head = "$progname: DEBUG: ";
1208   foreach (split (/\n/, $lastlog)) {
1209     print STDERR "$head$_\n";
1210   }
1211   $lastlog = "";
1212 }
1213
1214 sub LOG {
1215   my ($print, $msg) = @_;
1216   my $blurb = timestr() . "$current_state: ";
1217   $lastlog .= "$blurb$msg\n";
1218   print STDERR "$progname: $blurb$msg\n" if $print;
1219 }
1220
1221
1222 my %stats_attempts;
1223 my %stats_successes;
1224 my %stats_elapsed;
1225
1226 my $last_state = undef;
1227 sub record_attempt {
1228   my ($name) = @_;
1229
1230   if ($last_state) {
1231     record_failure($last_state) unless ($image_succeeded > 0);
1232   }
1233   $last_state = $name;
1234
1235   clearlog();
1236   report_performance();
1237
1238   start_timer($name);
1239   $image_succeeded = 0;
1240   $suppress_audit = 0;
1241 }
1242
1243 sub record_success {
1244   my ($name, $url, $base) = @_;
1245   if (defined($stats_successes{$name})) {
1246     $stats_successes{$name}++;
1247   } else {
1248     $stats_successes{$name} = 1;
1249   }
1250
1251   stop_timer ($name, 1);
1252   my $o = $current_state;
1253   $current_state = $name;
1254   save_recent_url ($url, $base);
1255   $current_state = $o;
1256   $image_succeeded = 1;
1257   clearlog();
1258 }
1259
1260
1261 sub record_failure {
1262   my ($name) = @_;
1263
1264   return if $image_succeeded;
1265
1266   stop_timer ($name, 0);
1267   if ($verbose_load && !$verbose_exec) {
1268
1269     if ($suppress_audit) {
1270       print STDERR "$progname: " . timestr() . "(audit log suppressed)\n";
1271       return;
1272     }
1273
1274     my $o = $current_state;
1275     $current_state = "DEBUG";
1276
1277     my $line =  "#" x 78;
1278     print STDERR "\n\n\n";
1279     print STDERR ("#" x 78) . "\n";
1280     print STDERR blurb() . "failed to get an image.  Full audit log:\n";
1281     print STDERR "\n";
1282     showlog();
1283     print STDERR ("-" x 78) . "\n";
1284     print STDERR "\n\n";
1285
1286     $current_state = $o;
1287   }
1288   $image_succeeded = 0;
1289 }
1290
1291
1292
1293 sub stats_of {
1294   my ($name) = @_;
1295   my $i = $stats_successes{$name};
1296   my $j = $stats_attempts{$name};
1297   $i = 0 unless $i;
1298   $j = 0 unless $j;
1299   return "" . ($j ? int($i * 100 / $j) : "0") . "%";
1300 }
1301
1302
1303 my $current_start_time = 0;
1304
1305 sub start_timer {
1306   my ($name) = @_;
1307   $current_start_time = time;
1308
1309   if (defined($stats_attempts{$name})) {
1310     $stats_attempts{$name}++;
1311   } else {
1312     $stats_attempts{$name} = 1;
1313   }
1314   if (!defined($stats_elapsed{$name})) {
1315     $stats_elapsed{$name} = 0;
1316   }
1317 }
1318
1319 sub stop_timer {
1320   my ($name, $success) = @_;
1321   $stats_elapsed{$name} += time - $current_start_time;
1322 }
1323
1324
1325 my $last_report_time = 0;
1326 sub report_performance {
1327
1328   return unless $verbose_warnings;
1329
1330   my $now = time;
1331   return unless ($now >= $last_report_time + $report_performance_interval);
1332   my $ot = $last_report_time;
1333   $last_report_time = $now;
1334
1335   return if ($ot == 0);
1336
1337   my $blurb = "$progname: " . timestr();
1338
1339   print STDERR "\n";
1340   print STDERR "${blurb}Current standings:\n";
1341
1342   foreach my $name (sort keys (%stats_attempts)) {
1343     my $try = $stats_attempts{$name};
1344     my $suc = $stats_successes{$name} || 0;
1345     my $pct = int($suc * 100 / $try);
1346     my $secs = $stats_elapsed{$name};
1347     my $secs_link = int($secs / $try);
1348     print STDERR sprintf ("$blurb   %-12s %4s (%d/%d);\t %2d secs/link\n",
1349                           "$name:", "$pct%", $suc, $try, $secs_link);
1350   }
1351 }
1352
1353
1354
1355 my $max_recent_images = 400;
1356 my $max_recent_sites  = 20;
1357 my @recent_images = ();
1358 my @recent_sites = ();
1359
1360 sub save_recent_url {
1361   my ($url, $base) = @_;
1362
1363   return unless ($verbose_warnings);
1364
1365   $_ = $url;
1366   my ($site) = m@^http://([^ \t\n\r/:]+)@;
1367
1368   my $done = 0;
1369   foreach (@recent_images) {
1370     if ($_ eq $url) {
1371       print STDERR blurb() . "WARNING: recently-duplicated image: $url" .
1372         " (on $base via $last_search)\n";
1373       $done = 1;
1374       last;
1375     }
1376   }
1377
1378   # suppress "duplicate site" warning via %warningless_sites.
1379   #
1380   if ($warningless_sites{$site}) {
1381     $done = 1;
1382   } elsif ($site =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
1383            $warningless_sites{$1}) {
1384     $done = 1;
1385   } elsif ($site =~ m@([^.]+\.[^.]+)$@ &&
1386            $warningless_sites{$1}) {
1387     $done = 1;
1388   }
1389
1390   if (!$done) {
1391     foreach (@recent_sites) {
1392       if ($_ eq $site) {
1393         print STDERR blurb() . "WARNING: recently-duplicated site: $site" .
1394         " ($url on $base via $last_search)\n";
1395         last;
1396       }
1397     }
1398   }
1399
1400   push @recent_images, $url;
1401   push @recent_sites,  $site;
1402   shift @recent_images if ($#recent_images >= $max_recent_images);
1403   shift @recent_sites  if ($#recent_sites  >= $max_recent_sites);
1404 }
1405
1406
1407 \f
1408 ##############################################################################
1409 #
1410 # other utilities
1411 #
1412 ##############################################################################
1413
1414 # Does %-decoding.
1415 #
1416 sub url_decode {
1417   ($_) = @_;
1418   tr/+/ /;
1419   s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
1420   return $_;
1421 }
1422
1423
1424 # Given the raw body of a GIF document, returns the dimensions of the image.
1425 #
1426 sub gif_size {
1427   my ($body) = @_;
1428   my $type = substr($body, 0, 6);
1429   my $s;
1430   return () unless ($type =~ /GIF8[7,9]a/);
1431   $s = substr ($body, 6, 10);
1432   my ($a,$b,$c,$d) = unpack ("C"x4, $s);
1433   return (($b<<8|$a), ($d<<8|$c));
1434 }
1435
1436 # Given the raw body of a JPEG document, returns the dimensions of the image.
1437 #
1438 sub jpeg_size {
1439   my ($body) = @_;
1440   my $i = 0;
1441   my $L = length($body);
1442
1443   my $c1 = substr($body, $i, 1); $i++;
1444   my $c2 = substr($body, $i, 1); $i++;
1445   return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
1446
1447   my $ch = "0";
1448   while (ord($ch) != 0xDA && $i < $L) {
1449     # Find next marker, beginning with 0xFF.
1450     while (ord($ch) != 0xFF) {
1451       $ch = substr($body, $i, 1); $i++;
1452     }
1453     # markers can be padded with any number of 0xFF.
1454     while (ord($ch) == 0xFF) {
1455       $ch = substr($body, $i, 1); $i++;
1456     }
1457
1458     # $ch contains the value of the marker.
1459     my $marker = ord($ch);
1460
1461     if (($marker >= 0xC0) &&
1462         ($marker <= 0xCF) &&
1463         ($marker != 0xC4) &&
1464         ($marker != 0xCC)) {  # it's a SOFn marker
1465       $i += 3;
1466       my $s = substr($body, $i, 4); $i += 4;
1467       my ($a,$b,$c,$d) = unpack("C"x4, $s);
1468       return (($c<<8|$d), ($a<<8|$b));
1469
1470     } else {
1471       # We must skip variables, since FFs in variable names aren't
1472       # valid JPEG markers.
1473       my $s = substr($body, $i, 2); $i += 2;
1474       my ($c1, $c2) = unpack ("C"x2, $s); 
1475       my $length = ($c1 << 8) | $c2;
1476       return () if ($length < 2);
1477       $i += $length-2;
1478     }
1479   }
1480   return ();
1481 }
1482
1483 # Given the raw body of a GIF or JPEG document, returns the dimensions of
1484 # the image.
1485 #
1486 sub image_size {
1487   my ($body) = @_;
1488   my ($w, $h) = gif_size ($body);
1489   if ($w && $h) { return ($w, $h); }
1490   return jpeg_size ($body);
1491 }
1492
1493
1494 # returns the full path of the named program, or undef.
1495 #
1496 sub which {
1497   my ($prog) = @_;
1498   foreach (split (/:/, $ENV{PATH})) {
1499     if (-x "$_/$prog") {
1500       return $prog;
1501     }
1502   }
1503   return undef;
1504 }
1505
1506
1507 # Like rand(), but chooses numbers with a bell curve distribution.
1508 sub bellrand {
1509   ($_) = @_;
1510   $_ = 1.0 unless defined($_);
1511   $_ /= 3.0;
1512   return (rand($_) + rand($_) + rand($_));
1513 }
1514
1515
1516 ##############################################################################
1517 #
1518 # Generating a list of urls only
1519 #
1520 ##############################################################################
1521
1522 sub url_only_output {
1523   do {
1524     my ($base, $img) = pick_image;
1525     if ($img) {
1526       $base =~ s/ /%20/g;
1527       $img  =~ s/ /%20/g;
1528       print "$img $base\n";
1529     }
1530   } while (1);
1531 }
1532
1533 ##############################################################################
1534 #
1535 # Running as an xscreensaver module
1536 #
1537 ##############################################################################
1538
1539 my $image_ppm   = ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp") . "/webcollage." . $$;
1540 my $image_tmp1  = $image_ppm . "-1";
1541 my $image_tmp2  = $image_ppm . "-2";
1542
1543 my $filter_cmd = undef;
1544 my $post_filter_cmd = undef;
1545 my $background = undef;
1546
1547 my $img_width;            # size of the image being generated.
1548 my $img_height;
1549
1550 my $delay = 0;
1551
1552
1553 sub x_cleanup {
1554   my ($sig) = @_;
1555   print STDERR blurb() . "caught signal $sig.\n" if ($verbose_exec);
1556   unlink $image_ppm, $image_tmp1, $image_tmp2;
1557   exit 1;
1558 }
1559
1560
1561 # Like system, but prints status about exit codes, and kills this process
1562 # with whatever signal killed the sub-process, if any.
1563 #
1564 sub nontrapping_system {
1565   $! = 0;
1566     
1567   $_ = join(" ", @_);
1568   s/\"[^\"]+\"/\"...\"/g;
1569
1570   LOG ($verbose_exec, "executing \"$_\"");
1571
1572   my $rc = system @_;
1573
1574   if ($rc == 0) {
1575     LOG ($verbose_exec, "subproc exited normally.");
1576   } elsif (($rc & 0xff) == 0) {
1577     $rc >>= 8;
1578     LOG ($verbose_exec, "subproc exited with status $rc.");
1579   } else {
1580     if ($rc & 0x80) {
1581       LOG ($verbose_exec, "subproc dumped core.");
1582       $rc &= ~0x80;
1583     }
1584     LOG ($verbose_exec, "subproc died with signal $rc.");
1585     # die that way ourselves.
1586     kill $rc, $$;
1587   }
1588
1589   return $rc;
1590 }
1591
1592
1593 # Given the URL of a GIF or JPEG image, and the body of that image, writes a
1594 # PPM to the given output file.  Returns the width/height of the image if 
1595 # successful.
1596 #
1597 sub image_to_pnm {
1598   my ($url, $body, $output) = @_;
1599   my ($cmd, $cmd2, $w, $h);
1600
1601   if ((@_ = gif_size ($body))) {
1602     ($w, $h) = @_;
1603     $cmd = "giftopnm";
1604   } elsif ((@_ = jpeg_size ($body))) {
1605     ($w, $h) = @_;
1606     $cmd = "djpeg";
1607   } else {
1608     LOG (($verbose_pbm || $verbose_load),
1609          "not a GIF or JPG" .
1610          (($body =~ m@<(base|html|head|body|script|table|a href)>@i)
1611           ? " (looks like HTML)" : "") .
1612          ": $url");
1613     $suppress_audit = 1;
1614     return ();
1615   }
1616
1617   $cmd2 = "exec $cmd";        # yes, this really is necessary.  if we don't
1618                               # do this, the process doesn't die properly.
1619   if (!$verbose_pbm) {
1620     #
1621     # We get a "giftopnm: got a 'Application Extension' extension"
1622     # warning any time it's an animgif.
1623     #
1624     # Note that "giftopnm: EOF / read error on image data" is not
1625     # always a fatal error -- sometimes the image looks fine anyway.
1626     #
1627     $cmd2 .= " 2>/dev/null";
1628   }
1629
1630   # There exist corrupted GIF and JPEG files that can make giftopnm and
1631   # djpeg lose their minds and go into a loop.  So this gives those programs
1632   # a small timeout -- if they don't complete in time, kill them.
1633   #
1634   my $pid;
1635   @_ = eval {
1636     my $timed_out;
1637
1638     local $SIG{ALRM}  = sub {
1639       LOG ($verbose_pbm,
1640            "timed out ($cvt_timeout) for $cmd on \"$url\" in pid $pid");
1641       kill ('TERM', $pid) if ($pid);
1642       $timed_out = 1;
1643       $body = undef;
1644     };
1645
1646     if (($pid = open(PIPE, "| $cmd2 > $output"))) {
1647       $timed_out = 0;
1648       alarm $cvt_timeout;
1649       print PIPE $body;
1650       $body = undef;
1651       close PIPE;
1652
1653       LOG ($verbose_exec, "awaiting $pid");
1654       waitpid ($pid, 0);
1655       LOG ($verbose_exec, "$pid completed");
1656
1657       my $size = (stat($output))[7];
1658       $size = -1 unless defined($size);
1659       if ($size < 5) {
1660         LOG ($verbose_pbm, "$cmd on ${w}x$h \"$url\" failed ($size bytes)");
1661         return ();
1662       }
1663
1664       LOG ($verbose_pbm, "created ${w}x$h $output ($cmd)");
1665       return ($w, $h);
1666     } else {
1667       print STDERR blurb() . "$cmd failed: $!\n";
1668       return ();
1669     }
1670   };
1671   die if ($@ && $@ ne "alarm\n");       # propagate errors
1672   if ($@) {
1673     # timed out
1674     $body = undef;
1675     return ();
1676   } else {
1677     # didn't
1678     alarm 0;
1679     $body = undef;
1680     return @_;
1681   }
1682 }
1683
1684 sub pick_root_displayer {
1685   my @names = ();
1686
1687   foreach my $cmd (@root_displayers) {
1688     $_ = $cmd;
1689     my ($name) = m/^([^ ]+)/;
1690     push @names, "\"$name\"";
1691     LOG ($verbose_exec, "looking for $name...");
1692     foreach my $dir (split (/:/, $ENV{PATH})) {
1693       LOG ($verbose_exec, "  checking $dir/$name");
1694       return $cmd if (-x "$dir/$name");
1695     }
1696   }
1697
1698   $names[$#names] = "or " . $names[$#names];
1699   error "none of: " . join (", ", @names) . " were found on \$PATH.";
1700 }
1701
1702
1703 my $ppm_to_root_window_cmd = undef;
1704
1705
1706 sub x_or_pbm_output {
1707
1708   # make sure the various programs we execute exist, right up front.
1709   #
1710   foreach ("ppmmake", "giftopnm", "djpeg", "pnmpaste", "pnmscale", "pnmcut") {
1711     which ($_) || error "$_ not found on \$PATH.";
1712   }
1713
1714   # find a root-window displayer program.
1715   #
1716   $ppm_to_root_window_cmd = pick_root_displayer();
1717
1718
1719   $SIG{HUP}  = \&x_cleanup;
1720   $SIG{INT}  = \&x_cleanup;
1721   $SIG{QUIT} = \&x_cleanup;
1722   $SIG{ABRT} = \&x_cleanup;
1723   $SIG{KILL} = \&x_cleanup;
1724   $SIG{TERM} = \&x_cleanup;
1725
1726   # Need this so that if giftopnm dies, we don't die.
1727   $SIG{PIPE} = 'IGNORE';
1728
1729   if (!$img_width || !$img_height) {
1730     $_ = "xdpyinfo";
1731     which ($_) || error "$_ not found on \$PATH.";
1732     $_ = `$_`;
1733     ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
1734     if (!defined($img_height)) {
1735       error "xdpyinfo failed.";
1736     }
1737   }
1738
1739   my $bgcolor = "#000000";
1740   my $bgimage = undef;
1741
1742   if ($background) {
1743     if ($background =~ m/^\#[0-9a-f]+$/i) {
1744       $bgcolor = $background;
1745
1746     } elsif (-r $background) {
1747       $bgimage = $background;
1748
1749     } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
1750       error "not a color or readable file: $background";
1751
1752     } else {
1753       # default to assuming it's a color
1754       $bgcolor = $background;
1755     }
1756   }
1757
1758   # Create the sold-colored base image.
1759   #
1760   $_ = "ppmmake '$bgcolor' $img_width $img_height";
1761   LOG ($verbose_pbm, "creating base image: $_");
1762   nontrapping_system "$_ > $image_ppm";
1763
1764   # Paste the default background image in the middle of it.
1765   #
1766   if ($bgimage) {
1767     my ($iw, $ih);
1768
1769     my $body = "";
1770     local *IMG;
1771     open(IMG, "<$bgimage") || error "couldn't open $bgimage: $!";
1772     my $cmd;
1773     while (<IMG>) { $body .= $_; }
1774     close (IMG);
1775
1776     if ((@_ = gif_size ($body))) {
1777       ($iw, $ih) = @_;
1778       $cmd = "giftopnm |";
1779
1780     } elsif ((@_ = jpeg_size ($body))) {
1781       ($iw, $ih) = @_;
1782       $cmd = "djpeg |";
1783
1784     } elsif ($body =~ m/^P\d\n(\d+) (\d+)\n/) {
1785       $iw = $1;
1786       $ih = $2;
1787       $cmd = "";
1788
1789     } else {
1790       error "$bgimage is not a GIF, JPEG, or PPM.";
1791     }
1792
1793     my $x = int (($img_width  - $iw) / 2);
1794     my $y = int (($img_height - $ih) / 2);
1795     LOG ($verbose_pbm,
1796          "pasting $bgimage (${iw}x$ih) into base image at $x,$y");
1797
1798     $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
1799     open (IMG, "| $cmd") || error "running $cmd: $!";
1800     print IMG $body;
1801     $body = undef;
1802     close (IMG);
1803     LOG ($verbose_exec, "subproc exited normally.");
1804     rename ($image_tmp1, $image_ppm) ||
1805       error "renaming $image_tmp1 to $image_ppm: $!";
1806   }
1807
1808   clearlog();
1809
1810   while (1) {
1811     my ($base, $img) = pick_image();
1812     my $source = $current_state;
1813     $current_state = "loadimage";
1814     if ($img) {
1815       my ($headers, $body) = get_document ($img, $base);
1816       if ($body) {
1817         paste_image ($base, $img, $body, $source);
1818         $body = undef;
1819       }
1820     }
1821     $current_state = "idle";
1822     $load_method = "none";
1823
1824     unlink $image_tmp1, $image_tmp2;
1825     sleep $delay;
1826   }
1827 }
1828
1829 sub paste_image {
1830   my ($base, $img, $body, $source) = @_;
1831
1832   $current_state = "paste";
1833
1834   $suppress_audit = 0;
1835
1836   LOG ($verbose_pbm, "got $img (" . length($body) . ")");
1837
1838   my ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
1839   $body = undef;
1840   if (!$iw || !$ih) {
1841     LOG ($verbose_pbm, "unable to make PBM from $img");
1842     return 0;
1843   }
1844
1845   record_success ($load_method, $img, $base);
1846
1847
1848   my $ow = $iw;  # used only for error messages
1849   my $oh = $ih;
1850
1851   # don't just tack this onto the front of the pipeline -- we want it to
1852   # be able to change the size of the input image.
1853   #
1854   if ($filter_cmd) {
1855     LOG ($verbose_pbm, "running $filter_cmd");
1856
1857     my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
1858     if ($rc != 0) {
1859       LOG(($verbose_pbm || $verbose_load), "failed command: \"$filter_cmd\"");
1860       LOG(($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
1861       return;
1862     }
1863     rename ($image_tmp2, $image_tmp1);
1864
1865     # re-get the width/height in case the filter resized it.
1866     local *IMG;
1867     open(IMG, "<$image_tmp1") || return 0;
1868     $_ = <IMG>;
1869     $_ = <IMG>;
1870     ($iw, $ih) = m/^(\d+) (\d+)$/;
1871     close (IMG);
1872     return 0 unless ($iw && $ih);
1873   }
1874
1875   my $target_w = $img_width;
1876   my $target_h = $img_height;
1877
1878   my $cmd = "";
1879
1880
1881   # Usually scale the image to fit on the screen -- but sometimes scale it
1882   # to fit on half or a quarter of the screen.  Note that we don't merely
1883   # scale it to fit, we instead cut it in half until it fits -- that should
1884   # give a wider distribution of sizes.
1885   #
1886   if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
1887   if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
1888
1889   if ($iw > $target_w || $ih > $target_h) {
1890     while ($iw > $target_w ||
1891            $ih > $target_h) {
1892       $iw = int($iw / 2);
1893       $ih = int($ih / 2);
1894     }
1895     if ($iw <= 10 || $ih <= 10) {
1896       LOG ($verbose_pbm, "scaling to ${iw}x$ih would have been bogus.");
1897       return 0;
1898     }
1899
1900     LOG ($verbose_pbm, "scaling to ${iw}x$ih");
1901
1902     $cmd .= " | pnmscale -xsize $iw -ysize $ih";
1903   }
1904
1905
1906   my $src = $image_tmp1;
1907
1908   my $crop_x = 0;     # the sub-rectangle of the image
1909   my $crop_y = 0;     # that we will actually paste.
1910   my $crop_w = $iw;
1911   my $crop_h = $ih;
1912
1913   # The chance that we will randomly crop out a section of an image starts
1914   # out fairly low, but goes up for images that are very large, or images
1915   # that have ratios that make them look like banners (we try to avoid
1916   # banner images entirely, but they slip through when the IMG tags didn't
1917   # have WIDTH and HEIGHT specified.)
1918   #
1919   my $crop_chance = 0.2;
1920   if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
1921     $crop_chance += 0.2;
1922   }
1923   if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
1924     $crop_chance += 0.2;
1925   }
1926   if ($min_ratio && ($iw * $min_ratio) > $ih) {
1927     $crop_chance += 0.7;
1928   }
1929
1930   if ($crop_chance > 0.1) {
1931     LOG ($verbose_pbm, "crop chance: $crop_chance");
1932   }
1933
1934   if (rand() < $crop_chance) {
1935     
1936     my $ow = $crop_w;
1937     my $oh = $crop_h;
1938     
1939     if ($crop_w > $min_width) {
1940       # if it's a banner, select the width linearly.
1941       # otherwise, select a bell.
1942       my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
1943                ? rand()
1944                : bellrand());
1945       $crop_w = $min_width + int ($r * ($crop_w - $min_width));
1946       $crop_x = int (rand() * ($ow - $crop_w));
1947     }
1948     if ($crop_h > $min_height) {
1949       # height always selects as a bell.
1950       $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
1951       $crop_y = int (rand() * ($oh - $crop_h));
1952     }
1953     
1954     if ($crop_x != 0   || $crop_y != 0 ||
1955         $crop_w != $iw || $crop_h != $ih) {
1956       LOG ($verbose_pbm,
1957            "randomly cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
1958     }
1959   }
1960
1961   # Where the image should logically land -- this might be negative.
1962   #
1963   my $x = int((rand() * ($img_width  + $crop_w/2)) - $crop_w*3/4);
1964   my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
1965
1966   # if we have chosen to paste the image outside of the rectangle of the
1967   # screen, then we need to crop it.
1968   #
1969   if ($x < 0 ||
1970       $y < 0 ||
1971       $x + $crop_w > $img_width ||
1972       $y + $crop_h > $img_height) {
1973     
1974     LOG ($verbose_pbm,
1975          "cropping for effective paste of ${crop_w}x$crop_h \@ $x,$y");
1976     
1977     if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
1978     if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
1979     
1980     if ($x + $crop_w >= $img_width)  { $crop_w = $img_width  - $x - 1; }
1981     if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
1982   }
1983
1984   # If any cropping needs to happen, add pnmcut.
1985   #
1986   if ($crop_x != 0   || $crop_y != 0 ||
1987         $crop_w != $iw || $crop_h != $ih) {
1988     $iw = $crop_w;
1989     $ih = $crop_h;
1990     $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
1991     LOG ($verbose_pbm, "cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
1992   }
1993
1994   LOG ($verbose_pbm, "pasting ${iw}x$ih \@ $x,$y in $image_ppm");
1995
1996   $cmd .= " | pnmpaste - $x $y $image_ppm";
1997
1998   $cmd =~ s@^ *\| *@@;
1999
2000   $_ = "($cmd)";
2001   $_ .= " < $image_tmp1 > $image_tmp2";
2002
2003   if ($verbose_pbm) {
2004     $_ = "($_) 2>&1 | sed s'/^/" . blurb() . "/'";
2005   } else {
2006     $_ .= " 2> /dev/null";
2007   }
2008   my $rc = nontrapping_system ($_);
2009
2010   if ($rc != 0) {
2011     LOG (($verbose_pbm || $verbose_load), "failed command: \"$cmd\"");
2012     LOG (($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
2013     return;
2014   }
2015
2016   rename ($image_tmp2, $image_ppm) || return;
2017
2018   my $target = "$image_ppm";
2019
2020   # don't just tack this onto the end of the pipeline -- we don't want it
2021   # to end up in $image_ppm, because we don't want the results to be
2022   # cumulative.
2023   #
2024   if ($post_filter_cmd) {
2025     $target = $image_tmp1;
2026     $rc = nontrapping_system "($post_filter_cmd) < $image_ppm > $target";
2027     if ($rc != 0) {
2028       LOG ($verbose_pbm, "filter failed: \"$post_filter_cmd\"\n");
2029       return;
2030     }
2031   }
2032
2033   if (!$no_output_p) {
2034     my $tsize = (stat($target))[7];
2035     if ($tsize > 200) {
2036       $cmd = "$ppm_to_root_window_cmd $target";
2037       
2038       # xv seems to hate being killed.  it tends to forget to clean
2039       # up after itself, and leaves windows around and colors allocated.
2040       # I had this same problem with vidwhacker, and I'm not entirely
2041       # sure what I did to fix it.  But, let's try this: launch xv
2042       # in the background, so that killing this process doesn't kill it.
2043       # it will die of its own accord soon enough.  So this means we
2044       # start pumping bits to the root window in parallel with starting
2045       # the next network retrieval, which is probably a better thing
2046       # to do anyway.
2047       #
2048       $cmd .= " &";
2049       
2050       $rc = nontrapping_system ($cmd);
2051       
2052       if ($rc != 0) {
2053         LOG (($verbose_pbm || $verbose_load), "display failed: \"$cmd\"");
2054         return;
2055       }
2056       
2057     } else {
2058       LOG ($verbose_pbm, "$target size is $tsize");
2059     }
2060   }
2061
2062   $source .= "-" . stats_of($source);
2063   print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n"
2064     if ($verbose_imgmap);
2065
2066   clearlog();
2067
2068   return 1;
2069 }
2070
2071
2072 sub main {
2073   $| = 1;
2074   srand(time ^ $$);
2075
2076   my $verbose = 0;
2077
2078   $current_state = "init";
2079   $load_method = "none";
2080
2081   my $root_p = 0;
2082
2083   # historical suckage: the environment variable name is lower case.
2084   $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
2085
2086   while ($_ = $ARGV[0]) {
2087     shift @ARGV;
2088     if ($_ eq "-display" ||
2089         $_ eq "-displ" ||
2090         $_ eq "-disp" ||
2091         $_ eq "-dis" ||
2092         $_ eq "-dpy" ||
2093         $_ eq "-d") {
2094       $ENV{DISPLAY} = shift @ARGV;
2095     } elsif ($_ eq "-root") {
2096       $root_p = 1;
2097     } elsif ($_ eq "-no-output") {
2098       $no_output_p = 1;
2099     } elsif ($_ eq "-urls-only") {
2100       $urls_only_p = 1;
2101       $no_output_p = 1;
2102     } elsif ($_ eq "-verbose") {
2103       $verbose++;
2104     } elsif (m/^-v+$/) {
2105       $verbose += length($_)-1;
2106     } elsif ($_ eq "-delay") {
2107       $delay = shift @ARGV;
2108     } elsif ($_ eq "-timeout") {
2109       $http_timeout = shift @ARGV;
2110     } elsif ($_ eq "-filter") {
2111       $filter_cmd = shift @ARGV;
2112     } elsif ($_ eq "-filter2") {
2113       $post_filter_cmd = shift @ARGV;
2114     } elsif ($_ eq "-background" || $_ eq "-bg") {
2115       $background = shift @ARGV;
2116     } elsif ($_ eq "-size") {
2117       $_ = shift @ARGV;
2118       if (m@^(\d+)x(\d+)$@) {
2119         $img_width = $1;
2120         $img_height = $2;
2121       } else {
2122         error "argument to \"-size\" must be of the form \"640x400\"";
2123       }
2124     } elsif ($_ eq "-proxy" || $_ eq "-http-proxy") {
2125       $http_proxy = shift @ARGV;
2126     } else {
2127       print STDERR "$copyright\nusage: $progname [-root]" .
2128                  " [-display dpy] [-root] [-verbose] [-timeout secs]\n" .
2129                  "\t\t  [-delay secs] [-filter cmd] [-filter2 cmd]\n" .
2130                  "\t\t  [-http-proxy host[:port]]\n";
2131       exit 1;
2132     }
2133   }
2134
2135   if ($http_proxy && $http_proxy eq "") {
2136     $http_proxy = undef;
2137   }
2138   if ($http_proxy && $http_proxy =~ m@^http://([^/]*)/?$@ ) {
2139     # historical suckage: allow "http://host:port" as well as "host:port".
2140     $http_proxy = $1;
2141   }
2142
2143   if (!$root_p && !$no_output_p) {
2144     print STDERR $copyright;
2145     error "the -root argument is mandatory (for now.)";
2146   }
2147
2148   if (!$no_output_p && !$ENV{DISPLAY}) {
2149     error "\$DISPLAY is not set.";
2150   }
2151
2152
2153   if ($verbose == 1) {
2154     $verbose_imgmap   = 1;
2155     $verbose_warnings = 1;
2156
2157   } elsif ($verbose == 2) {
2158     $verbose_imgmap   = 1;
2159     $verbose_warnings = 1;
2160     $verbose_load     = 1;
2161
2162   } elsif ($verbose == 3) {
2163     $verbose_imgmap   = 1;
2164     $verbose_warnings = 1;
2165     $verbose_load     = 1;
2166     $verbose_filter   = 1;
2167
2168   } elsif ($verbose == 4) {
2169     $verbose_imgmap   = 1;
2170     $verbose_warnings = 1;
2171     $verbose_load     = 1;
2172     $verbose_filter   = 1;
2173     $verbose_net      = 1;
2174
2175   } elsif ($verbose == 5) {
2176     $verbose_imgmap   = 1;
2177     $verbose_warnings = 1;
2178     $verbose_load     = 1;
2179     $verbose_filter   = 1;
2180     $verbose_net      = 1;
2181     $verbose_pbm      = 1;
2182
2183   } elsif ($verbose == 6) {
2184     $verbose_imgmap   = 1;
2185     $verbose_warnings = 1;
2186     $verbose_load     = 1;
2187     $verbose_filter   = 1;
2188     $verbose_net      = 1;
2189     $verbose_pbm      = 1;
2190     $verbose_http     = 1;
2191
2192   } elsif ($verbose >= 7) {
2193     $verbose_imgmap   = 1;
2194     $verbose_warnings = 1;
2195     $verbose_load     = 1;
2196     $verbose_filter   = 1;
2197     $verbose_net      = 1;
2198     $verbose_pbm      = 1;
2199     $verbose_http     = 1;
2200     $verbose_exec     = 1;
2201   }
2202
2203
2204   if ($urls_only_p) {
2205     url_only_output;
2206   } else {
2207     x_or_pbm_output;
2208   }
2209 }
2210
2211 main;
2212 exit (0);