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