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