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