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