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