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