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