http://nanonyme.dy.fi/mirrors/hvl/distfiles/xscreensaver/xscreensaver-5.03.tar.gz
[xscreensaver] / hacks / webcollage
1 #!/usr/bin/perl -w
2 #
3 # webcollage, Copyright (c) 1999-2005 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.135 $ }; $version =~ s/^[^0-9]+([0-9.]+).*$/$1/;
64 my $copyright = "WebCollage $version, Copyright (c) 1999-2005" .
65     " Jamie Zawinski <jwz\@jwz.org>\n" .
66     "            http://www.jwz.org/webcollage/\n";
67
68
69
70 my @search_methods = (  56, "altavista",    \&pick_from_alta_vista_random_link,
71                         11, "livejournal",  \&pick_from_livejournal_images,
72                          5, "yahoorand",    \&pick_from_yahoo_random_link,
73                         10, "googlephotos", \&pick_from_google_image_photos,
74                          5, "googleimgs",   \&pick_from_google_images,
75                          3, "googlenums",   \&pick_from_google_image_numbers,
76                          2, "flickr_recent", \&pick_from_flickr_recent,
77                          8, "flickr_random", \&pick_from_flickr_random,
78
79                      # In Apr 2002, Google asked me to stop searching them.
80                      # I asked them to add a "random link" url.  They said
81                      # "that would be easy, we'll think about it" and then
82                      # never wrote back.  Booo Google!  Booooo!  So, screw
83                      # those turkeys, I've turned Google searching back on.
84                      # I'm sure they can take it.  (Jan 2005.)
85
86                      # Jan 2005: Yahoo fucked up their search form so that
87                      # it's no longer possible to do "or" searches on news
88                      # images, so we rarely get any hits there any more.
89                      # 
90                      #  0, "yahoonews",   \&pick_from_yahoo_news_text,
91
92                      # Dec 2004: the ircimages guy's server can't take the
93                      # heat, so he started banning the webcollage user agent.
94                      # I tried to convince him to add a lighter-weight page to
95                      # support webcollage better, but he doesn't care.
96                      #
97                      #  0, "ircimages", \&pick_from_ircimages,
98
99                      # Dec 2002: Alta Vista has a new "random link" URL now.
100                      # They added it specifically to better support webcollage!
101                      # That was super cool of them.  This is how we used to do
102                      # it, before:
103                      #
104                      #  0, "avimages", \&pick_from_alta_vista_images,
105                      #  0, "avtext",   \&pick_from_alta_vista_text,
106
107                      # This broke in 2004.  Eh, Lycos sucks anyway.
108                      #
109                      #   0, "lycos",      \&pick_from_lycos_text,
110
111                      # This broke in 2003, I think.  I suspect Hotbot is
112                      # actually the same search engine data as Lycos.
113                      #
114                      #  0, "hotbot",     \&pick_from_hotbot_text,
115                       );
116
117 # programs we can use to write to the root window (tried in ascending order.)
118 #
119 my @root_displayers = (
120   "xscreensaver-getimage -root -file",
121   "chbg       -once -xscreensaver -max_size 100",
122   "xv         -root -quit -viewonly +noresetroot -quick24 -rmode 5" .
123   "           -rfg black -rbg black",
124   "xli        -quiet -onroot -center -border black",
125   "xloadimage -quiet -onroot -center -border black",
126
127 # this lame program wasn't built with vroot.h:
128 # "xsri       -scale -keep-aspect -center-horizontal -center-vertical",
129 );
130
131
132 # Some sites need cookies to work properly.   These are they.
133 #
134 my %cookies = (
135   "www.altavista.com"  =>  "AV_ALL=1",   # request uncensored searches
136   "web.altavista.com"  =>  "AV_ALL=1",
137
138                                          # log in as "cipherpunk"
139   "www.nytimes.com"    =>  'NYT-S=18cHMIlJOn2Y1bu5xvEG3Ufuk6E1oJ.' .
140                            'FMxWaQV0igaB5Yi/Q/guDnLeoL.pe7i1oakSb' .
141                            '/VqfdUdb2Uo27Vzt1jmPn3cpYRlTw9',
142
143   "ircimages.com"      =>  'disclaimer=1',
144 );
145
146
147 # If this is set, it's a helper program to use for pasting images together:
148 # this is a lot faster and more efficient than using PPM pipelines, which is
149 # what we do if this program doesn't exist.  (We check for "webcollage-helper"
150 # on $PATH at startup, and set this variable appropriately.)
151 #
152 my $webcollage_helper = undef;
153
154
155 # If we have the webcollage-helper program, then it will paste the images
156 # together with transparency!  0.0 is invisible, 1.0 is totally opaque.
157 #
158 my $opacity = 0.85;
159
160
161 # Some sites have  managed to poison the search engines.  These are they.
162 # (We auto-detect sites that have poisoned the search engines via excessive
163 # keywords or dictionary words,  but these are ones that slip through
164 # anyway.)
165 #
166 # This can contain full host names, or 2 or 3 component domains.
167 #
168 my %poisoners = (
169   "die.net"                 => 1,  # 'l33t h4ck3r d00dz.
170   "genforum.genealogy.com"  => 1,  # Cluttering avtext with human names.
171   "rootsweb.com"            => 1,  # Cluttering avtext with human names.
172   "akamai.net"              => 1,  # Lots of sites have their images on Akamai.
173   "akamaitech.net"          => 1,  # But those are pretty much all banners.
174                                    # Since Akamai is super-expensive, let's
175                                    # go out on a limb and assume that all of
176                                    # their customers are rich-and-boring.
177   "bartleby.com"            => 1,  # Dictionary, cluttering avtext.
178   "encyclopedia.com"        => 1,  # Dictionary, cluttering avtext.
179   "onlinedictionary.datasegment.com" => 1,  # Dictionary, cluttering avtext.
180   "hotlinkpics.com"         => 1,  # Porn site that has poisoned avimages
181                                    # (I don't see how they did it, though!)
182   "alwayshotels.com"        => 1,  # Poisoned Lycos pretty heavily.
183   "nextag.com"              => 1,  # Poisoned Alta Vista real good.
184 );
185
186
187 # When verbosity is turned on, we warn about sites that we seem to be hitting
188 # a lot: usually this means some new poisoner has made it into the search
189 # engines.  But sometimes, the warning is just because that site has a lot
190 # of stuff on it.  So these are the sites that are immune to the "frequent
191 # site" diagnostic message.
192 #
193 my %warningless_sites = (
194   "home.earthlink.net"      => 1,  # Lots of home pages here.
195   "www.geocities.com"       => 1,
196   "www.angelfire.com"       => 1,
197   "members.aol.com"         => 1,
198   "img.photobucket.com"     => 1,
199   "pics.livejournal.com"    => 1,
200   "tinypic.com"             => 1,
201   "flickr.com"              => 1,
202
203   "yimg.com"                => 1,  # This is where dailynews.yahoo.com stores
204   "eimg.com"                => 1,  # its images, so pick_from_yahoo_news_text()
205                                    # hits this every time.
206
207   "images.quizfarm.com"     => 1,  # damn those LJ quizzes...
208   "images.quizilla.com"     => 1,
209   "images.quizdiva.net"     => 1,
210
211   "driftnet"                => 1,  # builtin...
212   "local-directory"         => 1,  # builtin...
213 );
214
215
216 # For decoding HTML-encoded character entities to URLs.
217 #
218 my %entity_table = (
219    "apos"   => '\'',
220    "quot"   => '"', "amp"    => '&', "lt"     => '<', "gt"     => '>',
221    "nbsp"   => ' ', "iexcl"  => '¡', "cent"   => '¢', "pound"  => '£',
222    "curren" => '¤', "yen"    => '¥', "brvbar" => '¦', "sect"   => '§',
223    "uml"    => '¨', "copy"   => '©', "ordf"   => 'ª', "laquo"  => '«',
224    "not"    => '¬', "shy"    => '­', "reg"    => '®', "macr"   => '¯',
225    "deg"    => '°', "plusmn" => '±', "sup2"   => '²', "sup3"   => '³',
226    "acute"  => '´', "micro"  => 'µ', "para"   => '¶', "middot" => '·',
227    "cedil"  => '¸', "sup1"   => '¹', "ordm"   => 'º', "raquo"  => '»',
228    "frac14" => '¼', "frac12" => '½', "frac34" => '¾', "iquest" => '¿',
229    "Agrave" => 'À', "Aacute" => 'Á', "Acirc"  => 'Â', "Atilde" => 'Ã',
230    "Auml"   => 'Ä', "Aring"  => 'Å', "AElig"  => 'Æ', "Ccedil" => 'Ç',
231    "Egrave" => 'È', "Eacute" => 'É', "Ecirc"  => 'Ê', "Euml"   => 'Ë',
232    "Igrave" => 'Ì', "Iacute" => 'Í', "Icirc"  => 'Î', "Iuml"   => 'Ï',
233    "ETH"    => 'Ð', "Ntilde" => 'Ñ', "Ograve" => 'Ò', "Oacute" => 'Ó',
234    "Ocirc"  => 'Ô', "Otilde" => 'Õ', "Ouml"   => 'Ö', "times"  => '×',
235    "Oslash" => 'Ø', "Ugrave" => 'Ù', "Uacute" => 'Ú', "Ucirc"  => 'Û',
236    "Uuml"   => 'Ü', "Yacute" => 'Ý', "THORN"  => 'Þ', "szlig"  => 'ß',
237    "agrave" => 'à', "aacute" => 'á', "acirc"  => 'â', "atilde" => 'ã',
238    "auml"   => 'ä', "aring"  => 'å', "aelig"  => 'æ', "ccedil" => 'ç',
239    "egrave" => 'è', "eacute" => 'é', "ecirc"  => 'ê', "euml"   => 'ë',
240    "igrave" => 'ì', "iacute" => 'í', "icirc"  => 'î', "iuml"   => 'ï',
241    "eth"    => 'ð', "ntilde" => 'ñ', "ograve" => 'ò', "oacute" => 'ó',
242    "ocirc"  => 'ô', "otilde" => 'õ', "ouml"   => 'ö', "divide" => '÷',
243    "oslash" => 'ø', "ugrave" => 'ù', "uacute" => 'ú', "ucirc"  => 'û',
244    "uuml"   => 'ü', "yacute" => 'ý', "thorn"  => 'þ', "yuml"   => 'ÿ',
245    "ndash"  => '-', "mdash"  => "--"
246 );
247
248
249 ##############################################################################
250 #
251 # Various global flags set by command line parameters, or computed
252 #
253 ##############################################################################
254
255
256 my $current_state = "???";      # for diagnostics
257 my $load_method;
258 my $last_search;
259 my $image_succeeded = -1;
260 my $suppress_audit = 0;
261
262 my $verbose_imgmap = 0;         # print out rectangles and URLs only (stdout)
263 my $verbose_warnings = 0;       # print out warnings when things go wrong
264 my $verbose_load = 0;           # diagnostics about loading of URLs
265 my $verbose_filter = 0;         # diagnostics about page selection/rejection
266 my $verbose_net = 0;            # diagnostics about network I/O
267 my $verbose_pbm = 0;            # diagnostics about PBM pipelines
268 my $verbose_http = 0;           # diagnostics about all HTTP activity
269 my $verbose_exec = 0;           # diagnostics about executing programs
270
271 my $report_performance_interval = 60 * 15;  # print some stats every 15 minutes
272
273 my $http_proxy = undef;
274 my $http_timeout = 20;
275 my $cvt_timeout = 10;
276
277 my $min_width = 50;
278 my $min_height = 50;
279 my $min_ratio = 1/5;
280
281 my $min_gif_area = (120 * 120);
282
283
284 my $no_output_p = 0;
285 my $urls_only_p = 0;
286 my $cocoa_p = 0;
287 my $imagemap_base = undef;
288
289 my @pids_to_kill = ();  # forked pids we should kill when we exit, if any.
290
291 my $driftnet_magic = 'driftnet';
292 my $driftnet_dir = undef;
293 my $default_driftnet_cmd = "driftnet -a -m 100";
294
295 my $local_magic = 'local-directory';
296 my $local_dir = undef;
297
298 my $wordlist;
299
300 my %rejected_urls;
301 my @tripwire_words = ("aberrate", "abode", "amorphous", "antioch",
302                       "arrhenius", "arteriole", "blanket", "brainchild",
303                       "burdensome", "carnival", "cherub", "chord", "clever",
304                       "dedicate", "dilogarithm", "dolan", "dryden",
305                       "eggplant");
306
307
308 ##############################################################################
309 #
310 # Retrieving URLs
311 #
312 ##############################################################################
313
314 # returns three values: the HTTP response line; the document headers;
315 # and the document body.
316 #
317 sub get_document_1($$$) {
318   my ($url, $referer, $timeout) = @_;
319
320   if (!defined($timeout)) { $timeout = $http_timeout; }
321   if ($timeout > $http_timeout) { $timeout = $http_timeout; }
322
323   if ($timeout <= 0) {
324     LOG (($verbose_net || $verbose_load), "timed out for $url");
325     return ();
326   }
327
328   LOG ($verbose_net, "get_document_1 $url " . ($referer ? $referer : ""));
329
330   if (! ($url =~ m@^http://@i)) {
331     LOG ($verbose_net, "not an HTTP URL: $url");
332     return ();
333   }
334
335   my ($url_proto, $dummy, $serverstring, $path) = split(/\//, $url, 4);
336   $path = "" unless $path;
337
338   if (!$url_proto || !$serverstring) {
339     LOG (($verbose_net || $verbose_load), "unparsable URL: $url");
340     return ();
341   }
342
343   my ($them,$port) = split(/:/, $serverstring);
344   $port = 80 unless $port;
345
346   my $them2 = $them;
347   my $port2 = $port;
348   if ($http_proxy) {
349     $serverstring = $http_proxy if $http_proxy;
350     $serverstring =~ s@^[a-z]+://@@;
351     ($them2,$port2) = split(/:/, $serverstring);
352     $port2 = 80 unless $port2;
353   }
354
355   my ($remote, $iaddr, $paddr, $proto, $line);
356   $remote = $them2;
357   if ($port2 =~ /\D/) { $port2 = getservbyname($port2, 'tcp') }
358   if (!$port2) {
359     LOG (($verbose_net || $verbose_load), "unrecognised port in $url");
360     return ();
361   }
362   $iaddr   = inet_aton($remote);
363   if (!$iaddr) {
364     LOG (($verbose_net || $verbose_load), "host not found: $remote");
365     return ();
366   }
367   $paddr   = sockaddr_in($port2, $iaddr);
368
369
370   my $head = "";
371   my $body = "";
372
373   @_ =
374     eval {
375       local $SIG{ALRM} = sub {
376         LOG (($verbose_net || $verbose_load), "timed out ($timeout) for $url");
377         die "alarm\n";
378       };
379       alarm $timeout;
380
381       $proto   = getprotobyname('tcp');
382       if (!socket(S, PF_INET, SOCK_STREAM, $proto)) {
383         LOG (($verbose_net || $verbose_load), "socket: $!");
384         return ();
385       }
386       if (!connect(S, $paddr)) {
387         LOG (($verbose_net || $verbose_load), "connect($serverstring): $!");
388         return ();
389       }
390
391       select(S); $| = 1; select(STDOUT);
392
393       my $cookie = $cookies{$them};
394
395       my $user_agent = "$progname/$version";
396
397       if ($url =~ m@^http://www\.altavista\.com/@ ||
398           $url =~ m@^http://random\.yahoo\.com/@ ||
399           $url =~ m@^http://images\.google\.com/@) {
400         # block this, you turkeys.
401         $user_agent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.5)" .
402           " Gecko/20041111 Firefox/1.0";
403
404         # 28-Jun-2007: Google Images now emits the entire page in JS if
405         # you claim to be Gecko.  They also still block "webcollage".
406         # They serve non-JS for unrecognised agents, so let's try this...
407         $user_agent = "NoJavascriptPlease/1.0"
408           if ($url =~ m@^http://images\.google\.com/@);
409       }
410
411       my $hdrs = "GET " . ($http_proxy ? $url : "/$path") . " HTTP/1.0\r\n" .
412                  "Host: $them\r\n" .
413                  "User-Agent: $user_agent\r\n";
414       if ($referer) {
415         $hdrs .= "Referer: $referer\r\n";
416       }
417       if ($cookie) {
418         my @cc = split(/\r?\n/, $cookie);
419         $hdrs .= "Cookie: " . join('; ', @cc) . "\r\n";
420       }
421       $hdrs .= "\r\n";
422
423       foreach (split('\r?\n', $hdrs)) {
424         LOG ($verbose_http, "  ==> $_");
425       }
426       print S $hdrs;
427       my $http = <S> || "";
428
429       # Kludge: the Yahoo Random Link is now returning as its first
430       # line "Status: 301" instead of "HTTP/1.0 301 Found".  Fix it...
431       #
432       $http =~ s@^Status:\s+(\d+)\b@HTTP/1.0 $1@i;
433
434       $_  = $http;
435       s/[\r\n]+$//s;
436       LOG ($verbose_http, "  <== $_");
437
438       while (<S>) {
439         $head .= $_;
440         s/[\r\n]+$//s;
441         last if m@^$@;
442         LOG ($verbose_http, "  <== $_");
443
444         if (m@^Set-cookie:\s*([^;\r\n]+)@i) {
445           set_cookie($them, $1)
446         }
447       }
448
449       my $lines = 0;
450       while (<S>) {
451         $body .= $_;
452         $lines++;
453       }
454
455       LOG ($verbose_http,
456            "  <== [ body ]: $lines lines, " . length($body) . " bytes");
457
458       close S;
459
460       if (!$http) {
461         LOG (($verbose_net || $verbose_load), "null response: $url");
462         return ();
463       }
464
465       $SIG{ALRM} = 'DEFAULT';  # seem to be suffering a race?
466       return ( $http, $head, $body );
467     };
468   die if ($@ && $@ ne "alarm\n");       # propagate errors
469
470   if ($@ && $@ ne "alarm\n") {
471     print STDERR blurb() . "DIE " . join(" ", $@) . "\n";
472     die;
473   }
474
475   if ($@) {
476     # timed out
477     $head = undef;
478     $body = undef;
479     $suppress_audit = 1;
480     return ();
481   } else {
482     # didn't
483     alarm 0;
484     return @_;
485   }
486 }
487
488
489 # returns two values: the document headers; and the document body.
490 # if the given URL did a redirect, returns the redirected-to document.
491 #
492 sub get_document($$;$) {
493   my ($url, $referer, $timeout) = @_;
494   my $start = time;
495
496   if (defined($referer) && $referer eq $driftnet_magic) {
497     return get_driftnet_file ($url);
498   }
499
500   if (defined($referer) && $referer eq $local_magic) {
501     return get_local_file ($url);
502   }
503
504   my $orig_url = $url;
505   my $loop_count = 0;
506   my $max_loop_count = 4;
507
508   do {
509     if (defined($timeout) && $timeout <= 0) {
510       LOG (($verbose_net || $verbose_load), "timed out for $url");
511       $suppress_audit = 1;
512       return ();
513     }
514
515     my ( $http, $head, $body ) = get_document_1 ($url, $referer, $timeout);
516
517     if (defined ($timeout)) {
518       my $now = time;
519       my $elapsed = $now - $start;
520       $timeout -= $elapsed;
521       $start = $now;
522     }
523
524     return () unless $http; # error message already printed
525
526     $http =~ s/[\r\n]+$//s;
527
528     if ( $http =~ m@^HTTP/[0-9.]+ 30[123]@ ) {
529       $_ = $head;
530
531       my ( $location ) = m@^location:[ \t]*(.*)$@im;
532       if ( $location ) {
533         $location =~ s/[\r\n]$//;
534
535         LOG ($verbose_net, "redirect from $url to $location");
536         $referer = $url;
537         $url = $location;
538
539         if ($url =~ m@^/@) {
540           $referer =~ m@^(http://[^/]+)@i;
541           $url = $1 . $url;
542         } elsif (! ($url =~ m@^[a-z]+:@i)) {
543           $_ = $referer;
544           s@[^/]+$@@g if m@^http://[^/]+/@i;
545           $_ .= "/" if m@^http://[^/]+$@i;
546           $url = $_ . $url;
547         }
548
549       } else {
550         LOG ($verbose_net, "no Location with \"$http\"");
551         return ( $url, $body );
552       }
553
554       if ($loop_count++ > $max_loop_count) {
555         LOG ($verbose_net,
556              "too many redirects ($max_loop_count) from $orig_url");
557         $body = undef;
558         return ();
559       }
560
561     } elsif ( $http =~ m@^HTTP/[0-9.]+ ([4-9][0-9][0-9].*)$@ ) {
562
563       LOG (($verbose_net || $verbose_load), "failed: $1 ($url)");
564
565       # http errors -- return nothing.
566       $body = undef;
567       return ();
568
569     } elsif (!$body) {
570
571       LOG (($verbose_net || $verbose_load), "document contains no data: $url");
572       return ();
573
574     } else {
575
576       # ok!
577       return ( $url, $body );
578     }
579
580   } while (1);
581 }
582
583 # If we already have a cookie defined for this site, and the site is trying
584 # to overwrite that very same cookie, let it do so.  This is because nytimes
585 # expires its cookies - it lets you upgrade to a new cookie without logging
586 # in again, but you have to present the old cookie to get the new cookie.
587 # So, by doing this, the built-in cypherpunks cookie will never go "stale".
588 #
589 sub set_cookie($$) {
590   my ($host, $cookie) = @_;
591   my $oc = $cookies{$host};
592   return unless $oc;
593   $_ = $oc;
594   my ($oc_name, $oc_value) = m@^([^= \t\r\n]+)=(.*)$@;
595   $_ = $cookie;
596   my ($nc_name, $nc_value) = m@^([^= \t\r\n]+)=(.*)$@;
597
598   if ($oc_name eq $nc_name &&
599       $oc_value ne $nc_value) {
600     $cookies{$host} = $cookie;
601     LOG ($verbose_net, "overwrote ${host}'s $oc_name cookie");
602   }
603 }
604
605
606 ############################################################################
607 #
608 # Extracting image URLs from HTML
609 #
610 ############################################################################
611
612 # given a URL and the body text at that URL, selects and returns a random
613 # image from it.  returns () if no suitable images found.
614 #
615 sub pick_image_from_body($$) {
616   my ($url, $body) = @_;
617
618   my $base = $url;
619   $_ = $url;
620
621   # if there's at least one slash after the host, take off the last
622   # pathname component
623   if ( m@^http://[^/]+/@io ) {
624     $base =~ s@[^/]+$@@go;
625   }
626
627   # if there are no slashes after the host at all, put one on the end.
628   if ( m@^http://[^/]+$@io ) {
629     $base .= "/";
630   }
631
632   $_ = $body;
633
634   # strip out newlines, compress whitespace
635   s/[\r\n\t ]+/ /go;
636
637   # nuke comments
638   s/<!--.*?-->//go;
639
640
641   # There are certain web sites that list huge numbers of dictionary
642   # words in their bodies or in their <META NAME=KEYWORDS> tags (surprise!
643   # Porn sites tend not to be reputable!)
644   #
645   # I do not want webcollage to filter on content: I want it to select
646   # randomly from the set of images on the web.  All the logic here for
647   # rejecting some images is really a set of heuristics for rejecting
648   # images that are not really images: for rejecting *text* that is in
649   # GIF/JPEG/PNG form.  I don't want text, I want pictures, and I want
650   # the content of the pictures to be randomly selected from among all
651   # the available content.
652   #
653   # So, filtering out "dirty" pictures by looking for "dirty" keywords
654   # would be wrong: dirty pictures exist, like it or not, so webcollage
655   # should be able to select them.
656   #
657   # However, picking a random URL is a hard thing to do.  The mechanism I'm
658   # using is to search for a selection of random words.  This is not
659   # perfect, but works ok most of the time.  The way it breaks down is when
660   # some URLs get precedence because their pages list *every word* as
661   # related -- those URLs come up more often than others.
662   #
663   # So, after we've retrieved a URL, if it has too many keywords, reject
664   # it.  We reject it not on the basis of what those keywords are, but on
665   # the basis that by having so many, the page has gotten an unfair
666   # advantage against our randomizer.
667   #
668   my $trip_count = 0;
669   foreach my $trip (@tripwire_words) {
670     $trip_count++ if m/$trip/i;
671   }
672
673   if ($trip_count >= $#tripwire_words - 2) {
674     LOG (($verbose_filter || $verbose_load),
675          "there is probably a dictionary in \"$url\": rejecting.");
676     $rejected_urls{$url} = -1;
677     $body = undef;
678     $_ = undef;
679     return ();
680   }
681
682
683   my @urls;
684   my %unique_urls;
685
686   foreach (split(/ *</)) {
687     if ( m/^meta /i ) {
688
689       # Likewise, reject any web pages that have a KEYWORDS meta tag
690       # that is too long.
691       #
692       if (m/name ?= ?\"?keywords\"?/i &&
693           m/content ?= ?\"([^\"]+)\"/) {
694         my $L = length($1);
695         if ($L > 1000) {
696           LOG (($verbose_filter || $verbose_load),
697                "excessive keywords ($L bytes) in $url: rejecting.");
698           $rejected_urls{$url} = $L;
699           $body = undef;
700           $_ = undef;
701           return ();
702         } else {
703           LOG ($verbose_filter, "  keywords ($L bytes) in $url (ok)");
704         }
705       }
706
707     } elsif ( m/^(img|a) .*(src|href) ?= ?\"? ?(.*?)[ >\"]/io ) {
708
709       my $was_inline = (! ( "$1" eq "a" || "$1" eq "A" ));
710       my $link = $3;
711       my ( $width )  = m/width ?=[ \"]*(\d+)/oi;
712       my ( $height ) = m/height ?=[ \"]*(\d+)/oi;
713       $_ = $link;
714
715       if ( m@^/@o ) {
716         my $site;
717         ( $site = $base ) =~ s@^(http://[^/]*).*@$1@gio;
718         $_ = "$site$link";
719       } elsif ( ! m@^[^/:?]+:@ ) {
720         $_ = "$base$link";
721         s@/\./@/@g;
722         1 while (s@/[^/]+/\.\./@/@g);
723       }
724
725       # skip non-http
726       if ( ! m@^http://@io ) {
727         next;
728       }
729
730       # skip non-image
731       if ( ! m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@io ) {
732         next;
733       }
734
735       # skip really short or really narrow images
736       if ( $width && $width < $min_width) {
737         if (!$height) { $height = "?"; }
738         LOG ($verbose_filter, "  skip narrow image $_ (${width}x$height)");
739         next;
740       }
741
742       if ( $height && $height < $min_height) {
743         if (!$width) { $width = "?"; }
744         LOG ($verbose_filter, "  skip short image $_ (${width}x$height)");
745         next;
746       }
747
748       # skip images with ratios that make them look like banners.
749       if ($min_ratio && $width && $height &&
750           ($width * $min_ratio ) > $height) {
751         if (!$height) { $height = "?"; }
752         LOG ($verbose_filter, "  skip bad ratio $_ (${width}x$height)");
753         next;
754       }
755
756       # skip GIFs with a small number of pixels -- those usually suck.
757       if ($width && $height &&
758           m/\.gif$/io &&
759           ($width * $height) < $min_gif_area) {
760         LOG ($verbose_filter, "  skip small GIF $_ (${width}x$height)");
761         next;
762       }
763       
764       # skip images with a URL that indicates a Yahoo thumbnail.
765       if (m@\.yimg\.com/.*/t/@) {
766         if (!$width)  { $width  = "?"; }
767         if (!$height) { $height = "?"; }
768         LOG ($verbose_filter, "  skip yahoo thumb $_ (${width}x$height)");
769         next;
770       }
771
772       my $url = $_;
773
774       if ($unique_urls{$url}) {
775         LOG ($verbose_filter, "  skip duplicate image $_");
776         next;
777       }
778
779       LOG ($verbose_filter,
780            "  image $url" .
781            ($width && $height ? " (${width}x${height})" : "") .
782            ($was_inline ? " (inline)" : ""));
783
784       $urls[++$#urls] = $url;
785       $unique_urls{$url}++;
786
787       # JPEGs are preferable to GIFs and PNGs.
788       $_ = $url;
789       if ( ! m@[.](gif|png)$@io ) {
790         $urls[++$#urls] = $url;
791       }
792
793       # pointers to images are preferable to inlined images.
794       if ( ! $was_inline ) {
795         $urls[++$#urls] = $url;
796         $urls[++$#urls] = $url;
797       }
798     }
799   }
800
801   my $fsp = ($body =~ m@<frameset@i);
802
803   $_ = undef;
804   $body = undef;
805
806   @urls = depoison (@urls);
807
808   if ( $#urls < 0 ) {
809     LOG ($verbose_load, "no images on $base" . ($fsp ? " (frameset)" : ""));
810     return ();
811   }
812
813   # pick a random element of the table
814   my $i = int(rand($#urls+1));
815   $url = $urls[$i];
816
817   LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#urls+1) . ": $url");
818
819   return $url;
820 }
821
822 # Given a URL and the RSS feed from that URL, pick a random image from
823 # the feed.  This is a lot simpler than extracting images out of a page:
824 # we already know we have reasonable images, so we just pick one.
825 # Returns: the real URL of the page (preferably not the RSS version),
826 # and the image.
827
828 sub pick_image_from_rss($$) {
829   my ( $url, $body ) = @_;
830   my @suitable = ($body =~ m/<enclosure url="(.*?)"/g);
831
832   my ($base) = ($body =~ m@<link>([^<>]+)</link>@i);
833   $base = $url unless $base;
834
835   # pick a random element of the table
836   if (@suitable) {
837     my $i = int(rand(scalar @suitable));
838     my $url = $suitable[$i];
839     LOG ($verbose_load, "picked image " .($i+1) . "/" . 
840                         ($#suitable+1) . ": $url");
841     return ($base, $url);
842   }
843   return;
844 }
845
846 \f
847 ############################################################################
848 #
849 # Subroutines for getting pages and images out of search engines
850 #
851 ############################################################################
852
853
854 sub pick_dictionary() {
855   my @dicts = ("/usr/dict/words",
856                "/usr/share/dict/words",
857                "/usr/share/lib/dict/words");
858   foreach my $f (@dicts) {
859     if (-f $f) {
860       $wordlist = $f;
861       last;
862     }
863   }
864   error ("$dicts[0] does not exist") unless defined($wordlist);
865 }
866
867 # returns a random word from the dictionary
868 #
869 sub random_word() {
870
871   local *IN;
872   if (! open (IN, "<$wordlist")) {
873     return undef;
874   }
875
876   my $size = (stat(IN))[7];
877   my $word = undef;
878   my $count = 0;
879
880   while (1) {
881     error ("looping ($count) while reading $wordlist")
882       if (++$count > 100);
883
884     my $pos = int (rand ($size));
885     if (seek (IN, $pos, 0)) {
886       $word = <IN>;   # toss partial line
887       $word = <IN>;   # keep next line
888     }
889
890     next unless ($word);
891     next if ($word =~ m/^[-\']/);
892
893     $word = lc($word);
894     $word =~ s/^.*-//s;
895     $word =~ s/^[^a-z]+//s;
896     $word =~ s/[^a-z]+$//s;
897     $word =~ s/\'s$//s;
898     $word =~ s/ys$/y/s;
899     $word =~ s/ally$//s;
900     $word =~ s/ly$//s;
901     $word =~ s/ies$/y/s;
902     $word =~ s/ally$/al/s;
903     $word =~ s/izes$/ize/s;
904     $word =~ s/esses$/ess/s;
905     $word =~ s/(.{5})ing$/$1/s;
906
907     next if (length ($word) > 14);
908     last if ($word);
909   }
910
911   close (IN);
912
913   if ( $word =~ s/\s/\+/gs ) {  # convert intra-word spaces to "+".
914     $word = "\%22$word\%22";    # And put quotes (%22) around it.
915   }
916
917   return $word;
918 }
919
920
921 sub random_words($) {
922   my ($or_p) = @_;
923   my $sep = ($or_p ? "%20OR%20" : "%20");
924   return (random_word . $sep .
925           random_word . $sep .
926           random_word . $sep .
927           random_word . $sep .
928           random_word);
929 }
930
931
932 sub url_quote($) {
933   my ($s) = @_;
934   $s =~ s|([^-a-zA-Z0-9.\@/_\r\n])|sprintf("%%%02X", ord($1))|ge;
935   return $s;
936 }
937
938 sub url_unquote($) {
939   my ($s) = @_;
940   $s =~ s/[+]/ /g;
941   $s =~ s/%([a-z0-9]{2})/chr(hex($1))/ige;
942   return $s;
943 }
944
945 sub html_quote($) {
946   my ($s) = @_;
947   $s =~ s/&/&amp;/gi;
948   $s =~ s/</&lt;/gi;
949   $s =~ s/>/&gt;/gi;
950   $s =~ s/\"/&quot;/gi;
951   return $s;
952 }
953
954 sub html_unquote($) {
955   my ($s) = @_;
956   $s =~ s/(&([a-z]+);)/{ $entity_table{$2} || $1; }/gexi;  # e.g., &apos;
957   $s =~ s/(&\#(\d+);)/{ chr($2) }/gexi;                    # e.g., &#39;
958   return $s;
959 }
960
961
962 # Loads the given URL (a search on some search engine) and returns:
963 # - the total number of hits the search engine claimed it had;
964 # - a list of URLs from the page that the search engine returned;
965 # Note that this list contains all kinds of internal search engine
966 # junk URLs too -- caller must prune them.
967 #
968 sub pick_from_search_engine($$$) {
969   my ( $timeout, $search_url, $words ) = @_;
970
971   $_ = $words;
972   s/%20/ /g;
973
974   print STDERR "\n\n" if ($verbose_load);
975
976   LOG ($verbose_load, "words: $_");
977   LOG ($verbose_load, "URL: $search_url");
978
979   $last_search = $search_url;   # for warnings
980
981   my $start = time;
982   my ( $base, $body ) = get_document ($search_url, undef, $timeout);
983   if (defined ($timeout)) {
984     $timeout -= (time - $start);
985     if ($timeout <= 0) {
986       $body = undef;
987       LOG (($verbose_net || $verbose_load),
988            "timed out (late) for $search_url");
989       $suppress_audit = 1;
990       return ();
991     }
992   }
993
994   return () if (! $body);
995
996
997   my @subpages;
998
999   my $search_count = "?";
1000   if ($body =~ m@found (approximately |about )?(<B>)?(\d+)(</B>)? image@) {
1001     $search_count = $3;
1002   } elsif ($body =~ m@<NOBR>((\d{1,3})(,\d{3})*)&nbsp;@i) {
1003     $search_count = $1;
1004   } elsif ($body =~ m@found ((\d{1,3})(,\d{3})*|\d+) Web p@) {
1005     $search_count = $1;
1006   } elsif ($body =~ m@found about ((\d{1,3})(,\d{3})*|\d+) results@) {
1007     $search_count = $1;
1008   } elsif ($body =~ m@\b\d+ - \d+ of (\d+)\b@i) { # avimages
1009     $search_count = $1;
1010   } elsif ($body =~ m@About ((\d{1,3})(,\d{3})*) images@i) { # avimages
1011     $search_count = $1;
1012   } elsif ($body =~ m@We found ((\d{1,3})(,\d{3})*|\d+) results@i) { # *vista
1013     $search_count = $1;
1014   } elsif ($body =~ m@ of about <B>((\d{1,3})(,\d{3})*)<@i) { # googleimages
1015     $search_count = $1;
1016   } elsif ($body =~ m@<B>((\d{1,3})(,\d{3})*)</B> Web sites were found@i) {
1017     $search_count = $1;    # lycos
1018   } elsif ($body =~ m@WEB.*?RESULTS.*?\b((\d{1,3})(,\d{3})*)\b.*?Matches@i) {
1019     $search_count = $1;                          # hotbot
1020   } elsif ($body =~ m@no photos were found containing@i) { # avimages
1021     $search_count = "0";
1022   } elsif ($body =~ m@found no document matching@i) { # avtext
1023     $search_count = "0";
1024   }
1025   1 while ($search_count =~ s/^(\d+)(\d{3})/$1,$2/);
1026
1027 #  if ($search_count eq "?" || $search_count eq "0") {
1028 #    local *OUT;
1029 #    my $file = "/tmp/wc.html";
1030 #    open(OUT, ">$file") || error ("writing $file: $!");
1031 #    print OUT $body;
1032 #    close OUT;
1033 #    print STDERR  blurb() . "###### wrote $file\n";
1034 #  }
1035
1036
1037   my $length = length($body);
1038   my $href_count = 0;
1039
1040   $_ = $body;
1041
1042   s/[\r\n\t ]+/ /g;
1043
1044
1045   s/(<A )/\n$1/gi;
1046   foreach (split(/\n/)) {
1047     $href_count++;
1048     my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
1049     next unless $u;
1050
1051     if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; }   # quoted string
1052     elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; }  # or token
1053
1054     if ( $rejected_urls{$u} ) {
1055       LOG ($verbose_filter, "  pre-rejecting candidate: $u");
1056       next;
1057     }
1058
1059     LOG ($verbose_http, "    HREF: $u");
1060
1061     $subpages[++$#subpages] = $u;
1062   }
1063
1064   if ( $#subpages < 0 ) {
1065     LOG ($verbose_filter,
1066          "found nothing on $base ($length bytes, $href_count links).");
1067     return ();
1068   }
1069
1070   LOG ($verbose_filter, "" . $#subpages+1 . " links on $search_url");
1071
1072   return ($search_count, @subpages);
1073 }
1074
1075
1076 sub depoison(@) {
1077   my (@urls) = @_;
1078   my @urls2 = ();
1079   foreach (@urls) {
1080     my ($h) = m@^http://([^/: \t\r\n]+)@i;
1081
1082     next unless defined($h);
1083
1084     if ($poisoners{$h}) {
1085       LOG (($verbose_filter), "  rejecting poisoner: $_");
1086       next;
1087     }
1088     if ($h =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
1089         $poisoners{$1}) {
1090       LOG (($verbose_filter), "  rejecting poisoner: $_");
1091       next;
1092     }
1093     if ($h =~ m@([^.]+\.[^.]+)$@ &&
1094         $poisoners{$1}) {
1095       LOG (($verbose_filter), "  rejecting poisoner: $_");
1096       next;
1097     }
1098
1099     push @urls2, $_;
1100   }
1101   return @urls2;
1102 }
1103
1104
1105 # given a list of URLs, picks one at random; loads it; and returns a
1106 # random image from it.
1107 # returns the url of the page loaded; the url of the image chosen.
1108 #
1109 sub pick_image_from_pages($$$$@) {
1110   my ($base, $total_hit_count, $unfiltered_link_count, $timeout, @pages) = @_;
1111
1112   $total_hit_count = "?" unless defined($total_hit_count);
1113
1114   @pages = depoison (@pages);
1115   LOG ($verbose_load,
1116        "" . ($#pages+1) . " candidates of $unfiltered_link_count links" .
1117        " ($total_hit_count total)");
1118
1119   return () if ($#pages < 0);
1120
1121   my $i = int(rand($#pages+1));
1122   my $page = $pages[$i];
1123
1124   LOG ($verbose_load, "picked page $page");
1125
1126   $suppress_audit = 1;
1127
1128   my ( $base2, $body2 ) = get_document ($page, $base, $timeout);
1129
1130   if (!$base2 || !$body2) {
1131     $body2 = undef;
1132     return ();
1133   }
1134
1135   my $img = pick_image_from_body ($base2, $body2);
1136   $body2 = undef;
1137
1138   if ($img) {
1139     return ($base2, $img);
1140   } else {
1141     return ();
1142   }
1143 }
1144
1145 \f
1146 ############################################################################
1147 #
1148 # Pick images from random pages returned by the Yahoo Random Link
1149 #
1150 ############################################################################
1151
1152 # yahoorand
1153 my $yahoo_random_link = "http://random.yahoo.com/fast/ryl";
1154
1155
1156 # Picks a random page; picks a random image on that page;
1157 # returns two URLs: the page containing the image, and the image.
1158 # Returns () if nothing found this time.
1159 #
1160 sub pick_from_yahoo_random_link($) {
1161   my ($timeout) = @_;
1162
1163   print STDERR "\n\n" if ($verbose_load);
1164   LOG ($verbose_load, "URL: $yahoo_random_link");
1165
1166   $last_search = $yahoo_random_link;   # for warnings
1167
1168   $suppress_audit = 1;
1169
1170   my ( $base, $body ) = get_document ($yahoo_random_link, undef, $timeout);
1171   if (!$base || !$body) {
1172     $body = undef;
1173     return;
1174   }
1175
1176   LOG ($verbose_load, "redirected to: $base");
1177
1178   my $img = pick_image_from_body ($base, $body);
1179   $body = undef;
1180
1181   if ($img) {
1182     return ($base, $img);
1183   } else {
1184     return ();
1185   }
1186 }
1187
1188 \f
1189 ############################################################################
1190 #
1191 # Pick images from random pages returned by the Alta Vista Random Link
1192 #
1193 ############################################################################
1194
1195 # altavista
1196 my $alta_vista_random_link = "http://www.altavista.com/image/randomlink";
1197
1198
1199 # Picks a random page; picks a random image on that page;
1200 # returns two URLs: the page containing the image, and the image.
1201 # Returns () if nothing found this time.
1202 #
1203 sub pick_from_alta_vista_random_link($) {
1204   my ($timeout) = @_;
1205
1206   print STDERR "\n\n" if ($verbose_load);
1207   LOG ($verbose_load, "URL: $alta_vista_random_link");
1208
1209   $last_search = $alta_vista_random_link;   # for warnings
1210
1211   $suppress_audit = 1;
1212
1213   my ( $base, $body ) = get_document ($alta_vista_random_link,
1214                                       undef, $timeout);
1215   if (!$base || !$body) {
1216     $body = undef;
1217     return;
1218   }
1219
1220   LOG ($verbose_load, "redirected to: $base");
1221
1222   my $img = pick_image_from_body ($base, $body);
1223   $body = undef;
1224
1225   if ($img) {
1226     return ($base, $img);
1227   } else {
1228     return ();
1229   }
1230 }
1231
1232 \f
1233 ############################################################################
1234 #
1235 # Pick images by feeding random words into Alta Vista Image Search
1236 #
1237 ############################################################################
1238
1239
1240 my $alta_vista_images_url = "http://www.altavista.com/image/results" .
1241                             "?ipht=1" .       # photos
1242                             "&igrph=1" .      # graphics
1243                             "&iclr=1" .       # color
1244                             "&ibw=1" .        # b&w
1245                             "&micat=1" .      # no partner sites
1246                             "&sc=on" .        # "site collapse"
1247                             "&q=";
1248
1249 # avimages
1250 sub pick_from_alta_vista_images($) {
1251   my ($timeout) = @_;
1252
1253   my $words = random_word();
1254   my $page = (int(rand(9)) + 1);
1255   my $search_url = $alta_vista_images_url . $words;
1256
1257   if ($page > 1) {
1258     $search_url .= "&pgno=" . $page;            # page number
1259     $search_url .= "&stq=" . (($page-1) * 12);  # first hit result on page
1260   }
1261
1262   my ($search_hit_count, @subpages) =
1263     pick_from_search_engine ($timeout, $search_url, $words);
1264
1265   my @candidates = ();
1266   foreach my $u (@subpages) {
1267
1268     # avimages is encoding their URLs now.
1269     next unless ($u =~ s/^.*\*\*(http%3a.*$)/$1/gsi);
1270     $u = url_unquote($u);
1271
1272     next unless ($u =~ m@^http://@i);    #  skip non-HTTP or relative URLs
1273     next if ($u =~ m@[/.]altavista\.com\b@i);     # skip altavista builtins
1274     next if ($u =~ m@[/.]yahoo\.com\b@i);         # yahoo and av in cahoots?
1275     next if ($u =~ m@[/.]doubleclick\.net\b@i);   # you cretins
1276     next if ($u =~ m@[/.]clicktomarket\.com\b@i); # more cretins
1277
1278     next if ($u =~ m@[/.]viewimages\.com\b@i);    # stacked deck
1279     next if ($u =~ m@[/.]gettyimages\.com\b@i);
1280
1281     LOG ($verbose_filter, "  candidate: $u");
1282     push @candidates, $u;
1283   }
1284
1285   return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1286                                 $timeout, @candidates);
1287 }
1288
1289
1290 \f
1291 ############################################################################
1292 #
1293 # Pick images by feeding random words into Google Image Search.
1294 # By Charles Gales <gales@us.ibm.com>
1295 #
1296 ############################################################################
1297
1298
1299 my $google_images_url =     "http://images.google.com/images" .
1300                             "?site=images" .  # photos
1301                             "&btnG=Search" .  # graphics
1302                             "&safe=off" .     # no screening
1303                             "&imgsafe=off" .
1304                             "&q=";
1305
1306 # googleimgs
1307 sub pick_from_google_images($;$$) {
1308   my ($timeout, $words, $max_page) = @_;
1309
1310   if (!defined($words)) {
1311     $words = random_word;   # only one word for Google
1312   }
1313
1314   my $page = (int(rand(9)) + 1);
1315   my $num = 20;     # 20 images per page
1316   my $search_url = $google_images_url . $words;
1317
1318   if ($page > 1) {
1319     $search_url .= "&start=" . $page*$num;      # page number
1320     $search_url .= "&num="   . $num;            #images per page
1321   }
1322
1323   my ($search_hit_count, @subpages) =
1324     pick_from_search_engine ($timeout, $search_url, $words);
1325
1326   my @candidates = ();
1327   my %referers;
1328   foreach my $u (@subpages) {
1329     next unless ($u =~ m@imgres\?imgurl@i);    #  All pics start with this
1330     next if ($u =~ m@[/.]google\.com\b@i);     # skip google builtins
1331
1332     if ($u =~ m@^/imgres\?imgurl=(.*?)\&imgrefurl=(.*?)\&@) {
1333       my $ref = $2;
1334       my $img = $1;
1335       $img = "http://$img" unless ($img =~ m/^http:/i);
1336
1337       LOG ($verbose_filter, "  candidate: $ref");
1338       push @candidates, $img;
1339       $referers{$img} = $ref;
1340     }
1341   }
1342
1343   @candidates = depoison (@candidates);
1344   return () if ($#candidates < 0);
1345   my $i = int(rand($#candidates+1));
1346   my $img = $candidates[$i];
1347   my $ref = $referers{$img};
1348
1349   LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1350   return ($ref, $img);
1351 }
1352
1353
1354 \f
1355 ############################################################################
1356 #
1357 # Pick images by feeding random numbers into Google Image Search.
1358 # By jwz, suggested by Ian O'Donnell.
1359 #
1360 ############################################################################
1361
1362
1363 # googlenums
1364 sub pick_from_google_image_numbers($) {
1365   my ($timeout) = @_;
1366
1367   my $max = 9999;
1368   my $number = int(rand($max));
1369
1370   $number = sprintf("%04d", $number)
1371     if (rand() < 0.3);
1372
1373   pick_from_google_images ($timeout, "$number");
1374 }
1375
1376
1377 \f
1378 ############################################################################
1379 #
1380 # Pick images by feeding random digital camera file names into 
1381 # Google Image Search.
1382 # By jwz, inspired by the excellent Random Personal Picture Finder
1383 # at http://www.diddly.com/random/
1384 #
1385 ############################################################################
1386
1387 my @photomakers = (
1388   #
1389   # Common digital camera file name formats, as described at
1390   # http://www.diddly.com/random/about.html
1391   #
1392   sub { sprintf ("dcp%05d.jpg",  int(rand(4000))); },   # Kodak
1393   sub { sprintf ("dsc%05d.jpg",  int(rand(4000))); },   # Nikon
1394   sub { sprintf ("dscn%04d.jpg", int(rand(4000))); },   # Nikon
1395   sub { sprintf ("mvc-%03d.jpg", int(rand(999)));  },   # Sony Mavica
1396   sub { sprintf ("mvc%05d.jpg",  int(rand(9999))); },   # Sony Mavica
1397   sub { sprintf ("P101%04d.jpg", int(rand(9999))); },   # Olympus w/ date=101
1398   sub { sprintf ("P%x%02d%04d.jpg",                     # Olympus
1399                  int(rand(0xC)), int(rand(30))+1,
1400                  rand(9999)); },
1401   sub { sprintf ("IMG_%03d.jpg",  int(rand(999))); },   # ?
1402   sub { sprintf ("IMAG%04d.jpg",  int(rand(9999))); },  # RCA and Samsung
1403   sub { my $n = int(rand(9999));                        # Canon
1404           sprintf ("1%02d-%04d.jpg", int($n/100), $n); },
1405   sub { my $n = int(rand(9999));                        # Canon
1406           sprintf ("1%02d-%04d_IMG.jpg",
1407                    int($n/100), $n); },
1408   sub { sprintf ("IMG_%04d.jpg", int(rand(9999))); },   # Canon
1409   sub { sprintf ("dscf%04d.jpg", int(rand(9999))); },   # Fuji Finepix
1410   sub { sprintf ("pdrm%04d.jpg", int(rand(9999))); },   # Toshiba PDR
1411   sub { sprintf ("IM%06d.jpg", int(rand(9999))); },     # HP Photosmart
1412   sub { sprintf ("EX%06d.jpg", int(rand(9999))); },     # HP Photosmart
1413 #  sub { my $n = int(rand(3));                          # Kodak DC-40,50,120
1414 #        sprintf ("DC%04d%s.jpg", int(rand(9999)),
1415 #                 $n == 0 ? 'S' : $n == 1 ? 'M' : 'L'); },
1416   sub { sprintf ("pict%04d.jpg", int(rand(9999))); },   # Minolta Dimage
1417   sub { sprintf ("P%07d.jpg", int(rand(9999))); },      # Kodak DC290
1418 #  sub { sprintf ("%02d%02d%04d.jpg",                   # Casio QV3000, QV4000
1419 #                 int(rand(12))+1, int(rand(31))+1,
1420 #                 int(rand(999))); },
1421 #  sub { sprintf ("%02d%x%02d%04d.jpg",                 # Casio QV7000
1422 #                 int(rand(6)), # year
1423 #                 int(rand(12))+1, int(rand(31))+1,
1424 #                 int(rand(999))); },
1425   sub { sprintf ("IMGP%04d.jpg", int(rand(9999))); },   # Pentax Optio S
1426   sub { sprintf ("PANA%04d.jpg", int(rand(9999))); },   # Panasonic vid still
1427   sub { sprintf ("HPIM%04d.jpg", int(rand(9999))); },   # HP Photosmart
1428   sub { sprintf ("PCDV%04d.jpg", int(rand(9999))); },   # ?
1429  );
1430
1431
1432 # googlephotos
1433 sub pick_from_google_image_photos($) {
1434   my ($timeout) = @_;
1435
1436   my $i = int(rand($#photomakers + 1));
1437   my $fn = $photomakers[$i];
1438   my $file = &$fn;
1439   my $words .= $file . "%20filetype:jpg";
1440
1441   pick_from_google_images ($timeout, $words);
1442 }
1443
1444
1445 \f
1446 ############################################################################
1447 #
1448 # Pick images by feeding random words into Alta Vista Text Search
1449 #
1450 ############################################################################
1451
1452
1453 my $alta_vista_url = "http://www.altavista.com/web/results" .
1454                      "?pg=aq" .
1455                      "&aqmode=s" .
1456                      "&filetype=html" .
1457                      "&sc=on" .        # "site collapse"
1458                      "&nbq=50" .
1459                      "&aqo=";
1460
1461 # avtext
1462 sub pick_from_alta_vista_text($) {
1463   my ($timeout) = @_;
1464
1465   my $words = random_words(0);
1466   my $page = (int(rand(9)) + 1);
1467   my $search_url = $alta_vista_url . $words;
1468
1469   if ($page > 1) {
1470     $search_url .= "&pgno=" . $page;
1471     $search_url .= "&stq=" . (($page-1) * 10);
1472   }
1473
1474   my ($search_hit_count, @subpages) =
1475     pick_from_search_engine ($timeout, $search_url, $words);
1476
1477   my @candidates = ();
1478   foreach my $u (@subpages) {
1479
1480     # Those altavista fuckers are playing really nasty redirection games
1481     # these days: the filter your clicks through their site, but use
1482     # onMouseOver to make it look like they're not!  Well, it makes it
1483     # easier for us to identify search results...
1484     #
1485     next unless ($u =~ s/^.*\*\*(http%3a.*$)/$1/gsi);
1486     $u = url_unquote($u);
1487
1488     next unless ($u =~ m@^http://@i);    #  skip non-HTTP or relative URLs
1489     next if ($u =~ m@[/.]altavista\.com\b@i);     # skip altavista builtins
1490     next if ($u =~ m@[/.]yahoo\.com\b@i);         # yahoo and av in cahoots?
1491
1492     LOG ($verbose_filter, "  candidate: $u");
1493     push @candidates, $u;
1494   }
1495
1496   return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1497                                 $timeout, @candidates);
1498 }
1499
1500
1501 \f
1502 ############################################################################
1503 #
1504 # Pick images by feeding random words into Hotbot
1505 #
1506 ############################################################################
1507
1508 my $hotbot_search_url =("http://hotbot.lycos.com/default.asp" .
1509                         "?ca=w" .
1510                         "&descriptiontype=0" .
1511                         "&imagetoggle=1" .
1512                         "&matchmode=any" .
1513                         "&nummod=2" .
1514                         "&recordcount=50" .
1515                         "&sitegroup=1" .
1516                         "&stem=1" .
1517                         "&cobrand=undefined" .
1518                         "&query=");
1519
1520 sub pick_from_hotbot_text($) {
1521   my ($timeout) = @_;
1522
1523   $last_search = $hotbot_search_url;   # for warnings
1524
1525   # lycos seems to always give us back dictionaries and word lists if
1526   # we search for more than one word...
1527   #
1528   my $words = random_word();
1529
1530   my $start = int(rand(8)) * 10 + 1;
1531   my $search_url = $hotbot_search_url . $words . "&first=$start&page=more";
1532
1533   my ($search_hit_count, @subpages) =
1534     pick_from_search_engine ($timeout, $search_url, $words);
1535
1536   my @candidates = ();
1537   foreach my $u (@subpages) {
1538
1539     # Hotbot plays redirection games too
1540     # (not any more?)
1541 #    next unless ($u =~ m@/director.asp\?.*\btarget=([^&]+)@);
1542 #    $u = url_decode($1);
1543
1544     next unless ($u =~ m@^http://@i);    #  skip non-HTTP or relative URLs
1545     next if ($u =~ m@[/.]hotbot\.com\b@i);     # skip hotbot builtins
1546     next if ($u =~ m@[/.]lycos\.com\b@i);      # skip hotbot builtins
1547     next if ($u =~ m@[/.]inktomi\.com\b@i);    # skip hotbot builtins
1548
1549     LOG ($verbose_filter, "  candidate: $u");
1550     push @candidates, $u;
1551   }
1552
1553   return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1554                                 $timeout, @candidates);
1555 }
1556
1557
1558 \f
1559 ############################################################################
1560 #
1561 # Pick images by feeding random words into Lycos
1562 #
1563 ############################################################################
1564
1565 my $lycos_search_url = "http://search.lycos.com/default.asp" .
1566                        "?lpv=1" .
1567                        "&loc=searchhp" .
1568                        "&tab=web" .
1569                        "&query=";
1570
1571 sub pick_from_lycos_text($) {
1572   my ($timeout) = @_;
1573
1574   $last_search = $lycos_search_url;   # for warnings
1575
1576   # lycos seems to always give us back dictionaries and word lists if
1577   # we search for more than one word...
1578   #
1579   my $words = random_word();
1580
1581   my $start = int(rand(8)) * 10 + 1;
1582   my $search_url = $lycos_search_url . $words . "&first=$start&page=more";
1583
1584   my ($search_hit_count, @subpages) =
1585     pick_from_search_engine ($timeout, $search_url, $words);
1586
1587   my @candidates = ();
1588   foreach my $u (@subpages) {
1589
1590     # Lycos plays redirection games.
1591     # (not any more?)
1592 #    next unless ($u =~ m@^http://click.lycos.com/director.asp
1593 #                         .*
1594 #                         \btarget=([^&]+)
1595 #                         .*
1596 #                        @x);
1597 #    $u = url_decode($1);
1598
1599     next unless ($u =~ m@^http://@i);    #  skip non-HTTP or relative URLs
1600     next if ($u =~ m@[/.]hotbot\.com\b@i);     # skip lycos builtins
1601     next if ($u =~ m@[/.]lycos\.com\b@i);      # skip lycos builtins
1602     next if ($u =~ m@[/.]terralycos\.com\b@i); # skip lycos builtins
1603     next if ($u =~ m@[/.]inktomi\.com\b@i);    # skip lycos builtins
1604
1605
1606     LOG ($verbose_filter, "  candidate: $u");
1607     push @candidates, $u;
1608   }
1609
1610   return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1611                                 $timeout, @candidates);
1612 }
1613
1614
1615 \f
1616 ############################################################################
1617 #
1618 # Pick images by feeding random words into news.yahoo.com
1619 #
1620 ############################################################################
1621
1622 my $yahoo_news_url = "http://news.search.yahoo.com/search/news" .
1623                      "?c=news_photos" .
1624                      "&p=";
1625
1626 # yahoonews
1627 sub pick_from_yahoo_news_text($) {
1628   my ($timeout) = @_;
1629
1630   $last_search = $yahoo_news_url;   # for warnings
1631
1632   my $words = random_word();
1633   my $search_url = $yahoo_news_url . $words;
1634
1635   my ($search_hit_count, @subpages) =
1636     pick_from_search_engine ($timeout, $search_url, $words);
1637
1638   my @candidates = ();
1639   foreach my $u (@subpages) {
1640
1641     # de-redirectize the URLs
1642     $u =~ s@^http://rds\.yahoo\.com/.*-http%3A@http:@s;
1643
1644     # only accept URLs on Yahoo's news site
1645     next unless ($u =~ m@^http://dailynews\.yahoo\.com/@i ||
1646                  $u =~ m@^http://story\.news\.yahoo\.com/@i);
1647     next unless ($u =~ m@&u=/@);
1648
1649     LOG ($verbose_filter, "  candidate: $u");
1650     push @candidates, $u;
1651   }
1652
1653   return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1654                                 $timeout, @candidates);
1655 }
1656
1657
1658 \f
1659 ############################################################################
1660 #
1661 # Pick images from LiveJournal's list of recently-posted images.
1662 #
1663 ############################################################################
1664
1665 my $livejournal_img_url = "http://www.livejournal.com/stats/latest-img.bml";
1666
1667 # With most of our image sources, we get a random page and then select
1668 # from the images on it.  However, in the case of LiveJournal, the page
1669 # of images tends to update slowly; so we'll remember the last N entries
1670 # on it and randomly select from those, to get a wider variety each time.
1671
1672 my $lj_cache_size = 1000;
1673 my @lj_cache = (); # fifo, for ordering by age
1674 my %lj_cache = (); # hash, for detecting dups
1675
1676 # livejournal
1677 sub pick_from_livejournal_images($) {
1678   my ($timeout) = @_;
1679
1680   $last_search = $livejournal_img_url;   # for warnings
1681
1682   my ( $base, $body ) = get_document ($livejournal_img_url, undef, $timeout);
1683   return () unless $body;
1684
1685   $body =~ s/\n/ /gs;
1686   $body =~ s/(<recent-image)\b/\n$1/gsi;
1687
1688   foreach (split (/\n/, $body)) {
1689     next unless (m/^<recent-image\b/);
1690     next unless (m/\bIMG=[\'\"]([^\'\"]+)[\'\"]/si);
1691     my $img = html_unquote ($1);
1692
1693     next if ($lj_cache{$img}); # already have it
1694
1695     next unless (m/\bURL=[\'\"]([^\'\"]+)[\'\"]/si);
1696     my $page = html_unquote ($1);
1697     my @pair = ($img, $page);
1698     LOG ($verbose_filter, "  candidate: $img");
1699     push @lj_cache, \@pair;
1700     $lj_cache{$img} = \@pair;
1701   }
1702
1703   return () if ($#lj_cache == -1);
1704
1705   my $n = $#lj_cache+1;
1706   my $i = int(rand($n));
1707   my ($img, $page) = @{$lj_cache[$i]};
1708
1709   # delete this one from @lj_cache and from %lj_cache.
1710   #
1711   @lj_cache = ( @lj_cache[0 .. $i-1],
1712                 @lj_cache[$i+1 .. $#lj_cache] );
1713   delete $lj_cache{$img};
1714
1715   # Keep the size of the cache under the limit by nuking older entries
1716   #
1717   while ($#lj_cache >= $lj_cache_size) {
1718     my $pairP = shift @lj_cache;
1719     my $img = $pairP->[0];
1720     delete $lj_cache{$img};
1721   }
1722
1723   LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
1724
1725   return ($page, $img);
1726 }
1727
1728 \f
1729 ############################################################################
1730 #
1731 # Pick images from ircimages.com (images that have been in the /topic of
1732 # various IRC channels.)
1733 #
1734 ############################################################################
1735
1736 my $ircimages_url = "http://ircimages.com/";
1737
1738 # ircimages
1739 sub pick_from_ircimages($) {
1740   my ($timeout) = @_;
1741
1742   $last_search = $ircimages_url;   # for warnings
1743
1744   my $n = int(rand(2900));
1745   my $search_url = $ircimages_url . "page-$n";
1746
1747   my ( $base, $body ) = get_document ($search_url, undef, $timeout);
1748   return () unless $body;
1749
1750   my @candidates = ();
1751
1752   $body =~ s/\n/ /gs;
1753   $body =~ s/(<A)\b/\n$1/gsi;
1754
1755   foreach (split (/\n/, $body)) {
1756
1757     my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
1758     next unless $u;
1759
1760     if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; }   # quoted string
1761     elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; }  # or token
1762
1763     next unless ($u =~ m/^http:/i);
1764     next if ($u =~ m@^http://(searchirc\.com\|ircimages\.com)@i);
1765     next unless ($u =~ m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@i);
1766
1767     LOG ($verbose_http, "    HREF: $u");
1768     push @candidates, $u;
1769   }
1770
1771   LOG ($verbose_filter, "" . $#candidates+1 . " links on $search_url");
1772
1773   return () if ($#candidates == -1);
1774
1775   my $i = int(rand($#candidates+1));
1776   my $img = $candidates[$i];
1777
1778   LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#candidates+1) .
1779        ": $img");
1780
1781   $search_url = $img;  # hmm...
1782   return ($search_url, $img);
1783 }
1784
1785 \f
1786 ############################################################################
1787 #
1788 # Pick images from Flickr's page of recently-posted photos.
1789 #
1790 ############################################################################
1791
1792 my $flickr_img_url = "http://www.flickr.com/photos/";
1793
1794 # Like LiveJournal, the Flickr page of images tends to update slowly,
1795 # so remember the last N entries on it and randomly select from those.
1796
1797 # I know that Flickr has an API (http://www.flickr.com/services/api/)
1798 # but it was easy enough to scrape the HTML, so I didn't bother exploring.
1799
1800 my $flickr_cache_size = 1000;
1801 my @flickr_cache = (); # fifo, for ordering by age
1802 my %flickr_cache = (); # hash, for detecting dups
1803
1804
1805 # flickr_recent
1806 sub pick_from_flickr_recent($) {
1807   my ($timeout) = @_;
1808
1809   my $start = 16 * int(rand(100));
1810
1811   $last_search = $flickr_img_url;   # for warnings
1812   $last_search .= "?start=$start" if ($start > 0);
1813
1814   my ( $base, $body ) = get_document ($last_search, undef, $timeout);
1815   return () unless $body;
1816
1817   $body =~ s/[\r\n]/ /gs;
1818   $body =~ s/(<a)\b/\n$1/gsi;
1819
1820   my $count = 0;
1821   my $count2 = 0;
1822   foreach (split (/\n/, $body)) {
1823     my ($page, $thumb) = m@<A \s [^<>]* \b HREF=\"([^<>\"]+)\" [^<>]* > \s*
1824                            <IMG \s [^<>]* \b SRC=\"([^<>\"]+)\" @xsi;
1825     next unless defined ($thumb);
1826     $page = html_unquote ($page);
1827     $thumb = html_unquote ($thumb);
1828
1829     next unless ($thumb =~ m@^http://farm\d*\.static\.flickr\.com/@);
1830
1831     my $base = "http://www.flickr.com/";
1832     $page  =~ s@^/@$base@;
1833     $thumb =~ s@^/@$base@;
1834
1835     my $img = $thumb;
1836     $img =~ s/_[a-z](\.[a-z\d]+)$/$1/si;  # take off "thumb" suffix
1837
1838     $count++;
1839     next if ($flickr_cache{$img}); # already have it
1840
1841     my @pair = ($img, $page, $start);
1842     LOG ($verbose_filter, "  candidate: $img");
1843     push @flickr_cache, \@pair;
1844     $flickr_cache{$img} = \@pair;
1845     $count2++;
1846   }
1847
1848   return () if ($#flickr_cache == -1);
1849
1850   my $n = $#flickr_cache+1;
1851   my $i = int(rand($n));
1852   my ($img, $page) = @{$flickr_cache[$i]};
1853
1854   # delete this one from @flickr_cache and from %flickr_cache.
1855   #
1856   @flickr_cache = ( @flickr_cache[0 .. $i-1],
1857                     @flickr_cache[$i+1 .. $#flickr_cache] );
1858   delete $flickr_cache{$img};
1859
1860   # Keep the size of the cache under the limit by nuking older entries
1861   #
1862   while ($#flickr_cache >= $flickr_cache_size) {
1863     my $pairP = shift @flickr_cache;
1864     my $img = $pairP->[0];
1865     delete $flickr_cache{$img};
1866   }
1867
1868   LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
1869
1870   return ($page, $img);
1871 }
1872
1873 \f
1874 ############################################################################
1875 #
1876 # Pick images from a random RSS feed on Flickr.
1877 #
1878 ############################################################################
1879
1880 my $flickr_rss_base = ("http://www.flickr.com/services/feeds/photos_public.gne" .
1881                        "?format=rss_200_enc&tags=");
1882
1883 # Picks a random RSS feed; picks a random image from that feed;
1884 # returns 2 URLs: the page containing the image, and the image.
1885 # Mostly by Joe Mcmahon <mcmahon@yahoo-inc.com>
1886 #
1887 # flickr_random
1888 sub pick_from_flickr_random($) {
1889   my $timeout = shift;
1890
1891   my $rss = $flickr_rss_base . random_word();
1892   $last_search = $rss;
1893
1894   print STDERR "\n\n" if ($verbose_load);
1895   LOG ($verbose_load, "URL: $last_search");
1896
1897   $suppress_audit = 1;
1898
1899   my ( $base, $body ) = get_document ($last_search, undef, $timeout);
1900   if (!$base || !$body) {
1901     $body = undef;
1902     return;
1903   }
1904
1905   my $img;
1906   ($base, $img) = pick_image_from_rss ($base, $body);
1907   $body = undef;
1908   return () unless defined ($img);
1909
1910   LOG ($verbose_load, "redirected to: $base");
1911   return ($base, $img);
1912 }
1913
1914 \f
1915 ############################################################################
1916 #
1917 # Pick images by waiting for driftnet to populate a temp dir with files.
1918 # Requires driftnet version 0.1.5 or later.
1919 # (Driftnet is a program by Chris Lightfoot that sniffs your local ethernet
1920 # for images being downloaded by others.)
1921 # Driftnet/webcollage integration by jwz.
1922 #
1923 ############################################################################
1924
1925 # driftnet
1926 sub pick_from_driftnet($) {
1927   my ($timeout) = @_;
1928
1929   my $id = $driftnet_magic;
1930   my $dir = $driftnet_dir;
1931   my $start = time;
1932   my $now;
1933
1934   error ("\$driftnet_dir unset?") unless ($dir);
1935   $dir =~ s@/+$@@;
1936
1937   error ("$dir unreadable") unless (-d "$dir/.");
1938
1939   $timeout = $http_timeout unless ($timeout);
1940   $last_search = $id;
1941
1942   while ($now = time, $now < $start + $timeout) {
1943     local *DIR;
1944     opendir (DIR, $dir) || error ("$dir: $!");
1945     while (my $file = readdir(DIR)) {
1946       next if ($file =~ m/^\./);
1947       $file = "$dir/$file";
1948       closedir DIR;
1949       LOG ($verbose_load, "picked file $file ($id)");
1950       return ($id, $file);
1951     }
1952     closedir DIR;
1953   }
1954   LOG (($verbose_net || $verbose_load), "timed out for $id");
1955   return ();
1956 }
1957
1958
1959 sub get_driftnet_file($) {
1960   my ($file) = @_;
1961
1962   error ("\$driftnet_dir unset?") unless ($driftnet_dir);
1963
1964   my $id = $driftnet_magic;
1965   my $re = qr/$driftnet_dir/;
1966   error ("$id: $file not in $driftnet_dir?")
1967     unless ($file =~ m@^$re@o);
1968
1969   local *IN;
1970   open (IN, $file) || error ("$id: $file: $!");
1971   my $body = '';
1972   while (<IN>) { $body .= $_; }
1973   close IN || error ("$id: $file: $!");
1974   unlink ($file) || error ("$id: $file: rm: $!");
1975   return ($id, $body);
1976 }
1977
1978
1979 sub spawn_driftnet($) {
1980   my ($cmd) = @_;
1981
1982   # make a directory to use.
1983   while (1) {
1984     my $tmp = $ENV{TEMPDIR} || "/tmp";
1985     $driftnet_dir = sprintf ("$tmp/driftcollage-%08x", rand(0xffffffff));
1986     LOG ($verbose_exec, "mkdir $driftnet_dir");
1987     last if mkdir ($driftnet_dir, 0700);
1988   }
1989
1990   if (! ($cmd =~ m/\s/)) {
1991     # if the command didn't have any arguments in it, then it must be just
1992     # a pointer to the executable.  Append the default args to it.
1993     my $dargs = $default_driftnet_cmd;
1994     $dargs =~ s/^[^\s]+//;
1995     $cmd .= $dargs;
1996   }
1997
1998   # point the driftnet command at our newly-minted private directory.
1999   #
2000   $cmd .= " -d $driftnet_dir";
2001   $cmd .= ">/dev/null" unless ($verbose_exec);
2002
2003   my $pid = fork();
2004   if ($pid < 0) { error ("fork: $!\n"); }
2005   if ($pid) {
2006     # parent fork
2007     push @pids_to_kill, $pid;
2008     LOG ($verbose_exec, "forked for \"$cmd\"");
2009   } else {
2010     # child fork
2011     nontrapping_system ($cmd) || error ("exec: $!");
2012   }
2013
2014   # wait a bit, then make sure the process actually started up.
2015   #
2016   sleep (1);
2017   error ("pid $pid failed to start \"$cmd\"")
2018     unless (1 == kill (0, $pid));
2019 }
2020
2021 # local-directory
2022 sub pick_from_local_dir {
2023   my ( $timeout ) = @_;
2024
2025   my $id = $local_magic;
2026   $last_search = $id;
2027
2028   my $dir = $local_dir;
2029   error ("\$local_dir unset?") unless ($dir);
2030   $dir =~ s@/+$@@;
2031
2032   error ("$dir unreadable") unless (-d "$dir/.");
2033
2034   my $v = ($verbose_exec ? "-v" : "");
2035   my $pick = `xscreensaver-getimage-file $v "$dir"`;
2036
2037   LOG ($verbose_load, "picked file $pick ($id)");
2038   return ($id, $pick);
2039 }
2040
2041
2042 sub get_local_file {
2043   my ($file) = @_;
2044
2045   error ("\$local_dir unset?") unless ($local_dir);
2046
2047   my $id = $local_magic;
2048   my $re = qr/$local_dir/;
2049   error ("$id: $file not in $local_dir?")
2050     unless ($file =~ m@^$re@o);
2051
2052   local *IN;
2053   open (IN, $file) || error ("$id: $file: $!");
2054   my $body = '';
2055   while (<IN>) { $body .= $_; }
2056   close IN || error ("$id: $file: $!");
2057   return ($id, $body);
2058 }
2059
2060
2061 \f
2062 ############################################################################
2063 #
2064 # Pick a random image in a random way
2065 #
2066 ############################################################################
2067
2068
2069 # Picks a random image on a random page, and returns two URLs:
2070 # the page containing the image, and the image.
2071 # Returns () if nothing found this time.
2072 #
2073
2074 sub pick_image(;$) {
2075   my ($timeout) = @_;
2076
2077   $current_state = "select";
2078   $load_method = "none";
2079
2080   my $n = int(rand(100));
2081   my $fn = undef;
2082   my $total = 0;
2083   my @rest = @search_methods;
2084
2085   while (@rest) {
2086     my $pct  = shift @rest;
2087     my $name = shift @rest;
2088     my $tfn  = shift @rest;
2089     $total += $pct;
2090     if ($total > $n && !defined($fn)) {
2091       $fn = $tfn;
2092       $current_state = $name;
2093       $load_method = $current_state;
2094     }
2095   }
2096
2097   if ($total != 100) {
2098     error ("internal error: \@search_methods totals to $total%!");
2099   }
2100
2101   record_attempt ($current_state);
2102   return $fn->($timeout);
2103 }
2104
2105
2106 \f
2107 ############################################################################
2108 #
2109 # Statistics and logging
2110 #
2111 ############################################################################
2112
2113 sub timestr() {
2114   return strftime ("%H:%M:%S: ", localtime);
2115 }
2116
2117 sub blurb() {
2118   return "$progname: " . timestr() . "$current_state: ";
2119 }
2120
2121 sub error($) {
2122   my ($err) = @_;
2123   print STDERR blurb() . "$err\n";
2124   exit 1;
2125 }
2126
2127 sub stacktrace() {
2128   my $i = 1;
2129   print STDERR "$progname: stack trace:\n";
2130   while (1) {
2131     my ($package, $filename, $line, $subroutine) = caller($i++);
2132     last unless defined($package);
2133     $filename =~ s@^.*/@@;
2134     print STDERR "  $filename#$line, $subroutine\n";
2135   }
2136 }
2137
2138
2139 my $lastlog = "";
2140
2141 sub clearlog() {
2142   $lastlog = "";
2143 }
2144
2145 sub showlog() {
2146   my $head = "$progname: DEBUG: ";
2147   foreach (split (/\n/, $lastlog)) {
2148     print STDERR "$head$_\n";
2149   }
2150   $lastlog = "";
2151 }
2152
2153 sub LOG($$) {
2154   my ($print, $msg) = @_;
2155   my $blurb = timestr() . "$current_state: ";
2156   $lastlog .= "$blurb$msg\n";
2157   print STDERR "$progname: $blurb$msg\n" if $print;
2158 }
2159
2160
2161 my %stats_attempts;
2162 my %stats_successes;
2163 my %stats_elapsed;
2164
2165 my $last_state = undef;
2166 sub record_attempt($) {
2167   my ($name) = @_;
2168
2169   if ($last_state) {
2170     record_failure($last_state) unless ($image_succeeded > 0);
2171   }
2172   $last_state = $name;
2173
2174   clearlog();
2175   report_performance();
2176
2177   start_timer($name);
2178   $image_succeeded = 0;
2179   $suppress_audit = 0;
2180 }
2181
2182 sub record_success($$$) {
2183   my ($name, $url, $base) = @_;
2184   if (defined($stats_successes{$name})) {
2185     $stats_successes{$name}++;
2186   } else {
2187     $stats_successes{$name} = 1;
2188   }
2189
2190   stop_timer ($name, 1);
2191   my $o = $current_state;
2192   $current_state = $name;
2193   save_recent_url ($url, $base);
2194   $current_state = $o;
2195   $image_succeeded = 1;
2196   clearlog();
2197 }
2198
2199
2200 sub record_failure($) {
2201   my ($name) = @_;
2202
2203   return if $image_succeeded;
2204
2205   stop_timer ($name, 0);
2206   if ($verbose_load && !$verbose_exec) {
2207
2208     if ($suppress_audit) {
2209       print STDERR "$progname: " . timestr() . "(audit log suppressed)\n";
2210       return;
2211     }
2212
2213     my $o = $current_state;
2214     $current_state = "DEBUG";
2215
2216     my $line =  "#" x 78;
2217     print STDERR "\n\n\n";
2218     print STDERR ("#" x 78) . "\n";
2219     print STDERR blurb() . "failed to get an image.  Full audit log:\n";
2220     print STDERR "\n";
2221     showlog();
2222     print STDERR ("-" x 78) . "\n";
2223     print STDERR "\n\n";
2224
2225     $current_state = $o;
2226   }
2227   $image_succeeded = 0;
2228 }
2229
2230
2231
2232 sub stats_of($) {
2233   my ($name) = @_;
2234   my $i = $stats_successes{$name};
2235   my $j = $stats_attempts{$name};
2236   $i = 0 unless $i;
2237   $j = 0 unless $j;
2238   return "" . ($j ? int($i * 100 / $j) : "0") . "%";
2239 }
2240
2241
2242 my $current_start_time = 0;
2243
2244 sub start_timer($) {
2245   my ($name) = @_;
2246   $current_start_time = time;
2247
2248   if (defined($stats_attempts{$name})) {
2249     $stats_attempts{$name}++;
2250   } else {
2251     $stats_attempts{$name} = 1;
2252   }
2253   if (!defined($stats_elapsed{$name})) {
2254     $stats_elapsed{$name} = 0;
2255   }
2256 }
2257
2258 sub stop_timer($$) {
2259   my ($name, $success) = @_;
2260   $stats_elapsed{$name} += time - $current_start_time;
2261 }
2262
2263
2264 my $last_report_time = 0;
2265 sub report_performance() {
2266
2267   return unless $verbose_warnings;
2268
2269   my $now = time;
2270   return unless ($now >= $last_report_time + $report_performance_interval);
2271   my $ot = $last_report_time;
2272   $last_report_time = $now;
2273
2274   return if ($ot == 0);
2275
2276   my $blurb = "$progname: " . timestr();
2277
2278   print STDERR "\n";
2279   print STDERR "${blurb}Current standings:\n";
2280
2281   foreach my $name (sort keys (%stats_attempts)) {
2282     my $try = $stats_attempts{$name};
2283     my $suc = $stats_successes{$name} || 0;
2284     my $pct = int($suc * 100 / $try);
2285     my $secs = $stats_elapsed{$name};
2286     my $secs_link = int($secs / $try);
2287     print STDERR sprintf ("$blurb   %-12s %4s (%d/%d);\t %2d secs/link\n",
2288                           "$name:", "$pct%", $suc, $try, $secs_link);
2289   }
2290 }
2291
2292
2293
2294 my $max_recent_images = 400;
2295 my $max_recent_sites  = 20;
2296 my @recent_images = ();
2297 my @recent_sites = ();
2298
2299 sub save_recent_url($$) {
2300   my ($url, $base) = @_;
2301
2302   return unless ($verbose_warnings);
2303
2304   $_ = $url;
2305   my ($site) = m@^http://([^ \t\n\r/:]+)@;
2306   return unless defined ($site);
2307
2308   if ($base eq $driftnet_magic || $base eq $local_magic) {
2309     $site = $base;
2310     @recent_images = ();
2311   }
2312
2313   my $done = 0;
2314   foreach (@recent_images) {
2315     if ($_ eq $url) {
2316       print STDERR blurb() . "WARNING: recently-duplicated image: $url" .
2317         " (on $base via $last_search)\n";
2318       $done = 1;
2319       last;
2320     }
2321   }
2322
2323   # suppress "duplicate site" warning via %warningless_sites.
2324   #
2325   if ($warningless_sites{$site}) {
2326     $done = 1;
2327   } elsif ($site =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
2328            $warningless_sites{$1}) {
2329     $done = 1;
2330   } elsif ($site =~ m@([^.]+\.[^.]+)$@ &&
2331            $warningless_sites{$1}) {
2332     $done = 1;
2333   }
2334
2335   if (!$done) {
2336     foreach (@recent_sites) {
2337       if ($_ eq $site) {
2338         print STDERR blurb() . "WARNING: recently-duplicated site: $site" .
2339         " ($url on $base via $last_search)\n";
2340         last;
2341       }
2342     }
2343   }
2344
2345   push @recent_images, $url;
2346   push @recent_sites,  $site;
2347   shift @recent_images if ($#recent_images >= $max_recent_images);
2348   shift @recent_sites  if ($#recent_sites  >= $max_recent_sites);
2349 }
2350
2351
2352 \f
2353 ##############################################################################
2354 #
2355 # other utilities
2356 #
2357 ##############################################################################
2358
2359 # Does %-decoding.
2360 #
2361 sub url_decode($) {
2362   ($_) = @_;
2363   tr/+/ /;
2364   s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
2365   return $_;
2366 }
2367
2368
2369 # Given the raw body of a GIF document, returns the dimensions of the image.
2370 #
2371 sub gif_size($) {
2372   my ($body) = @_;
2373   my $type = substr($body, 0, 6);
2374   my $s;
2375   return () unless ($type =~ /GIF8[7,9]a/);
2376   $s = substr ($body, 6, 10);
2377   my ($a,$b,$c,$d) = unpack ("C"x4, $s);
2378   return () unless defined ($d);
2379   return (($b<<8|$a), ($d<<8|$c));
2380 }
2381
2382 # Given the raw body of a JPEG document, returns the dimensions of the image.
2383 #
2384 sub jpeg_size($) {
2385   my ($body) = @_;
2386   my $i = 0;
2387   my $L = length($body);
2388
2389   my $c1 = substr($body, $i, 1); $i++;
2390   my $c2 = substr($body, $i, 1); $i++;
2391   return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
2392
2393   my $ch = "0";
2394   while (ord($ch) != 0xDA && $i < $L) {
2395     # Find next marker, beginning with 0xFF.
2396     while (ord($ch) != 0xFF) {
2397       return () if (length($body) <= $i);
2398       $ch = substr($body, $i, 1); $i++;
2399     }
2400     # markers can be padded with any number of 0xFF.
2401     while (ord($ch) == 0xFF) {
2402       return () if (length($body) <= $i);
2403       $ch = substr($body, $i, 1); $i++;
2404     }
2405
2406     # $ch contains the value of the marker.
2407     my $marker = ord($ch);
2408
2409     if (($marker >= 0xC0) &&
2410         ($marker <= 0xCF) &&
2411         ($marker != 0xC4) &&
2412         ($marker != 0xCC)) {  # it's a SOFn marker
2413       $i += 3;
2414       return () if (length($body) <= $i);
2415       my $s = substr($body, $i, 4); $i += 4;
2416       my ($a,$b,$c,$d) = unpack("C"x4, $s);
2417       return (($c<<8|$d), ($a<<8|$b));
2418
2419     } else {
2420       # We must skip variables, since FFs in variable names aren't
2421       # valid JPEG markers.
2422       return () if (length($body) <= $i);
2423       my $s = substr($body, $i, 2); $i += 2;
2424       my ($c1, $c2) = unpack ("C"x2, $s);
2425       my $length = ($c1 << 8) | $c2;
2426       return () if ($length < 2);
2427       $i += $length-2;
2428     }
2429   }
2430   return ();
2431 }
2432
2433 # Given the raw body of a PNG document, returns the dimensions of the image.
2434 #
2435 sub png_size($) {
2436   my ($body) = @_;
2437   return () unless ($body =~ m/^\211PNG\r/);
2438   my ($bits) = ($body =~ m/^.{12}(.{12})/s);
2439   return () unless defined ($bits);
2440   return () unless ($bits =~ /^IHDR/);
2441   my ($ign, $w, $h) = unpack("a4N2", $bits);
2442   return ($w, $h);
2443 }
2444
2445
2446 # Given the raw body of a GIF, JPEG, or PNG document, returns the dimensions
2447 # of the image.
2448 #
2449 sub image_size($) {
2450   my ($body) = @_;
2451   my ($w, $h) = gif_size ($body);
2452   if ($w && $h) { return ($w, $h); }
2453   ($w, $h) = jpeg_size ($body);
2454   if ($w && $h) { return ($w, $h); }
2455   return png_size ($body);
2456 }
2457
2458
2459 # returns the full path of the named program, or undef.
2460 #
2461 sub which($) {
2462   my ($prog) = @_;
2463   foreach (split (/:/, $ENV{PATH})) {
2464     if (-x "$_/$prog") {
2465       return $prog;
2466     }
2467   }
2468   return undef;
2469 }
2470
2471
2472 # Like rand(), but chooses numbers with a bell curve distribution.
2473 sub bellrand(;$) {
2474   ($_) = @_;
2475   $_ = 1.0 unless defined($_);
2476   $_ /= 3.0;
2477   return (rand($_) + rand($_) + rand($_));
2478 }
2479
2480
2481 sub exit_cleanup() {
2482   x_cleanup();
2483   print STDERR "$progname: exiting\n" if ($verbose_warnings);
2484   if (@pids_to_kill) {
2485     print STDERR blurb() . "killing: " . join(' ', @pids_to_kill) . "\n";
2486     kill ('TERM', @pids_to_kill);
2487   }
2488 }
2489
2490 sub signal_cleanup($) {
2491   my ($sig) = @_;
2492   print STDERR blurb() . (defined($sig)
2493                           ? "caught signal $sig."
2494                           : "exiting.")
2495                        . "\n"
2496     if ($verbose_exec || $verbose_warnings);
2497   exit 1;
2498 }
2499
2500
2501
2502 ##############################################################################
2503 #
2504 # Generating a list of urls only
2505 #
2506 ##############################################################################
2507
2508 sub url_only_output() {
2509   do {
2510     my ($base, $img) = pick_image;
2511     if ($img) {
2512       $base =~ s/ /%20/g;
2513       $img  =~ s/ /%20/g;
2514       print "$img $base\n";
2515     }
2516   } while (1);
2517 }
2518
2519 ##############################################################################
2520 #
2521 # Running as an xscreensaver module, or as a web page imagemap
2522 #
2523 ##############################################################################
2524
2525 my $image_ppm   = sprintf ("%s/webcollage-%08x",
2526                            ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2527                            rand(0xFFFFFFFF));
2528 my $image_tmp1  = sprintf ("%s/webcollage-1-%08x",
2529                            ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2530                            rand(0xFFFFFFFF));
2531 my $image_tmp2  = sprintf ("%s/webcollage-2-%08x",
2532                            ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2533                            rand(0xFFFFFFFF));
2534
2535 my $filter_cmd = undef;
2536 my $post_filter_cmd = undef;
2537 my $background = undef;
2538
2539 my @imagemap_areas = ();
2540 my $imagemap_html_tmp = undef;
2541 my $imagemap_jpg_tmp = undef;
2542
2543
2544 my $img_width;            # size of the image being generated.
2545 my $img_height;
2546
2547 my $delay = 2;
2548
2549 sub x_cleanup() {
2550   unlink $image_ppm, $image_tmp1, $image_tmp2;
2551   unlink $imagemap_html_tmp, $imagemap_jpg_tmp
2552     if (defined ($imagemap_html_tmp));
2553 }
2554
2555
2556 # Like system, but prints status about exit codes, and kills this process
2557 # with whatever signal killed the sub-process, if any.
2558 #
2559 sub nontrapping_system(@) {
2560   $! = 0;
2561
2562   $_ = join(" ", @_);
2563   s/\"[^\"]+\"/\"...\"/g;
2564
2565   LOG ($verbose_exec, "executing \"$_\"");
2566
2567   my $rc = system @_;
2568
2569   if ($rc == 0) {
2570     LOG ($verbose_exec, "subproc exited normally.");
2571   } elsif (($rc & 0xff) == 0) {
2572     $rc >>= 8;
2573     LOG ($verbose_exec, "subproc exited with status $rc.");
2574   } else {
2575     if ($rc & 0x80) {
2576       LOG ($verbose_exec, "subproc dumped core.");
2577       $rc &= ~0x80;
2578     }
2579     LOG ($verbose_exec, "subproc died with signal $rc.");
2580     # die that way ourselves.
2581     kill $rc, $$;
2582   }
2583
2584   return $rc;
2585 }
2586
2587
2588 # Given the URL of a GIF, JPEG, or PNG image, and the body of that image,
2589 # writes a PPM to the given output file.  Returns the width/height of the
2590 # image if successful.
2591 #
2592 sub image_to_pnm($$$) {
2593   my ($url, $body, $output) = @_;
2594   my ($cmd, $cmd2, $w, $h);
2595
2596   if ((@_ = gif_size ($body))) {
2597     ($w, $h) = @_;
2598     $cmd = "giftopnm";
2599   } elsif ((@_ = jpeg_size ($body))) {
2600     ($w, $h) = @_;
2601     $cmd = "djpeg";
2602   } elsif ((@_ = png_size ($body))) {
2603     ($w, $h) = @_;
2604     $cmd = "pngtopnm";
2605   } else {
2606     LOG (($verbose_pbm || $verbose_load),
2607          "not a GIF, JPG, or PNG" .
2608          (($body =~ m@<(base|html|head|body|script|table|a href)\b@i)
2609           ? " (looks like HTML)" : "") .
2610          ": $url");
2611     $suppress_audit = 1;
2612     return ();
2613   }
2614
2615   $cmd2 = "exec $cmd";        # yes, this really is necessary.  if we don't
2616                               # do this, the process doesn't die properly.
2617   if (!$verbose_pbm) {
2618     #
2619     # We get a "giftopnm: got a 'Application Extension' extension"
2620     # warning any time it's an animgif.
2621     #
2622     # Note that "giftopnm: EOF / read error on image data" is not
2623     # always a fatal error -- sometimes the image looks fine anyway.
2624     #
2625     $cmd2 .= " 2>/dev/null";
2626   }
2627
2628   # There exist corrupted GIF and JPEG files that can make giftopnm and
2629   # djpeg lose their minds and go into a loop.  So this gives those programs
2630   # a small timeout -- if they don't complete in time, kill them.
2631   #
2632   my $pid;
2633   @_ = eval {
2634     my $timed_out;
2635
2636     local $SIG{ALRM}  = sub {
2637       LOG ($verbose_pbm,
2638            "timed out ($cvt_timeout) for $cmd on \"$url\" in pid $pid");
2639       kill ('TERM', $pid) if ($pid);
2640       $timed_out = 1;
2641       $body = undef;
2642     };
2643
2644     if (($pid = open(PIPE, "| $cmd2 > $output"))) {
2645       $timed_out = 0;
2646       alarm $cvt_timeout;
2647       print PIPE $body;
2648       $body = undef;
2649       close PIPE;
2650
2651       LOG ($verbose_exec, "awaiting $pid");
2652       waitpid ($pid, 0);
2653       LOG ($verbose_exec, "$pid completed");
2654
2655       my $size = (stat($output))[7];
2656       $size = -1 unless defined($size);
2657       if ($size < 5) {
2658         LOG ($verbose_pbm, "$cmd on ${w}x$h \"$url\" failed ($size bytes)");
2659         return ();
2660       }
2661
2662       LOG ($verbose_pbm, "created ${w}x$h $output ($cmd)");
2663       return ($w, $h);
2664     } else {
2665       print STDERR blurb() . "$cmd failed: $!\n";
2666       return ();
2667     }
2668   };
2669   die if ($@ && $@ ne "alarm\n");       # propagate errors
2670   if ($@) {
2671     # timed out
2672     $body = undef;
2673     return ();
2674   } else {
2675     # didn't
2676     alarm 0;
2677     $body = undef;
2678     return @_;
2679   }
2680 }
2681
2682
2683 # Same as the "ppmmake" command: creates a solid-colored PPM.
2684 # Does not understand the rgb.txt color names except "black" and "white".
2685 #
2686 sub ppmmake($$$$) {
2687   my ($outfile, $bgcolor, $w, $h) = @_;
2688
2689   my ($r, $g, $b);
2690   if ($bgcolor =~ m/^\#?([\dA-F][\dA-F])([\dA-F][\dA-F])([\dA-F][\dA-F])$/i ||
2691       $bgcolor =~ m/^\#?([\dA-F])([\dA-F])([\dA-F])$/i) {
2692     ($r, $g, $b) = (hex($1), hex($2), hex($3));
2693   } elsif ($bgcolor =~ m/^black$/i) {
2694     ($r, $g, $b) = (0, 0, 0);
2695   } elsif ($bgcolor =~ m/^white$/i) {
2696     ($r, $g, $b) = (0xFF, 0xFF, 0xFF);
2697   } else {
2698     error ("unparsable color name: $bgcolor");
2699   }
2700
2701   my $pixel = pack('CCC', $r, $g, $b);
2702   my $bits = "P6\n$w $h\n255\n" . ($pixel x ($w * $h));
2703
2704   local *OUT;
2705   open (OUT, ">$outfile") || error ("$outfile: $!");
2706   print OUT $bits;
2707   close OUT;
2708 }
2709
2710
2711 sub pick_root_displayer() {
2712   my @names = ();
2713
2714   if ($cocoa_p) {
2715     # see "xscreensaver/hacks/webcollage-cocoa.m"
2716     return "echo COCOA LOAD ";
2717   }
2718
2719   foreach my $cmd (@root_displayers) {
2720     $_ = $cmd;
2721     my ($name) = m/^([^ ]+)/;
2722     push @names, "\"$name\"";
2723     LOG ($verbose_exec, "looking for $name...");
2724     foreach my $dir (split (/:/, $ENV{PATH})) {
2725       LOG ($verbose_exec, "  checking $dir/$name");
2726       return $cmd if (-x "$dir/$name");
2727     }
2728   }
2729
2730   $names[$#names] = "or " . $names[$#names];
2731   error "none of: " . join (", ", @names) . " were found on \$PATH.";
2732 }
2733
2734
2735 my $ppm_to_root_window_cmd = undef;
2736
2737
2738 sub x_or_pbm_output($) {
2739   my ($window_id) = @_;
2740
2741   # Check for our helper program, to see whether we need to use PPM pipelines.
2742   #
2743   $_ = "webcollage-helper";
2744   if (defined ($webcollage_helper) || which ($_)) {
2745     $webcollage_helper = $_ unless (defined($webcollage_helper));
2746     LOG ($verbose_pbm, "found \"$webcollage_helper\"");
2747     $webcollage_helper .= " -v";
2748   } else {
2749     LOG (($verbose_pbm || $verbose_load), "no $_ program");
2750   }
2751
2752   if ($cocoa_p && !defined ($webcollage_helper)) {
2753     error ("webcollage-helper not found in Cocoa-mode!");
2754   }
2755
2756
2757   # make sure the various programs we execute exist, right up front.
2758   #
2759   my @progs = ();
2760
2761   if (!defined($webcollage_helper)) {
2762     # Only need these others if we don't have the helper.
2763     @progs = (@progs,
2764               "giftopnm", "pngtopnm", "djpeg",
2765               "pnmpaste", "pnmscale", "pnmcut");
2766   }
2767
2768   foreach (@progs) {
2769     which ($_) || error "$_ not found on \$PATH.";
2770   }
2771
2772   # find a root-window displayer program.
2773   #
2774   if (!$no_output_p) {
2775     $ppm_to_root_window_cmd = pick_root_displayer();
2776   }
2777
2778   if (defined ($window_id)) {
2779     error ("-window-id only works if xscreensaver-getimage is installed")
2780       unless ($ppm_to_root_window_cmd =~ m/^xscreensaver-getimage\b/);
2781
2782     error ("unparsable window id: $window_id")
2783       unless ($window_id =~ m/^\d+$|^0x[\da-f]+$/i);
2784     $ppm_to_root_window_cmd =~ s/--?root\b/$window_id/ ||
2785       error ("unable to munge displayer: $ppm_to_root_window_cmd");
2786   }
2787
2788   if (!$img_width || !$img_height) {
2789
2790     if (!defined ($window_id) &&
2791         defined ($ENV{XSCREENSAVER_WINDOW})) {
2792       $window_id = $ENV{XSCREENSAVER_WINDOW};
2793     }
2794
2795     if (!defined ($window_id)) {
2796       $_ = "xdpyinfo";
2797       which ($_) || error "$_ not found on \$PATH.";
2798       $_ = `$_`;
2799       ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
2800       if (!defined($img_height)) {
2801         error "xdpyinfo failed.";
2802       }
2803     } else {  # we have a window id
2804       $_ = "xwininfo";
2805       which ($_) || error "$_ not found on \$PATH.";
2806       $_ .= " -id $window_id";
2807       $_ = `$_`;
2808       ($img_width, $img_height) = m/^\s*Width:\s*(\d+)\n\s*Height:\s*(\d+)\n/m;
2809
2810       if (!defined($img_height)) {
2811         error "xwininfo failed.";
2812       }
2813     }
2814   }
2815
2816   my $bgcolor = "#000000";
2817   my $bgimage = undef;
2818
2819   if ($background) {
2820     if ($background =~ m/^\#[0-9a-f]+$/i) {
2821       $bgcolor = $background;
2822
2823     } elsif (-r $background) {
2824       $bgimage = $background;
2825
2826     } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
2827       error "not a color or readable file: $background";
2828
2829     } else {
2830       # default to assuming it's a color
2831       $bgcolor = $background;
2832     }
2833   }
2834
2835   # Create the sold-colored base image.
2836   #
2837   LOG ($verbose_pbm, "creating base image: ${img_width}x${img_height}");
2838   $_ = ppmmake ($image_ppm, $bgcolor, $img_width, $img_height);
2839
2840   # Paste the default background image in the middle of it.
2841   #
2842   if ($bgimage) {
2843     my ($iw, $ih);
2844
2845     my $body = "";
2846     local *IMG;
2847     open(IMG, "<$bgimage") || error "couldn't open $bgimage: $!";
2848     my $cmd;
2849     while (<IMG>) { $body .= $_; }
2850     close (IMG);
2851
2852     if ((@_ = gif_size ($body))) {
2853       ($iw, $ih) = @_;
2854       $cmd = "giftopnm |";
2855
2856     } elsif ((@_ = jpeg_size ($body))) {
2857       ($iw, $ih) = @_;
2858       $cmd = "djpeg |";
2859
2860     } elsif ((@_ = png_size ($body))) {
2861       ($iw, $ih) = @_;
2862       $cmd = "pngtopnm |";
2863
2864     } elsif ($body =~ m/^P\d\n(\d+) (\d+)\n/) {
2865       $iw = $1;
2866       $ih = $2;
2867       $cmd = "";
2868
2869     } else {
2870       error "$bgimage is not a GIF, JPEG, PNG, or PPM.";
2871     }
2872
2873     my $x = int (($img_width  - $iw) / 2);
2874     my $y = int (($img_height - $ih) / 2);
2875     LOG ($verbose_pbm,
2876          "pasting $bgimage (${iw}x$ih) into base image at $x,$y");
2877
2878     $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
2879     open (IMG, "| $cmd") || error "running $cmd: $!";
2880     print IMG $body;
2881     $body = undef;
2882     close (IMG);
2883     LOG ($verbose_exec, "subproc exited normally.");
2884     rename ($image_tmp1, $image_ppm) ||
2885       error "renaming $image_tmp1 to $image_ppm: $!";
2886   }
2887
2888   clearlog();
2889
2890   while (1) {
2891     my ($base, $img) = pick_image();
2892     my $source = $current_state;
2893     $current_state = "loadimage";
2894     if ($img) {
2895       my ($headers, $body) = get_document ($img, $base);
2896       if ($body) {
2897         paste_image ($base, $img, $body, $source);
2898         $body = undef;
2899       }
2900     }
2901     $current_state = "idle";
2902     $load_method = "none";
2903
2904     unlink $image_tmp1, $image_tmp2;
2905     sleep $delay;
2906   }
2907 }
2908
2909 sub paste_image($$$$) {
2910   my ($base, $img, $body, $source) = @_;
2911
2912   $current_state = "paste";
2913
2914   $suppress_audit = 0;
2915
2916   LOG ($verbose_pbm, "got $img (" . length($body) . ")");
2917
2918   my ($iw, $ih);
2919
2920   # If we are using the webcollage-helper, then we do not need to convert this
2921   # image to a PPM.  But, if we're using a filter command, we still must, since
2922   # that's what the filters expect (webcollage-helper can read PPMs, so that's
2923   # fine.)
2924   #
2925   if (defined ($webcollage_helper) &&
2926       !defined ($filter_cmd)) {
2927
2928     ($iw, $ih) = image_size ($body);
2929     if (!$iw || !$ih) {
2930       LOG (($verbose_pbm || $verbose_load),
2931            "not a GIF, JPG, or PNG" .
2932            (($body =~ m@<(base|html|head|body|script|table|a href)>@i)
2933             ? " (looks like HTML)" : "") .
2934            ": $img");
2935       $suppress_audit = 1;
2936       $body = undef;
2937       return 0;
2938     }
2939
2940     local *OUT;
2941     open (OUT, ">$image_tmp1") || error ("writing $image_tmp1: $!");
2942     print OUT $body || error ("writing $image_tmp1: $!");
2943     close OUT || error ("writing $image_tmp1: $!");
2944
2945   } else {
2946     ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
2947     $body = undef;
2948     if (!$iw || !$ih) {
2949       LOG ($verbose_pbm, "unable to make PBM from $img");
2950       return 0;
2951     }
2952   }
2953
2954   record_success ($load_method, $img, $base);
2955
2956
2957   my $ow = $iw;  # used only for error messages
2958   my $oh = $ih;
2959
2960   # don't just tack this onto the front of the pipeline -- we want it to
2961   # be able to change the size of the input image.
2962   #
2963   if ($filter_cmd) {
2964     LOG ($verbose_pbm, "running $filter_cmd");
2965
2966     my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
2967     if ($rc != 0) {
2968       LOG(($verbose_pbm || $verbose_load), "failed command: \"$filter_cmd\"");
2969       LOG(($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
2970       return;
2971     }
2972     rename ($image_tmp2, $image_tmp1);
2973
2974     # re-get the width/height in case the filter resized it.
2975     local *IMG;
2976     open(IMG, "<$image_tmp1") || return 0;
2977     $_ = <IMG>;
2978     $_ = <IMG>;
2979     ($iw, $ih) = m/^(\d+) (\d+)$/;
2980     close (IMG);
2981     return 0 unless ($iw && $ih);
2982   }
2983
2984   my $target_w = $img_width;   # max rectangle into which the image must fit
2985   my $target_h = $img_height;
2986
2987   my $cmd = "";
2988   my $scale = 1.0;
2989
2990
2991   # Usually scale the image to fit on the screen -- but sometimes scale it
2992   # to fit on half or a quarter of the screen.  (We do this by reducing the
2993   # size of the target rectangle.)  Note that the image is not merely scaled
2994   # to fit; we instead cut the image in half repeatedly until it fits in the
2995   # target rectangle -- that gives a wider distribution of sizes.
2996   #
2997   if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; } # reduce target rect
2998   if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
2999
3000   if ($iw > $target_w || $ih > $target_h) {
3001     while ($iw > $target_w ||
3002            $ih > $target_h) {
3003       $iw = int($iw / 2);
3004       $ih = int($ih / 2);
3005       $scale /= 2;
3006     }
3007     if ($iw <= 10 || $ih <= 10) {
3008       LOG ($verbose_pbm, "scaling to ${iw}x$ih would have been bogus.");
3009       return 0;
3010     }
3011
3012     LOG ($verbose_pbm, "scaling to ${iw}x$ih ($scale)");
3013
3014     $cmd .= " | pnmscale -xsize $iw -ysize $ih";
3015   }
3016
3017
3018   my $src = $image_tmp1;
3019
3020   my $crop_x = 0;     # the sub-rectangle of the image
3021   my $crop_y = 0;     # that we will actually paste.
3022   my $crop_w = $iw;
3023   my $crop_h = $ih;
3024
3025   # The chance that we will randomly crop out a section of an image starts
3026   # out fairly low, but goes up for images that are very large, or images
3027   # that have ratios that make them look like banners (we try to avoid
3028   # banner images entirely, but they slip through when the IMG tags didn't
3029   # have WIDTH and HEIGHT specified.)
3030   #
3031   my $crop_chance = 0.2;
3032   if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
3033     $crop_chance += 0.2;
3034   }
3035   if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
3036     $crop_chance += 0.2;
3037   }
3038   if ($min_ratio && ($iw * $min_ratio) > $ih) {
3039     $crop_chance += 0.7;
3040   }
3041
3042   if ($crop_chance > 0.1) {
3043     LOG ($verbose_pbm, "crop chance: $crop_chance");
3044   }
3045
3046   if (rand() < $crop_chance) {
3047
3048     my $ow = $crop_w;
3049     my $oh = $crop_h;
3050
3051     if ($crop_w > $min_width) {
3052       # if it's a banner, select the width linearly.
3053       # otherwise, select a bell.
3054       my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
3055                ? rand()
3056                : bellrand());
3057       $crop_w = $min_width + int ($r * ($crop_w - $min_width));
3058       $crop_x = int (rand() * ($ow - $crop_w));
3059     }
3060     if ($crop_h > $min_height) {
3061       # height always selects as a bell.
3062       $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
3063       $crop_y = int (rand() * ($oh - $crop_h));
3064     }
3065
3066     if ($crop_x != 0   || $crop_y != 0 ||
3067         $crop_w != $iw || $crop_h != $ih) {
3068       LOG ($verbose_pbm,
3069            "randomly cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
3070     }
3071   }
3072
3073   # Where the image should logically land -- this might be negative.
3074   #
3075   my $x = int((rand() * ($img_width  + $crop_w/2)) - $crop_w*3/4);
3076   my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
3077
3078   # if we have chosen to paste the image outside of the rectangle of the
3079   # screen, then we need to crop it.
3080   #
3081   if ($x < 0 ||
3082       $y < 0 ||
3083       $x + $crop_w > $img_width ||
3084       $y + $crop_h > $img_height) {
3085
3086     LOG ($verbose_pbm,
3087          "cropping for effective paste of ${crop_w}x$crop_h \@ $x,$y");
3088
3089     if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
3090     if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
3091
3092     if ($x + $crop_w >= $img_width)  { $crop_w = $img_width  - $x - 1; }
3093     if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
3094   }
3095
3096   # If any cropping needs to happen, add pnmcut.
3097   #
3098   if ($crop_x != 0   || $crop_y != 0 ||
3099       $crop_w != $iw || $crop_h != $ih) {
3100     $iw = $crop_w;
3101     $ih = $crop_h;
3102     $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
3103     LOG ($verbose_pbm, "cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
3104   }
3105
3106   LOG ($verbose_pbm, "pasting ${iw}x$ih \@ $x,$y in $image_ppm");
3107
3108   $cmd .= " | pnmpaste - $x $y $image_ppm";
3109
3110   $cmd =~ s@^ *\| *@@;
3111
3112   if (defined ($webcollage_helper)) {
3113     $cmd = "$webcollage_helper $image_tmp1 $image_ppm " .
3114                               "$scale $opacity " .
3115                               "$crop_x $crop_y $x $y " .
3116                               "$iw $ih";
3117     $_ = $cmd;
3118
3119   } else {
3120     # use a PPM pipeline
3121     $_ = "($cmd)";
3122     $_ .= " < $image_tmp1 > $image_tmp2";
3123   }
3124
3125   if ($verbose_pbm) {
3126     $_ = "($_) 2>&1 | sed s'/^/" . blurb() . "/'";
3127   } else {
3128     $_ .= " 2> /dev/null";
3129   }
3130
3131   my $rc = nontrapping_system ($_);
3132
3133   if (defined ($webcollage_helper) && -z $image_ppm) {
3134     LOG (1, "failed command: \"$cmd\"");
3135     print STDERR "\naudit log:\n\n\n";
3136     print STDERR ("#" x 78) . "\n";
3137     print STDERR blurb() . "$image_ppm has zero size\n";
3138     showlog();
3139     print STDERR "\n\n";
3140     exit (1);
3141   }
3142
3143   if ($rc != 0) {
3144     LOG (($verbose_pbm || $verbose_load), "failed command: \"$cmd\"");
3145     LOG (($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
3146     return;
3147   }
3148
3149   if (!defined ($webcollage_helper)) {
3150     rename ($image_tmp2, $image_ppm) || return;
3151   }
3152
3153   my $target = "$image_ppm";
3154
3155   # don't just tack this onto the end of the pipeline -- we don't want it
3156   # to end up in $image_ppm, because we don't want the results to be
3157   # cumulative.
3158   #
3159   if ($post_filter_cmd) {
3160
3161     my $cmd;
3162
3163     $target = $image_tmp1;
3164     if (!defined ($webcollage_helper)) {
3165       $cmd = "($post_filter_cmd) < $image_ppm > $target";
3166     } else {
3167       # Blah, my scripts need the JPEG data, but some other folks need
3168       # the PPM data -- what to do?  Ignore the problem, that's what!
3169 #     $cmd = "djpeg < $image_ppm | ($post_filter_cmd) > $target";
3170       $cmd = "($post_filter_cmd) < $image_ppm > $target";
3171     }
3172
3173     $rc = nontrapping_system ($cmd);
3174     if ($rc != 0) {
3175       LOG ($verbose_pbm, "filter failed: \"$post_filter_cmd\"\n");
3176       return;
3177     }
3178   }
3179
3180   if (!$no_output_p) {
3181     my $tsize = (stat($target))[7];
3182     if ($tsize > 200) {
3183       $cmd = "$ppm_to_root_window_cmd $target";
3184
3185       # xv seems to hate being killed.  it tends to forget to clean
3186       # up after itself, and leaves windows around and colors allocated.
3187       # I had this same problem with vidwhacker, and I'm not entirely
3188       # sure what I did to fix it.  But, let's try this: launch xv
3189       # in the background, so that killing this process doesn't kill it.
3190       # it will die of its own accord soon enough.  So this means we
3191       # start pumping bits to the root window in parallel with starting
3192       # the next network retrieval, which is probably a better thing
3193       # to do anyway.
3194       #
3195       $cmd .= " &";
3196
3197       $rc = nontrapping_system ($cmd);
3198
3199       if ($rc != 0) {
3200         LOG (($verbose_pbm || $verbose_load), "display failed: \"$cmd\"");
3201         return;
3202       }
3203
3204     } else {
3205       LOG ($verbose_pbm, "$target size is $tsize");
3206     }
3207   }
3208
3209   $source .= "-" . stats_of($source);
3210   print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n"
3211     if ($verbose_imgmap);
3212   if ($imagemap_base) {
3213     update_imagemap ($base, $x, $y, $iw, $ih,
3214                      $image_ppm, $img_width, $img_height);
3215   }
3216
3217   clearlog();
3218
3219   return 1;
3220 }
3221
3222
3223 sub update_imagemap($$$$$$$$) {
3224   my ($url, $x, $y, $w, $h, $image_ppm, $image_width, $image_height) = @_;
3225
3226   $current_state = "imagemap";
3227
3228   my $max_areas = 200;
3229
3230   $url = html_quote ($url);
3231   my $x2 = $x + $w;
3232   my $y2 = $y + $h;
3233   my $area = "<AREA SHAPE=RECT COORDS=\"$x,$y,$x2,$y2\" HREF=\"$url\">";
3234   unshift @imagemap_areas, $area;       # put one on the front
3235   if ($#imagemap_areas >= $max_areas) {
3236     pop @imagemap_areas;                # take one off the back.
3237   }
3238
3239   LOG ($verbose_pbm, "area: $x,$y,$x2,$y2 (${w}x$h)");
3240
3241   my $map_name = $imagemap_base;
3242   $map_name =~ s@^.*/@@;
3243   $map_name = 'collage' if ($map_name eq '');
3244
3245   my $imagemap_html = $imagemap_base . ".html";
3246   my $imagemap_jpg  = $imagemap_base . ".jpg";
3247
3248   if (!defined ($imagemap_html_tmp)) {
3249     $imagemap_html_tmp = $imagemap_html . sprintf (".%08x", rand(0xffffffff));
3250     $imagemap_jpg_tmp  = $imagemap_jpg  . sprintf (".%08x", rand(0xffffffff));
3251   }
3252
3253   # Read the imagemap html file (if any) to get a template.
3254   #
3255   my $template_html = '';
3256   {
3257     local *IN;
3258     if (open (IN, "<$imagemap_html")) {
3259       while (<IN>) { $template_html .= $_; }
3260       close IN;
3261       LOG ($verbose_pbm, "read template $imagemap_html");
3262     }
3263
3264     if ($template_html =~ m/^\s*$/s) {
3265       $template_html = ("<MAP NAME=\"$map_name\"></MAP>\n" .
3266                         "<IMG SRC=\"$imagemap_base.jpg\"" .
3267                         " USEMAP=\"$map_name\">\n");
3268       LOG ($verbose_pbm, "created dummy template");
3269     }
3270   }
3271
3272   # Write the jpg to a tmp file
3273   #
3274   {
3275     my $cmd;
3276     if (defined ($webcollage_helper)) {
3277       $cmd = "cp -p $image_ppm $imagemap_jpg_tmp";
3278     } else {
3279       $cmd = "cjpeg < $image_ppm > $imagemap_jpg_tmp";
3280     }
3281     my $rc = nontrapping_system ($cmd);
3282     if ($rc != 0) {
3283       error ("imagemap jpeg failed: \"$cmd\"\n");
3284     }
3285   }
3286
3287   # Write the html to a tmp file
3288   #
3289   {
3290     my $body = $template_html;
3291     my $areas = join ("\n\t", @imagemap_areas);
3292     my $map = ("<MAP NAME=\"$map_name\">\n\t$areas\n</MAP>");
3293     my $img = ("<IMG SRC=\"$imagemap_base.jpg\" " .
3294                "BORDER=0 " .
3295                "WIDTH=$image_width HEIGHT=$image_height " .
3296                "USEMAP=\"#$map_name\">");
3297     $body =~ s@(<MAP\s+NAME=\"[^\"]*\"\s*>).*?(</MAP>)@$map@is;
3298     $body =~ s@<IMG\b[^<>]*\bUSEMAP\b[^<>]*>@$img@is;
3299
3300     # if there are magic webcollage spans in the html, update those too.
3301     #
3302     {
3303       my @st = stat ($imagemap_jpg_tmp);
3304       my $date = strftime("%d-%b-%Y %l:%M:%S %p %Z", localtime($st[9]));
3305       my $size = int(($st[7] / 1024) + 0.5) . "K";
3306       $body =~ s@(<SPAN\s+CLASS=\"webcollage_date\">).*?(</SPAN>)@$1$date$2@si;
3307       $body =~ s@(<SPAN\s+CLASS=\"webcollage_size\">).*?(</SPAN>)@$1$size$2@si;
3308     }
3309
3310     local *OUT;
3311     open (OUT, ">$imagemap_html_tmp") || error ("$imagemap_html_tmp: $!");
3312     print OUT $body                   || error ("$imagemap_html_tmp: $!");
3313     close OUT                         || error ("$imagemap_html_tmp: $!");
3314     LOG ($verbose_pbm, "wrote $imagemap_html_tmp");
3315   }
3316
3317   # Rename the two tmp files to the real files
3318   #
3319   rename ($imagemap_html_tmp, $imagemap_html) ||
3320     error "renaming $imagemap_html_tmp to $imagemap_html";
3321   LOG ($verbose_pbm, "wrote $imagemap_html");
3322   rename ($imagemap_jpg_tmp,  $imagemap_jpg) ||
3323     error "renaming $imagemap_jpg_tmp to $imagemap_jpg";
3324   LOG ($verbose_pbm, "wrote $imagemap_jpg");
3325 }
3326
3327
3328 sub init_signals() {
3329
3330   $SIG{HUP}  = \&signal_cleanup;
3331   $SIG{INT}  = \&signal_cleanup;
3332   $SIG{QUIT} = \&signal_cleanup;
3333   $SIG{ABRT} = \&signal_cleanup;
3334   $SIG{KILL} = \&signal_cleanup;
3335   $SIG{TERM} = \&signal_cleanup;
3336
3337   # Need this so that if giftopnm dies, we don't die.
3338   $SIG{PIPE} = 'IGNORE';
3339 }
3340
3341 END { exit_cleanup(); }
3342
3343
3344 sub main() {
3345   $| = 1;
3346   srand(time ^ $$);
3347
3348   my $verbose = 0;
3349   my $dict;
3350   my $driftnet_cmd = 0;
3351
3352   $current_state = "init";
3353   $load_method = "none";
3354
3355   my $root_p = 0;
3356   my $window_id = undef;
3357
3358   # historical suckage: the environment variable name is lower case.
3359   $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
3360
3361   while ($_ = $ARGV[0]) {
3362     shift @ARGV;
3363     if ($_ eq "-display" ||
3364         $_ eq "-displ" ||
3365         $_ eq "-disp" ||
3366         $_ eq "-dis" ||
3367         $_ eq "-dpy" ||
3368         $_ eq "-d") {
3369       $ENV{DISPLAY} = shift @ARGV;
3370     } elsif ($_ eq "-root") {
3371       $root_p = 1;
3372     } elsif ($_ eq "-window-id" || $_ eq "--window-id") {
3373       $window_id = shift @ARGV;
3374       $root_p = 1;
3375     } elsif ($_ eq "-no-output") {
3376       $no_output_p = 1;
3377     } elsif ($_ eq "-urls-only") {
3378       $urls_only_p = 1;
3379       $no_output_p = 1;
3380     } elsif ($_ eq "-cocoa") {
3381       $cocoa_p = 1;
3382     } elsif ($_ eq "-imagemap") {
3383       $imagemap_base = shift @ARGV;
3384       $no_output_p = 1;
3385     } elsif ($_ eq "-verbose") {
3386       $verbose++;
3387     } elsif (m/^-v+$/) {
3388       $verbose += length($_)-1;
3389     } elsif ($_ eq "-delay") {
3390       $delay = shift @ARGV;
3391     } elsif ($_ eq "-timeout") {
3392       $http_timeout = shift @ARGV;
3393     } elsif ($_ eq "-filter") {
3394       $filter_cmd = shift @ARGV;
3395     } elsif ($_ eq "-filter2") {
3396       $post_filter_cmd = shift @ARGV;
3397     } elsif ($_ eq "-background" || $_ eq "-bg") {
3398       $background = shift @ARGV;
3399     } elsif ($_ eq "-size") {
3400       $_ = shift @ARGV;
3401       if (m@^(\d+)x(\d+)$@) {
3402         $img_width = $1;
3403         $img_height = $2;
3404       } else {
3405         error "argument to \"-size\" must be of the form \"640x400\"";
3406       }
3407     } elsif ($_ eq "-proxy" || $_ eq "-http-proxy") {
3408       $http_proxy = shift @ARGV;
3409     } elsif ($_ eq "-dictionary" || $_ eq "-dict") {
3410       $dict = shift @ARGV;
3411     } elsif ($_ eq "-opacity") {
3412       $opacity = shift @ARGV;
3413       error ("opacity must be between 0.0 and 1.0")
3414         if ($opacity <= 0 || $opacity > 1);
3415     } elsif ($_ eq "-driftnet" || $_ eq "--driftnet") {
3416       @search_methods = ( 100, "driftnet", \&pick_from_driftnet );
3417       if (! ($ARGV[0] =~ m/^-/)) {
3418         $driftnet_cmd = shift @ARGV;
3419       } else {
3420         $driftnet_cmd = $default_driftnet_cmd;
3421       }
3422     } elsif ($_ eq "-directory" || $_ eq "--directory") {
3423       @search_methods = ( 100, "local", \&pick_from_local_dir );
3424       if (! ($ARGV[0] =~ m/^-/)) {
3425         $local_dir = shift @ARGV;
3426       } else {
3427         error ("local directory path must be set")
3428       }
3429     } elsif ($_ eq "-debug" || $_ eq "--debug") {
3430       my $which = shift @ARGV;
3431       my @rest = @search_methods;
3432       my $ok = 0;
3433       while (@rest) {
3434         my $pct  = shift @rest;
3435         my $name = shift @rest;
3436         my $tfn  = shift @rest;
3437
3438         if ($name eq $which) {
3439           @search_methods = (100, $name, $tfn);
3440           $ok = 1;
3441           last;
3442         }
3443       }
3444       error "no such search method as \"$which\"" unless ($ok);
3445       LOG (1, "DEBUG: using only \"$which\"");
3446
3447     } else {
3448       print STDERR "$copyright\nusage: $progname " .
3449               "[-root] [-display dpy] [-verbose] [-debug which]\n" .
3450         "\t\t  [-timeout secs] [-delay secs] [-size WxH]\n" .
3451         "\t\t  [-no-output] [-urls-only] [-imagemap filename]\n" .
3452         "\t\t  [-filter cmd] [-filter2 cmd] [-background color]\n" .
3453         "\t\t  [-dictionary dictionary-file] [-http-proxy host[:port]]\n" .
3454         "\t\t  [-driftnet [driftnet-program-and-args]]\n" .
3455         "\t\t  [-directory local-image-directory]\n" .
3456         "\n";
3457       exit 1;
3458     }
3459   }
3460
3461   if ($http_proxy && $http_proxy eq "") {
3462     $http_proxy = undef;
3463   }
3464   if ($http_proxy && $http_proxy =~ m@^http://([^/]*)/?$@ ) {
3465     # historical suckage: allow "http://host:port" as well as "host:port".
3466     $http_proxy = $1;
3467   }
3468
3469   if (!$root_p && !$no_output_p && !$cocoa_p) {
3470     print STDERR $copyright;
3471     error "the -root argument is mandatory (for now.)";
3472   }
3473
3474   if (!$no_output_p && !$cocoa_p && !$ENV{DISPLAY}) {
3475     error "\$DISPLAY is not set.";
3476   }
3477
3478
3479   if ($verbose == 1) {
3480     $verbose_imgmap   = 1;
3481     $verbose_warnings = 1;
3482
3483   } elsif ($verbose == 2) {
3484     $verbose_imgmap   = 1;
3485     $verbose_warnings = 1;
3486     $verbose_load     = 1;
3487
3488   } elsif ($verbose == 3) {
3489     $verbose_imgmap   = 1;
3490     $verbose_warnings = 1;
3491     $verbose_load     = 1;
3492     $verbose_filter   = 1;
3493
3494   } elsif ($verbose == 4) {
3495     $verbose_imgmap   = 1;
3496     $verbose_warnings = 1;
3497     $verbose_load     = 1;
3498     $verbose_filter   = 1;
3499     $verbose_net      = 1;
3500
3501   } elsif ($verbose == 5) {
3502     $verbose_imgmap   = 1;
3503     $verbose_warnings = 1;
3504     $verbose_load     = 1;
3505     $verbose_filter   = 1;
3506     $verbose_net      = 1;
3507     $verbose_pbm      = 1;
3508
3509   } elsif ($verbose == 6) {
3510     $verbose_imgmap   = 1;
3511     $verbose_warnings = 1;
3512     $verbose_load     = 1;
3513     $verbose_filter   = 1;
3514     $verbose_net      = 1;
3515     $verbose_pbm      = 1;
3516     $verbose_http     = 1;
3517
3518   } elsif ($verbose >= 7) {
3519     $verbose_imgmap   = 1;
3520     $verbose_warnings = 1;
3521     $verbose_load     = 1;
3522     $verbose_filter   = 1;
3523     $verbose_net      = 1;
3524     $verbose_pbm      = 1;
3525     $verbose_http     = 1;
3526     $verbose_exec     = 1;
3527   }
3528
3529   if ($dict) {
3530     error ("$dict does not exist") unless (-f $dict);
3531     $wordlist = $dict;
3532   } else {
3533     pick_dictionary();
3534   }
3535
3536   if ($imagemap_base && !($img_width && $img_height)) {
3537     error ("-size WxH is required with -imagemap");
3538   }
3539
3540   if (defined ($local_dir)) {
3541     $_ = "xscreensaver-getimage-file";
3542     which ($_) || error "$_ not found on \$PATH.";
3543   }
3544
3545   init_signals();
3546
3547   spawn_driftnet ($driftnet_cmd) if ($driftnet_cmd);
3548
3549   if ($urls_only_p) {
3550     url_only_output ();
3551   } else {
3552     x_or_pbm_output ($window_id);
3553   }
3554 }
3555
3556 main();
3557 exit (0);