3 # webcollage, Copyright (c) 1999-2002 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."
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
16 # To run this as a display mode with xscreensaver, add this to `programs':
18 # default-n: webcollage -root \n\
19 # default-n: webcollage -root -filter 'vidwhacker -stdin -stdout' \n\
22 # If you have the "driftnet" program installed, webcollage can display a
23 # collage of images sniffed off your local ethernet, instead of pulled out
24 # of search engines: in that way, your screensaver can display the images
25 # that your co-workers are downloading!
27 # Driftnet is available here: http://www.ex-parrot.com/~chris/driftnet/
30 # default-n: webcollage -root -driftnet \n\
32 # Driftnet is the Unix implementation of the MacOS "EtherPEG" program.
38 # We can't "use diagnostics" here, because that library malfunctions if
39 # you signal and catch alarms: it says "Uncaught exception from user code"
40 # and exits, even though I damned well AM catching it!
47 use Fcntl ':flock'; # import LOCK_* constants
48 use POSIX qw(strftime);
50 use bytes; # Larry can take Unicode and shove it up his ass sideways.
51 # Perl 5.8.0 causes us to start getting incomprehensible
52 # errors about UTF-8 all over the place without this.
55 my $progname = $0; $progname =~ s@.*/@@g;
56 my $version = q{ $Revision: 1.102 $ }; $version =~ s/^[^0-9]+([0-9.]+).*$/$1/;
57 my $copyright = "WebCollage $version, Copyright (c) 1999-2002" .
58 " Jamie Zawinski <jwz\@jwz.org>\n" .
59 " http://www.jwz.org/xscreensaver/\n";
63 my @search_methods = ( 77, "altavista", \&pick_from_alta_vista_random_link,
64 12, "yahoorand", \&pick_from_yahoo_random_link,
65 9, "lycos", \&pick_from_lycos_text,
66 2, "yahoonews", \&pick_from_yahoo_news_text,
68 # Alta Vista has a new "random link" URL now.
69 # They added it specifically to better support webcollage!
70 # That was super cool of them. This is how we used to do
73 # 0, "avimages", \&pick_from_alta_vista_images,
74 # 0, "avtext", \&pick_from_alta_vista_text,
76 # Google asked (nicely) for me to stop searching them.
77 # I asked them to add a "random link" url. They said
78 # "that would be easy, we'll think about it" and then
79 # never wrote back. Booo Google! Booooo!
81 # 0, "googlenums", \&pick_from_google_image_numbers,
82 # 0, "googleimgs", \&pick_from_google_images,
84 # I suspect Hotbot is actually the same search engine
87 # 0, "hotbot", \&pick_from_hotbot_text,
90 # programs we can use to write to the root window (tried in ascending order.)
92 my @root_displayers = (
93 "chbg -once -xscreensaver -max_size 100",
94 "xv -root -quit -viewonly +noresetroot -quick24 -rmode 5" .
95 " -rfg black -rbg black",
96 "xli -quiet -onroot -center -border black",
97 "xloadimage -quiet -onroot -center -border black",
99 # this lame program wasn't built with vroot.h:
100 # "xsri -scale -keep-aspect -center-horizontal -center-vertical",
104 # Some sites need cookies to work properly. These are they.
107 "www.altavista.com" => "AV_ALL=1", # request uncensored searches
108 "web.altavista.com" => "AV_ALL=1",
110 # log in as "cipherpunk"
111 "www.nytimes.com" => 'NYT-S=18cHMIlJOn2Y1bu5xvEG3Ufuk6E1oJ.' .
112 'FMxWaQV0igaB5Yi/Q/guDnLeoL.pe7i1oakSb' .
113 '/VqfdUdb2Uo27Vzt1jmPn3cpYRlTw9',
117 # If this is set, it's a helper program to use for pasting images together:
118 # this is a lot faster and more efficient than using PPM pipelines, which is
119 # what we do if this program doesn't exist. (We check for "webcollage-helper"
120 # on $PATH at startup, and set this variable appropriately.)
122 my $webcollage_helper = undef;
125 # If we have the webcollage-helper program, then it will paste the images
126 # together with transparency! 0.0 is invisible, 1.0 is totally opaque.
131 # Some sites have managed to poison the search engines. These are they.
132 # (We auto-detect sites that have poisoned the search engines via excessive
133 # keywords or dictionary words, but these are ones that slip through
136 # This can contain full host names, or 2 or 3 component domains.
139 "die.net" => 1, # 'l33t h4ck3r d00dz.
140 "genforum.genealogy.com" => 1, # Cluttering avtext with human names.
141 "rootsweb.com" => 1, # Cluttering avtext with human names.
142 "akamai.net" => 1, # Lots of sites have their images on Akamai.
143 "akamaitech.net" => 1, # But those are pretty much all banners.
144 # Since Akamai is super-expensive, let's
145 # go out on a limb and assume that all of
146 # their customers are rich-and-boring.
147 "bartleby.com" => 1, # Dictionary, cluttering avtext.
148 "encyclopedia.com" => 1, # Dictionary, cluttering avtext.
149 "onlinedictionary.datasegment.com" => 1, # Dictionary, cluttering avtext.
150 "hotlinkpics.com" => 1, # Porn site that has poisoned avimages
151 # (I don't see how they did it, though!)
152 "alwayshotels.com" => 1, # Poisoned Lycos pretty heavily.
153 "nextag.com" => 1, # Poisoned Alta Vista real good.
157 # When verbosity is turned on, we warn about sites that we seem to be hitting
158 # a lot: usually this means some new poisoner has made it into the search
159 # engines. But sometimes, the warning is just because that site has a lot
160 # of stuff on it. So these are the sites that are immune to the "frequent
161 # site" diagnostic message.
163 my %warningless_sites = (
164 "home.earthlink.net" => 1, # Lots of home pages here.
165 "www.geocities.com" => 1,
166 "www.angelfire.com" => 1,
167 "members.aol.com" => 1,
169 "yimg.com" => 1, # This is where dailynews.yahoo.com stores
170 "eimg.com" => 1, # its images, so pick_from_yahoo_news_text()
171 # hits this every time.
173 "driftnet" => 1, # builtin...
177 ##############################################################################
179 # Various global flags set by command line parameters, or computed
181 ##############################################################################
184 my $current_state = "???"; # for diagnostics
187 my $image_succeeded = -1;
188 my $suppress_audit = 0;
190 my $verbose_imgmap = 0; # print out rectangles and URLs only (stdout)
191 my $verbose_warnings = 0; # print out warnings when things go wrong
192 my $verbose_load = 0; # diagnostics about loading of URLs
193 my $verbose_filter = 0; # diagnostics about page selection/rejection
194 my $verbose_net = 0; # diagnostics about network I/O
195 my $verbose_pbm = 0; # diagnostics about PBM pipelines
196 my $verbose_http = 0; # diagnostics about all HTTP activity
197 my $verbose_exec = 0; # diagnostics about executing programs
199 my $report_performance_interval = 60 * 15; # print some stats every 15 minutes
201 my $http_proxy = undef;
202 my $http_timeout = 30;
203 my $cvt_timeout = 10;
209 my $min_gif_area = (120 * 120);
215 my @pids_to_kill = (); # forked pids we should kill when we exit, if any.
217 my $driftnet_magic = 'driftnet';
218 my $driftnet_dir = undef;
219 my $default_driftnet_cmd = "driftnet -a -m 100";
224 my @tripwire_words = ("aberrate", "abode", "amorphous", "antioch",
225 "arrhenius", "arteriole", "blanket", "brainchild",
226 "burdensome", "carnival", "cherub", "chord", "clever",
227 "dedicate", "dilogarithm", "dolan", "dryden",
231 ##############################################################################
235 ##############################################################################
237 # returns three values: the HTTP response line; the document headers;
238 # and the document body.
241 my ( $url, $referer, $timeout ) = @_;
243 if (!defined($timeout)) { $timeout = $http_timeout; }
244 if ($timeout > $http_timeout) { $timeout = $http_timeout; }
247 LOG (($verbose_net || $verbose_load), "timed out for $url");
251 LOG ($verbose_net, "get_document_1 $url " . ($referer ? $referer : ""));
253 if (! ($url =~ m@^http://@i)) {
254 LOG ($verbose_net, "not an HTTP URL: $url");
258 my ($url_proto, $dummy, $serverstring, $path) = split(/\//, $url, 4);
259 $path = "" unless $path;
261 my ($them,$port) = split(/:/, $serverstring);
262 $port = 80 unless $port;
267 $serverstring = $http_proxy if $http_proxy;
268 ($them2,$port2) = split(/:/, $serverstring);
269 $port2 = 80 unless $port2;
272 my ($remote, $iaddr, $paddr, $proto, $line);
274 if ($port2 =~ /\D/) { $port2 = getservbyname($port2, 'tcp') }
276 LOG (($verbose_net || $verbose_load), "unrecognised port in $url");
279 $iaddr = inet_aton($remote);
281 LOG (($verbose_net || $verbose_load), "host not found: $remote");
284 $paddr = sockaddr_in($port2, $iaddr);
292 local $SIG{ALRM} = sub {
293 LOG (($verbose_net || $verbose_load), "timed out ($timeout) for $url");
298 $proto = getprotobyname('tcp');
299 if (!socket(S, PF_INET, SOCK_STREAM, $proto)) {
300 LOG (($verbose_net || $verbose_load), "socket: $!");
303 if (!connect(S, $paddr)) {
304 LOG (($verbose_net || $verbose_load), "connect($serverstring): $!");
308 select(S); $| = 1; select(STDOUT);
310 my $cookie = $cookies{$them};
312 my $user_agent = "$progname/$version";
314 if ($url =~ m@^http://www\.altavista\.com/@) {
315 # block this, you turkeys.
316 $user_agent = "Mozilla/4.76 [en] (X11; U; Linux 2.2.16-22 i686; Nav)";
319 my $hdrs = "GET " . ($http_proxy ? $url : "/$path") . " HTTP/1.0\r\n" .
321 "User-Agent: $user_agent\r\n";
323 $hdrs .= "Referer: $referer\r\n";
326 my @cc = split(/\r?\n/, $cookie);
327 $hdrs .= "Cookie: " . join('; ', @cc) . "\r\n";
331 foreach (split('\r?\n', $hdrs)) {
332 LOG ($verbose_http, " ==> $_");
335 my $http = <S> || "";
339 LOG ($verbose_http, " <== $_");
345 LOG ($verbose_http, " <== $_");
347 if (m@^Set-cookie:\s*([^;\r\n]+)@i) {
348 set_cookie($them, $1)
359 " <== [ body ]: $lines lines, " . length($body) . " bytes");
364 LOG (($verbose_net || $verbose_load), "null response: $url");
368 return ( $http, $head, $body );
370 die if ($@ && $@ ne "alarm\n"); # propagate errors
385 # returns two values: the document headers; and the document body.
386 # if the given URL did a redirect, returns the redirected-to document.
389 my ( $url, $referer, $timeout ) = @_;
392 if (defined($referer) && $referer eq $driftnet_magic) {
393 return get_driftnet_file ($url);
398 my $max_loop_count = 4;
401 if (defined($timeout) && $timeout <= 0) {
402 LOG (($verbose_net || $verbose_load), "timed out for $url");
407 my ( $http, $head, $body ) = get_document_1 ($url, $referer, $timeout);
409 if (defined ($timeout)) {
411 my $elapsed = $now - $start;
412 $timeout -= $elapsed;
416 return () unless $http; # error message already printed
418 $http =~ s/[\r\n]+$//s;
420 if ( $http =~ m@^HTTP/[0-9.]+ 30[123]@ ) {
422 my ( $location ) = m@^location:[ \t]*(.*)$@im;
424 $location =~ s/[\r\n]$//;
426 LOG ($verbose_net, "redirect from $url to $location");
431 $referer =~ m@^(http://[^/]+)@i;
433 } elsif (! ($url =~ m@^[a-z]+:@i)) {
435 s@[^/]+$@@g if m@^http://[^/]+/@i;
436 $_ .= "/" if m@^http://[^/]+$@i;
441 LOG ($verbose_net, "no Location with \"$http\"");
442 return ( $url, $body );
445 if ($loop_count++ > $max_loop_count) {
447 "too many redirects ($max_loop_count) from $orig_url");
452 } elsif ( $http =~ m@^HTTP/[0-9.]+ ([4-9][0-9][0-9].*)$@ ) {
454 LOG (($verbose_net || $verbose_load), "failed: $1 ($url)");
456 # http errors -- return nothing.
462 LOG (($verbose_net || $verbose_load), "document contains no data: $url");
468 return ( $url, $body );
474 # If we already have a cookie defined for this site, and the site is trying
475 # to overwrite that very same cookie, let it do so. This is because nytimes
476 # expires its cookies - it lets you upgrade to a new cookie without logging
477 # in again, but you have to present the old cookie to get the new cookie.
478 # So, by doing this, the built-in cypherpunks cookie will never go "stale".
481 my ($host, $cookie) = @_;
482 my $oc = $cookies{$host};
485 my ($oc_name, $oc_value) = m@^([^= \t\r\n]+)=(.*)$@;
487 my ($nc_name, $nc_value) = m@^([^= \t\r\n]+)=(.*)$@;
489 if ($oc_name eq $nc_name &&
490 $oc_value ne $nc_value) {
491 $cookies{$host} = $cookie;
492 LOG ($verbose_net, "overwrote ${host}'s $oc_name cookie");
497 ############################################################################
499 # Extracting image URLs from HTML
501 ############################################################################
503 # given a URL and the body text at that URL, selects and returns a random
504 # image from it. returns () if no suitable images found.
506 sub pick_image_from_body {
507 my ( $url, $body ) = @_;
512 # if there's at least one slash after the host, take off the last
514 if ( m@^http://[^/]+/@io ) {
515 $base =~ s@[^/]+$@@go;
518 # if there are no slashes after the host at all, put one on the end.
519 if ( m@^http://[^/]+$@io ) {
525 # strip out newlines, compress whitespace
532 # There are certain web sites that list huge numbers of dictionary
533 # words in their bodies or in their <META NAME=KEYWORDS> tags (surprise!
534 # Porn sites tend not to be reputable!)
536 # I do not want webcollage to filter on content: I want it to select
537 # randomly from the set of images on the web. All the logic here for
538 # rejecting some images is really a set of heuristics for rejecting
539 # images that are not really images: for rejecting *text* that is in
540 # GIF/JPEG form. I don't want text, I want pictures, and I want the
541 # content of the pictures to be randomly selected from among all the
544 # So, filtering out "dirty" pictures by looking for "dirty" keywords
545 # would be wrong: dirty pictures exist, like it or not, so webcollage
546 # should be able to select them.
548 # However, picking a random URL is a hard thing to do. The mechanism I'm
549 # using is to search for a selection of random words. This is not
550 # perfect, but works ok most of the time. The way it breaks down is when
551 # some URLs get precedence because their pages list *every word* as
552 # related -- those URLs come up more often than others.
554 # So, after we've retrieved a URL, if it has too many keywords, reject
555 # it. We reject it not on the basis of what those keywords are, but on
556 # the basis that by having so many, the page has gotten an unfair
557 # advantage against our randomizer.
560 foreach my $trip (@tripwire_words) {
561 $trip_count++ if m/$trip/i;
564 if ($trip_count >= $#tripwire_words - 2) {
565 LOG (($verbose_filter || $verbose_load),
566 "there is probably a dictionary in \"$url\": rejecting.");
567 $rejected_urls{$url} = -1;
577 foreach (split(/ *</)) {
580 # Likewise, reject any web pages that have a KEYWORDS meta tag
583 if (m/name ?= ?\"?keywords\"?/i &&
584 m/content ?= ?\"([^\"]+)\"/) {
587 LOG (($verbose_filter || $verbose_load),
588 "excessive keywords ($L bytes) in $url: rejecting.");
589 $rejected_urls{$url} = $L;
594 LOG ($verbose_filter, " keywords ($L bytes) in $url (ok)");
598 } elsif ( m/^(img|a) .*(src|href) ?= ?\"? ?(.*?)[ >\"]/io ) {
600 my $was_inline = ( "$1" eq "a" || "$1" eq "A" );
602 my ( $width ) = m/width ?=[ \"]*(\d+)/oi;
603 my ( $height ) = m/height ?=[ \"]*(\d+)/oi;
608 ( $site = $base ) =~ s@^(http://[^/]*).*@$1@gio;
610 } elsif ( ! m@^[^/:?]+:@ ) {
613 1 while (s@/[^/]+/\.\./@/@g);
617 if ( ! m@^http://@io ) {
622 if ( ! m@[.](gif|jpg|jpeg|pjpg|pjpeg)$@io ) {
626 # skip really short or really narrow images
627 if ( $width && $width < $min_width) {
628 if (!$height) { $height = "?"; }
629 LOG ($verbose_filter, " skip narrow image $_ (${width}x$height)");
633 if ( $height && $height < $min_height) {
634 if (!$width) { $width = "?"; }
635 LOG ($verbose_filter, " skip short image $_ (${width}x$height)");
639 # skip images with ratios that make them look like banners.
640 if ($min_ratio && $width && $height &&
641 ($width * $min_ratio ) > $height) {
642 if (!$height) { $height = "?"; }
643 LOG ($verbose_filter, " skip bad ratio $_ (${width}x$height)");
647 # skip GIFs with a small number of pixels -- those usually suck.
648 if ($width && $height &&
650 ($width * $height) < $min_gif_area) {
651 LOG ($verbose_filter, " skip small GIF $_ (${width}x$height)");
658 if ($unique_urls{$url}) {
659 LOG ($verbose_filter, " skip duplicate image $_");
663 LOG ($verbose_filter,
665 ($width && $height ? " (${width}x${height})" : "") .
666 ($was_inline ? " (inline)" : ""));
668 $urls[++$#urls] = $url;
669 $unique_urls{$url}++;
671 # jpegs are preferable to gifs.
673 if ( ! m@[.]gif$@io ) {
674 $urls[++$#urls] = $url;
677 # pointers to images are preferable to inlined images.
678 if ( ! $was_inline ) {
679 $urls[++$#urls] = $url;
680 $urls[++$#urls] = $url;
685 my $fsp = ($body =~ m@<frameset@i);
690 @urls = depoison (@urls);
693 LOG ($verbose_load, "no images on $base" . ($fsp ? " (frameset)" : ""));
697 # pick a random element of the table
698 my $i = int(rand($#urls+1));
701 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#urls+1) . ": $url");
708 ############################################################################
710 # Subroutines for getting pages and images out of search engines
712 ############################################################################
715 sub pick_dictionary {
716 my @dicts = ("/usr/dict/words",
717 "/usr/share/dict/words",
718 "/usr/share/lib/dict/words");
719 foreach my $f (@dicts) {
725 error ("$dicts[0] does not exist") unless defined($wordlist);
728 # returns a random word from the dictionary
732 if (open (IN, "<$wordlist")) {
733 my $size = (stat(IN))[7];
734 my $pos = rand $size;
735 if (seek (IN, $pos, 0)) {
736 $word = <IN>; # toss partial line
737 $word = <IN>; # keep next line
746 return 0 if (!$word);
748 $word =~ s/^[ \t\n\r]+//;
749 $word =~ s/[ \t\n\r]+$//;
754 $word =~ s/ally$/al/;
755 $word =~ s/izes$/ize/;
756 $word =~ tr/A-Z/a-z/;
758 if ( $word =~ s/[ \t\n\r]/\+/g ) { # convert intra-word spaces to "+".
759 $word = "\%22$word\%22"; # And put quotes (%22) around it.
767 my $sep = ($or_p ? "%20OR%20" : "%20");
768 return (random_word . $sep .
778 $s =~ s|([^-a-zA-Z0-9.\@/_\r\n])|sprintf("%%%02X", ord($1))|ge;
785 $s =~ s/%([a-z0-9]{2})/chr(hex($1))/ige;
790 # Loads the given URL (a search on some search engine) and returns:
791 # - the total number of hits the search engine claimed it had;
792 # - a list of URLs from the page that the search engine returned;
793 # Note that this list contains all kinds of internal search engine
794 # junk URLs too -- caller must prune them.
796 sub pick_from_search_engine {
797 my ( $timeout, $search_url, $words ) = @_;
802 print STDERR "\n\n" if ($verbose_load);
804 LOG ($verbose_load, "words: $_");
805 LOG ($verbose_load, "URL: $search_url");
807 $last_search = $search_url; # for warnings
810 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
811 if (defined ($timeout)) {
812 $timeout -= (time - $start);
815 LOG (($verbose_net || $verbose_load),
816 "timed out (late) for $search_url");
822 return () if (! $body);
827 my $search_count = "?";
828 if ($body =~ m@found (approximately |about )?(<B>)?(\d+)(</B>)? image@) {
830 } elsif ($body =~ m@<NOBR>((\d{1,3})(,\d{3})*) @i) {
832 } elsif ($body =~ m@found ((\d{1,3})(,\d{3})*|\d+) Web p@) {
834 } elsif ($body =~ m@found about ((\d{1,3})(,\d{3})*|\d+) results@) {
836 } elsif ($body =~ m@\b\d+ - \d+ of (\d+)\b@i) { # avimages
838 } elsif ($body =~ m@About ((\d{1,3})(,\d{3})*) images@i) { # avimages
840 } elsif ($body =~ m@We found ((\d{1,3})(,\d{3})*|\d+) results@i) { # *vista
842 } elsif ($body =~ m@ of about <B>((\d{1,3})(,\d{3})*)<@i) { # googleimages
844 } elsif ($body =~ m@<B>((\d{1,3})(,\d{3})*)</B> Web sites were found@i) {
845 $search_count = $1; # lycos
846 } elsif ($body =~ m@WEB.*?RESULTS.*?\b((\d{1,3})(,\d{3})*)\b.*?Matches@i) {
847 $search_count = $1; # hotbot
848 } elsif ($body =~ m@no photos were found containing@i) { # avimages
850 } elsif ($body =~ m@found no document matching@i) { # avtext
853 1 while ($search_count =~ s/^(\d+)(\d{3})/$1,$2/);
855 # if ($search_count eq "?" || $search_count eq "0") {
857 # my $file = "/tmp/wc.html";
858 # open(OUT, ">$file") || error ("writing $file: $!");
861 # print STDERR blurb() . "###### wrote $file\n";
865 my $length = length($body);
874 foreach (split(/\n/)) {
876 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
879 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
880 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
882 if ( $rejected_urls{$u} ) {
883 LOG ($verbose_filter, " pre-rejecting candidate: $u");
887 LOG ($verbose_http, " HREF: $u");
889 $subpages[++$#subpages] = $u;
892 if ( $#subpages < 0 ) {
893 LOG ($verbose_filter,
894 "found nothing on $base ($length bytes, $href_count links).");
898 LOG ($verbose_filter, "" . $#subpages+1 . " links on $search_url");
900 return ($search_count, @subpages);
908 my ($h) = m@^http://([^/: \t\r\n]+)@i;
910 next unless defined($h);
912 if ($poisoners{$h}) {
913 LOG (($verbose_filter), " rejecting poisoner: $_");
916 if ($h =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
918 LOG (($verbose_filter), " rejecting poisoner: $_");
921 if ($h =~ m@([^.]+\.[^.]+)$@ &&
923 LOG (($verbose_filter), " rejecting poisoner: $_");
933 # given a list of URLs, picks one at random; loads it; and returns a
934 # random image from it.
935 # returns the url of the page loaded; the url of the image chosen;
936 # and a debugging description string.
938 sub pick_image_from_pages {
939 my ($base, $total_hit_count, $unfiltered_link_count, $timeout, @pages) = @_;
941 $total_hit_count = "?" unless defined($total_hit_count);
943 @pages = depoison (@pages);
945 "" . ($#pages+1) . " candidates of $unfiltered_link_count links" .
946 " ($total_hit_count total)");
948 return () if ($#pages < 0);
950 my $i = int(rand($#pages+1));
951 my $page = $pages[$i];
953 LOG ($verbose_load, "picked page $page");
957 my ( $base2, $body2 ) = get_document ($page, $base, $timeout);
959 if (!$base2 || !$body2) {
964 my $img = pick_image_from_body ($base2, $body2);
968 return ($base2, $img);
975 ############################################################################
977 # Pick images from random pages returned by the Yahoo Random Link
979 ############################################################################
982 my $yahoo_random_link = "http://random.yahoo.com/bin/ryl";
985 # Picks a random page; picks a random image on that page;
986 # returns two URLs: the page containing the image, and the image.
987 # Returns () if nothing found this time.
989 sub pick_from_yahoo_random_link {
990 my ( $timeout ) = @_;
992 print STDERR "\n\n" if ($verbose_load);
993 LOG ($verbose_load, "URL: $yahoo_random_link");
995 $last_search = $yahoo_random_link; # for warnings
999 my ( $base, $body ) = get_document ($yahoo_random_link, undef, $timeout);
1000 if (!$base || !$body) {
1005 LOG ($verbose_load, "redirected to: $base");
1007 my $img = pick_image_from_body ($base, $body);
1011 return ($base, $img);
1018 ############################################################################
1020 # Pick images from random pages returned by the Alta Vista Random Link
1022 ############################################################################
1025 my $alta_vista_random_link = "http://www.altavista.com/image/randomlink";
1028 # Picks a random page; picks a random image on that page;
1029 # returns two URLs: the page containing the image, and the image.
1030 # Returns () if nothing found this time.
1032 sub pick_from_alta_vista_random_link {
1033 my ( $timeout ) = @_;
1035 print STDERR "\n\n" if ($verbose_load);
1036 LOG ($verbose_load, "URL: $alta_vista_random_link");
1038 $last_search = $alta_vista_random_link; # for warnings
1040 $suppress_audit = 1;
1042 my ( $base, $body ) = get_document ($alta_vista_random_link,
1044 if (!$base || !$body) {
1049 LOG ($verbose_load, "redirected to: $base");
1051 my $img = pick_image_from_body ($base, $body);
1055 return ($base, $img);
1062 ############################################################################
1064 # Pick images by feeding random words into Alta Vista Image Search
1066 ############################################################################
1069 my $alta_vista_images_url = "http://www.altavista.com/image/results" .
1070 "?ipht=1" . # photos
1071 "&igrph=1" . # graphics
1074 "&micat=1" . # no partner sites
1075 "&sc=on" . # "site collapse"
1079 sub pick_from_alta_vista_images {
1080 my ( $timeout ) = @_;
1082 my $words = random_words(0);
1083 my $page = (int(rand(9)) + 1);
1084 my $search_url = $alta_vista_images_url . $words;
1087 $search_url .= "&pgno=" . $page; # page number
1088 $search_url .= "&stq=" . (($page-1) * 12); # first hit result on page
1091 my ($search_hit_count, @subpages) =
1092 pick_from_search_engine ($timeout, $search_url, $words);
1094 my @candidates = ();
1095 foreach my $u (@subpages) {
1097 # avtext is encoding their URLs now.
1098 next unless ($u =~ m@^/r.*\&r=([^&]+).*@);
1099 $u = url_unquote($1);
1101 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1102 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
1103 next if ($u =~ m@[/.]doubleclick\.net\b@i); # you cretins
1104 next if ($u =~ m@[/.]clicktomarket\.com\b@i); # more cretins
1106 next if ($u =~ m@[/.]viewimages\.com\b@i); # stacked deck
1107 next if ($u =~ m@[/.]gettyimages\.com\b@i);
1109 LOG ($verbose_filter, " candidate: $u");
1110 push @candidates, $u;
1113 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1114 $timeout, @candidates);
1119 ############################################################################
1121 # Pick images by feeding random words into Google Image Search.
1122 # By Charles Gales <gales@us.ibm.com>
1124 ############################################################################
1127 my $google_images_url = "http://images.google.com/images" .
1128 "?site=images" . # photos
1129 "&btnG=Search" . # graphics
1130 "&safe=off" . # no screening
1135 sub pick_from_google_images {
1136 my ( $timeout ) = @_;
1138 my $words = random_word; # only one word for Google
1139 my $page = (int(rand(9)) + 1);
1140 my $num = 20; # 20 images per page
1141 my $search_url = $google_images_url . $words;
1144 $search_url .= "&start=" . $page*$num; # page number
1145 $search_url .= "&num=" . $num; #images per page
1148 my ($search_hit_count, @subpages) =
1149 pick_from_search_engine ($timeout, $search_url, $words);
1151 my @candidates = ();
1152 foreach my $u (@subpages) {
1153 next unless ($u =~ m@imgres\?imgurl@i); # All pics start with this
1154 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins
1156 if ($u =~ m@^/imgres\?imgurl=(.*?)\&imgrefurl=(.*?)\&@) {
1158 LOG ($verbose_filter, " candidate: $urlf");
1159 push @candidates, $urlf;
1163 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1164 $timeout, @candidates);
1169 ############################################################################
1171 # Pick images by feeding random *numbers* into Google Image Search.
1172 # By jwz, suggested by from Ian O'Donnell.
1174 ############################################################################
1178 sub pick_from_google_image_numbers {
1179 my ( $timeout ) = @_;
1182 my $number = int(rand($max));
1184 $number = sprintf("%04d", $number)
1187 my $words = "$number";
1188 my $page = (int(rand(40)) + 1);
1189 my $num = 20; # 20 images per page
1190 my $search_url = $google_images_url . $words;
1193 $search_url .= "&start=" . $page*$num; # page number
1194 $search_url .= "&num=" . $num; #images per page
1197 my ($search_hit_count, @subpages) =
1198 pick_from_search_engine ($timeout, $search_url, $words);
1200 my @candidates = ();
1202 foreach my $u (@subpages) {
1203 next unless ($u =~ m@imgres\?imgurl@i); # All pics start with this
1204 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins
1206 if ($u =~ m@^/imgres\?imgurl=(.*?)\&imgrefurl=(.*?)\&@) {
1208 my $img = "http://$1";
1210 LOG ($verbose_filter, " candidate: $ref");
1211 push @candidates, $img;
1212 $referers{$img} = $ref;
1216 @candidates = depoison (@candidates);
1217 return () if ($#candidates < 0);
1218 my $i = int(rand($#candidates+1));
1219 my $img = $candidates[$i];
1220 my $ref = $referers{$img};
1222 LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1223 return ($ref, $img);
1228 ############################################################################
1230 # Pick images by feeding random words into Alta Vista Text Search
1232 ############################################################################
1235 my $alta_vista_url = "http://www.altavista.com/web/results" .
1239 "&sc=on" . # "site collapse"
1244 sub pick_from_alta_vista_text {
1245 my ( $timeout ) = @_;
1247 my $words = random_words(0);
1248 my $page = (int(rand(9)) + 1);
1249 my $search_url = $alta_vista_url . $words;
1252 $search_url .= "&pgno=" . $page;
1253 $search_url .= "&stq=" . (($page-1) * 10);
1256 my ($search_hit_count, @subpages) =
1257 pick_from_search_engine ($timeout, $search_url, $words);
1259 my @candidates = ();
1260 foreach my $u (@subpages) {
1262 # Those altavista fuckers are playing really nasty redirection games
1263 # these days: the filter your clicks through their site, but use
1264 # onMouseOver to make it look like they're not! Well, it makes it
1265 # easier for us to identify search results...
1267 next unless ($u =~ m@^/r.*\&r=([^&]+).*@);
1268 $u = url_unquote($1);
1270 LOG ($verbose_filter, " candidate: $u");
1271 push @candidates, $u;
1274 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1275 $timeout, @candidates);
1280 ############################################################################
1282 # Pick images by feeding random words into Hotbot
1284 ############################################################################
1286 my $hotbot_search_url =("http://hotbot.lycos.com/default.asp" .
1288 "&descriptiontype=0" .
1295 "&cobrand=undefined" .
1298 sub pick_from_hotbot_text {
1299 my ( $timeout ) = @_;
1301 # lycos seems to always give us back dictionaries and word lists if
1302 # we search for more than one word...
1304 my $words = random_word();
1306 my $start = int(rand(8)) * 10 + 1;
1307 my $search_url = $hotbot_search_url . $words . "&first=$start&page=more";
1309 my ($search_hit_count, @subpages) =
1310 pick_from_search_engine ($timeout, $search_url, $words);
1312 my @candidates = ();
1313 foreach my $u (@subpages) {
1315 # Hotbot plays redirection games too
1316 next unless ($u =~ m@/director.asp\?.*\btarget=([^&]+)@);
1317 $u = url_decode($1);
1319 LOG ($verbose_filter, " candidate: $u");
1320 push @candidates, $u;
1323 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1324 $timeout, @candidates);
1329 ############################################################################
1331 # Pick images by feeding random words into Lycos
1333 ############################################################################
1335 my $lycos_search_url = "http://search.lycos.com/default.asp" .
1341 sub pick_from_lycos_text {
1342 my ( $timeout ) = @_;
1344 # lycos seems to always give us back dictionaries and word lists if
1345 # we search for more than one word...
1347 my $words = random_word();
1349 my $start = int(rand(8)) * 10 + 1;
1350 my $search_url = $lycos_search_url . $words . "&first=$start&page=more";
1352 my ($search_hit_count, @subpages) =
1353 pick_from_search_engine ($timeout, $search_url, $words);
1355 my @candidates = ();
1356 foreach my $u (@subpages) {
1358 # Lycos plays redirection games.
1359 next unless ($u =~ m@^http://click.lycos.com/director.asp
1364 $u = url_decode($1);
1366 LOG ($verbose_filter, " candidate: $u");
1367 push @candidates, $u;
1370 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1371 $timeout, @candidates);
1376 ############################################################################
1378 # Pick images by feeding random words into news.yahoo.com
1380 ############################################################################
1382 my $yahoo_news_url = "http://search.news.yahoo.com/search/news" .
1385 "&s=-%24s%2C-date" .
1393 sub pick_from_yahoo_news_text {
1394 my ( $timeout ) = @_;
1396 my $words = random_words(0);
1397 my $search_url = $yahoo_news_url . $words;
1399 my ($search_hit_count, @subpages) =
1400 pick_from_search_engine ($timeout, $search_url, $words);
1402 my @candidates = ();
1403 foreach my $u (@subpages) {
1404 # only accept URLs on Yahoo's news site
1405 next unless ($u =~ m@^http://dailynews\.yahoo\.com/@i ||
1406 $u =~ m@^http://story\.news\.yahoo\.com/@i);
1408 LOG ($verbose_filter, " candidate: $u");
1409 push @candidates, $u;
1412 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1413 $timeout, @candidates);
1419 ############################################################################
1421 # Pick images by waiting for driftnet to populate a temp dir with files.
1422 # Requires driftnet version 0.1.5 or later.
1423 # (Driftnet is a program by Chris Lightfoot that sniffs your local ethernet
1424 # for images being downloaded by others.)
1425 # Driftnet/webcollage integration by jwz.
1427 ############################################################################
1430 sub pick_from_driftnet {
1431 my ( $timeout ) = @_;
1433 my $id = $driftnet_magic;
1434 my $dir = $driftnet_dir;
1438 error ("\$driftnet_dir unset?") unless ($dir);
1441 error ("$dir unreadable") unless (-d "$dir/.");
1443 $timeout = $http_timeout unless ($timeout);
1446 while ($now = time, $now < $start + $timeout) {
1448 opendir (DIR, $dir) || error ("$dir: $!");
1449 while (my $file = readdir(DIR)) {
1450 next if ($file =~ m/^\./);
1451 $file = "$dir/$file";
1453 LOG ($verbose_load, "picked file $file ($id)");
1454 return ($id, $file);
1458 LOG (($verbose_net || $verbose_load), "timed out for $id");
1463 sub get_driftnet_file {
1466 error ("\$driftnet_dir unset?") unless ($driftnet_dir);
1468 my $id = $driftnet_magic;
1469 my $re = qr/$driftnet_dir/;
1470 error ("$id: $file not in $driftnet_dir?")
1471 unless ($file =~ m@^$re@o);
1474 open (IN, $file) || error ("$id: $file: $!");
1476 while (<IN>) { $body .= $_; }
1477 close IN || error ("$id: $file: $!");
1478 unlink ($file) || error ("$id: $file: rm: $!");
1479 return ($id, $body);
1483 sub spawn_driftnet {
1486 # make a directory to use.
1488 my $tmp = $ENV{TEMPDIR} || "/tmp";
1489 $driftnet_dir = sprintf ("$tmp/driftcollage-%08x", rand(0xffffffff));
1490 LOG ($verbose_exec, "mkdir $driftnet_dir");
1491 last if mkdir ($driftnet_dir, 0700);
1494 if (! ($cmd =~ m/\s/)) {
1495 # if the command didn't have any arguments in it, then it must be just
1496 # a pointer to the executable. Append the default args to it.
1497 my $dargs = $default_driftnet_cmd;
1498 $dargs =~ s/^[^\s]+//;
1502 # point the driftnet command at our newly-minted private directory.
1504 $cmd .= " -d $driftnet_dir";
1505 $cmd .= ">/dev/null" unless ($verbose_exec);
1508 if ($pid < 0) { error ("fork: $!\n"); }
1511 push @pids_to_kill, $pid;
1512 LOG ($verbose_exec, "forked for \"$cmd\"");
1515 nontrapping_system ($cmd) || error ("exec: $!");
1518 # wait a bit, then make sure the process actually started up.
1521 error ("pid $pid failed to start \"$cmd\"")
1522 unless (1 == kill (0, $pid));
1526 ############################################################################
1528 # Pick a random image in a random way
1530 ############################################################################
1533 # Picks a random image on a random page, and returns two URLs:
1534 # the page containing the image, and the image.
1535 # Returns () if nothing found this time.
1539 my ( $timeout ) = @_;
1541 $current_state = "select";
1542 $load_method = "none";
1544 my $n = int(rand(100));
1547 my @rest = @search_methods;
1550 my $pct = shift @rest;
1551 my $name = shift @rest;
1552 my $tfn = shift @rest;
1554 if ($total > $n && !defined($fn)) {
1556 $current_state = $name;
1557 $load_method = $current_state;
1561 if ($total != 100) {
1562 error ("internal error: \@search_methods totals to $total%!");
1565 record_attempt ($current_state);
1566 return $fn->($timeout);
1571 ############################################################################
1573 # Statistics and logging
1575 ############################################################################
1578 return strftime ("%H:%M:%S: ", localtime);
1582 return "$progname: " . timestr() . "$current_state: ";
1587 print STDERR blurb() . "$err\n";
1599 my $head = "$progname: DEBUG: ";
1600 foreach (split (/\n/, $lastlog)) {
1601 print STDERR "$head$_\n";
1607 my ($print, $msg) = @_;
1608 my $blurb = timestr() . "$current_state: ";
1609 $lastlog .= "$blurb$msg\n";
1610 print STDERR "$progname: $blurb$msg\n" if $print;
1615 my %stats_successes;
1618 my $last_state = undef;
1619 sub record_attempt {
1623 record_failure($last_state) unless ($image_succeeded > 0);
1625 $last_state = $name;
1628 report_performance();
1631 $image_succeeded = 0;
1632 $suppress_audit = 0;
1635 sub record_success {
1636 my ($name, $url, $base) = @_;
1637 if (defined($stats_successes{$name})) {
1638 $stats_successes{$name}++;
1640 $stats_successes{$name} = 1;
1643 stop_timer ($name, 1);
1644 my $o = $current_state;
1645 $current_state = $name;
1646 save_recent_url ($url, $base);
1647 $current_state = $o;
1648 $image_succeeded = 1;
1653 sub record_failure {
1656 return if $image_succeeded;
1658 stop_timer ($name, 0);
1659 if ($verbose_load && !$verbose_exec) {
1661 if ($suppress_audit) {
1662 print STDERR "$progname: " . timestr() . "(audit log suppressed)\n";
1666 my $o = $current_state;
1667 $current_state = "DEBUG";
1669 my $line = "#" x 78;
1670 print STDERR "\n\n\n";
1671 print STDERR ("#" x 78) . "\n";
1672 print STDERR blurb() . "failed to get an image. Full audit log:\n";
1675 print STDERR ("-" x 78) . "\n";
1676 print STDERR "\n\n";
1678 $current_state = $o;
1680 $image_succeeded = 0;
1687 my $i = $stats_successes{$name};
1688 my $j = $stats_attempts{$name};
1691 return "" . ($j ? int($i * 100 / $j) : "0") . "%";
1695 my $current_start_time = 0;
1699 $current_start_time = time;
1701 if (defined($stats_attempts{$name})) {
1702 $stats_attempts{$name}++;
1704 $stats_attempts{$name} = 1;
1706 if (!defined($stats_elapsed{$name})) {
1707 $stats_elapsed{$name} = 0;
1712 my ($name, $success) = @_;
1713 $stats_elapsed{$name} += time - $current_start_time;
1717 my $last_report_time = 0;
1718 sub report_performance {
1720 return unless $verbose_warnings;
1723 return unless ($now >= $last_report_time + $report_performance_interval);
1724 my $ot = $last_report_time;
1725 $last_report_time = $now;
1727 return if ($ot == 0);
1729 my $blurb = "$progname: " . timestr();
1732 print STDERR "${blurb}Current standings:\n";
1734 foreach my $name (sort keys (%stats_attempts)) {
1735 my $try = $stats_attempts{$name};
1736 my $suc = $stats_successes{$name} || 0;
1737 my $pct = int($suc * 100 / $try);
1738 my $secs = $stats_elapsed{$name};
1739 my $secs_link = int($secs / $try);
1740 print STDERR sprintf ("$blurb %-12s %4s (%d/%d);\t %2d secs/link\n",
1741 "$name:", "$pct%", $suc, $try, $secs_link);
1747 my $max_recent_images = 400;
1748 my $max_recent_sites = 20;
1749 my @recent_images = ();
1750 my @recent_sites = ();
1752 sub save_recent_url {
1753 my ($url, $base) = @_;
1755 return unless ($verbose_warnings);
1758 my ($site) = m@^http://([^ \t\n\r/:]+)@;
1759 return unless defined ($site);
1761 if ($base eq $driftnet_magic) {
1762 $site = $driftnet_magic;
1763 @recent_images = ();
1767 foreach (@recent_images) {
1769 print STDERR blurb() . "WARNING: recently-duplicated image: $url" .
1770 " (on $base via $last_search)\n";
1776 # suppress "duplicate site" warning via %warningless_sites.
1778 if ($warningless_sites{$site}) {
1780 } elsif ($site =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
1781 $warningless_sites{$1}) {
1783 } elsif ($site =~ m@([^.]+\.[^.]+)$@ &&
1784 $warningless_sites{$1}) {
1789 foreach (@recent_sites) {
1791 print STDERR blurb() . "WARNING: recently-duplicated site: $site" .
1792 " ($url on $base via $last_search)\n";
1798 push @recent_images, $url;
1799 push @recent_sites, $site;
1800 shift @recent_images if ($#recent_images >= $max_recent_images);
1801 shift @recent_sites if ($#recent_sites >= $max_recent_sites);
1806 ##############################################################################
1810 ##############################################################################
1817 s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
1822 # Given the raw body of a GIF document, returns the dimensions of the image.
1826 my $type = substr($body, 0, 6);
1828 return () unless ($type =~ /GIF8[7,9]a/);
1829 $s = substr ($body, 6, 10);
1830 my ($a,$b,$c,$d) = unpack ("C"x4, $s);
1831 return (($b<<8|$a), ($d<<8|$c));
1834 # Given the raw body of a JPEG document, returns the dimensions of the image.
1839 my $L = length($body);
1841 my $c1 = substr($body, $i, 1); $i++;
1842 my $c2 = substr($body, $i, 1); $i++;
1843 return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
1846 while (ord($ch) != 0xDA && $i < $L) {
1847 # Find next marker, beginning with 0xFF.
1848 while (ord($ch) != 0xFF) {
1849 return () if (length($body) <= $i);
1850 $ch = substr($body, $i, 1); $i++;
1852 # markers can be padded with any number of 0xFF.
1853 while (ord($ch) == 0xFF) {
1854 return () if (length($body) <= $i);
1855 $ch = substr($body, $i, 1); $i++;
1858 # $ch contains the value of the marker.
1859 my $marker = ord($ch);
1861 if (($marker >= 0xC0) &&
1862 ($marker <= 0xCF) &&
1863 ($marker != 0xC4) &&
1864 ($marker != 0xCC)) { # it's a SOFn marker
1866 return () if (length($body) <= $i);
1867 my $s = substr($body, $i, 4); $i += 4;
1868 my ($a,$b,$c,$d) = unpack("C"x4, $s);
1869 return (($c<<8|$d), ($a<<8|$b));
1872 # We must skip variables, since FFs in variable names aren't
1873 # valid JPEG markers.
1874 return () if (length($body) <= $i);
1875 my $s = substr($body, $i, 2); $i += 2;
1876 my ($c1, $c2) = unpack ("C"x2, $s);
1877 my $length = ($c1 << 8) | $c2;
1878 return () if ($length < 2);
1885 # Given the raw body of a GIF or JPEG document, returns the dimensions of
1890 my ($w, $h) = gif_size ($body);
1891 if ($w && $h) { return ($w, $h); }
1892 return jpeg_size ($body);
1896 # returns the full path of the named program, or undef.
1900 foreach (split (/:/, $ENV{PATH})) {
1901 if (-x "$_/$prog") {
1909 # Like rand(), but chooses numbers with a bell curve distribution.
1912 $_ = 1.0 unless defined($_);
1914 return (rand($_) + rand($_) + rand($_));
1918 sub signal_cleanup {
1920 print STDERR blurb() . (defined($sig)
1921 ? "caught signal $sig."
1928 if (@pids_to_kill) {
1929 print STDERR blurb() . "killing: " . join(' ', @pids_to_kill) . "\n";
1930 kill ('TERM', @pids_to_kill);
1936 ##############################################################################
1938 # Generating a list of urls only
1940 ##############################################################################
1942 sub url_only_output {
1944 my ($base, $img) = pick_image;
1948 print "$img $base\n";
1953 ##############################################################################
1955 # Running as an xscreensaver module
1957 ##############################################################################
1959 my $image_ppm = ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp") . "/webcollage." . $$;
1960 my $image_tmp1 = $image_ppm . "-1";
1961 my $image_tmp2 = $image_ppm . "-2";
1963 my $filter_cmd = undef;
1964 my $post_filter_cmd = undef;
1965 my $background = undef;
1967 my $img_width; # size of the image being generated.
1973 unlink $image_ppm, $image_tmp1, $image_tmp2;
1977 # Like system, but prints status about exit codes, and kills this process
1978 # with whatever signal killed the sub-process, if any.
1980 sub nontrapping_system {
1984 s/\"[^\"]+\"/\"...\"/g;
1986 LOG ($verbose_exec, "executing \"$_\"");
1991 LOG ($verbose_exec, "subproc exited normally.");
1992 } elsif (($rc & 0xff) == 0) {
1994 LOG ($verbose_exec, "subproc exited with status $rc.");
1997 LOG ($verbose_exec, "subproc dumped core.");
2000 LOG ($verbose_exec, "subproc died with signal $rc.");
2001 # die that way ourselves.
2009 # Given the URL of a GIF or JPEG image, and the body of that image, writes a
2010 # PPM to the given output file. Returns the width/height of the image if
2014 my ($url, $body, $output) = @_;
2015 my ($cmd, $cmd2, $w, $h);
2017 if ((@_ = gif_size ($body))) {
2020 } elsif ((@_ = jpeg_size ($body))) {
2024 LOG (($verbose_pbm || $verbose_load),
2025 "not a GIF or JPG" .
2026 (($body =~ m@<(base|html|head|body|script|table|a href)>@i)
2027 ? " (looks like HTML)" : "") .
2029 $suppress_audit = 1;
2033 $cmd2 = "exec $cmd"; # yes, this really is necessary. if we don't
2034 # do this, the process doesn't die properly.
2035 if (!$verbose_pbm) {
2037 # We get a "giftopnm: got a 'Application Extension' extension"
2038 # warning any time it's an animgif.
2040 # Note that "giftopnm: EOF / read error on image data" is not
2041 # always a fatal error -- sometimes the image looks fine anyway.
2043 $cmd2 .= " 2>/dev/null";
2046 # There exist corrupted GIF and JPEG files that can make giftopnm and
2047 # djpeg lose their minds and go into a loop. So this gives those programs
2048 # a small timeout -- if they don't complete in time, kill them.
2054 local $SIG{ALRM} = sub {
2056 "timed out ($cvt_timeout) for $cmd on \"$url\" in pid $pid");
2057 kill ('TERM', $pid) if ($pid);
2062 if (($pid = open(PIPE, "| $cmd2 > $output"))) {
2069 LOG ($verbose_exec, "awaiting $pid");
2071 LOG ($verbose_exec, "$pid completed");
2073 my $size = (stat($output))[7];
2074 $size = -1 unless defined($size);
2076 LOG ($verbose_pbm, "$cmd on ${w}x$h \"$url\" failed ($size bytes)");
2080 LOG ($verbose_pbm, "created ${w}x$h $output ($cmd)");
2083 print STDERR blurb() . "$cmd failed: $!\n";
2087 die if ($@ && $@ ne "alarm\n"); # propagate errors
2100 sub pick_root_displayer {
2103 foreach my $cmd (@root_displayers) {
2105 my ($name) = m/^([^ ]+)/;
2106 push @names, "\"$name\"";
2107 LOG ($verbose_exec, "looking for $name...");
2108 foreach my $dir (split (/:/, $ENV{PATH})) {
2109 LOG ($verbose_exec, " checking $dir/$name");
2110 return $cmd if (-x "$dir/$name");
2114 $names[$#names] = "or " . $names[$#names];
2115 error "none of: " . join (", ", @names) . " were found on \$PATH.";
2119 my $ppm_to_root_window_cmd = undef;
2122 sub x_or_pbm_output {
2124 # Check for our helper program, to see whether we need to use PPM pipelines.
2126 $_ = "webcollage-helper";
2127 if (defined ($webcollage_helper) || which ($_)) {
2128 $webcollage_helper = $_ unless (defined($webcollage_helper));
2129 LOG ($verbose_pbm, "found \"$webcollage_helper\"");
2130 $webcollage_helper .= " -v";
2132 LOG (($verbose_pbm || $verbose_load), "no $_ program");
2135 # make sure the various programs we execute exist, right up front.
2137 my @progs = ("ppmmake"); # always need this one
2139 if (!defined($webcollage_helper)) {
2140 # Only need these others if we don't have the helper.
2141 @progs = (@progs, "giftopnm", "djpeg", "pnmpaste", "pnmscale", "pnmcut");
2145 which ($_) || error "$_ not found on \$PATH.";
2148 # find a root-window displayer program.
2150 $ppm_to_root_window_cmd = pick_root_displayer();
2152 if (!$img_width || !$img_height) {
2154 which ($_) || error "$_ not found on \$PATH.";
2156 ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
2157 if (!defined($img_height)) {
2158 error "xdpyinfo failed.";
2162 my $bgcolor = "#000000";
2163 my $bgimage = undef;
2166 if ($background =~ m/^\#[0-9a-f]+$/i) {
2167 $bgcolor = $background;
2169 } elsif (-r $background) {
2170 $bgimage = $background;
2172 } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
2173 error "not a color or readable file: $background";
2176 # default to assuming it's a color
2177 $bgcolor = $background;
2181 # Create the sold-colored base image.
2183 $_ = "ppmmake '$bgcolor' $img_width $img_height";
2184 LOG ($verbose_pbm, "creating base image: $_");
2185 nontrapping_system "$_ > $image_ppm";
2187 # Paste the default background image in the middle of it.
2194 open(IMG, "<$bgimage") || error "couldn't open $bgimage: $!";
2196 while (<IMG>) { $body .= $_; }
2199 if ((@_ = gif_size ($body))) {
2201 $cmd = "giftopnm |";
2203 } elsif ((@_ = jpeg_size ($body))) {
2207 } elsif ($body =~ m/^P\d\n(\d+) (\d+)\n/) {
2213 error "$bgimage is not a GIF, JPEG, or PPM.";
2216 my $x = int (($img_width - $iw) / 2);
2217 my $y = int (($img_height - $ih) / 2);
2219 "pasting $bgimage (${iw}x$ih) into base image at $x,$y");
2221 $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
2222 open (IMG, "| $cmd") || error "running $cmd: $!";
2226 LOG ($verbose_exec, "subproc exited normally.");
2227 rename ($image_tmp1, $image_ppm) ||
2228 error "renaming $image_tmp1 to $image_ppm: $!";
2234 my ($base, $img) = pick_image();
2235 my $source = $current_state;
2236 $current_state = "loadimage";
2238 my ($headers, $body) = get_document ($img, $base);
2240 paste_image ($base, $img, $body, $source);
2244 $current_state = "idle";
2245 $load_method = "none";
2247 unlink $image_tmp1, $image_tmp2;
2253 my ($base, $img, $body, $source) = @_;
2255 $current_state = "paste";
2257 $suppress_audit = 0;
2259 LOG ($verbose_pbm, "got $img (" . length($body) . ")");
2263 # If we are using the webcollage-helper, then we do not need to convert this
2264 # image to a PPM. But, if we're using a filter command, we still must, since
2265 # that's what the filters expect (webcollage-helper can read PPMs, so that's
2268 if (defined ($webcollage_helper) &&
2269 !defined ($filter_cmd)) {
2271 ($iw, $ih) = image_size ($body);
2273 LOG (($verbose_pbm || $verbose_load),
2274 "not a GIF or JPG" .
2275 (($body =~ m@<(base|html|head|body|script|table|a href)>@i)
2276 ? " (looks like HTML)" : "") .
2278 $suppress_audit = 1;
2284 open (OUT, ">$image_tmp1") || error ("writing $image_tmp1: $!");
2285 print OUT $body || error ("writing $image_tmp1: $!");
2286 close OUT || error ("writing $image_tmp1: $!");
2289 ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
2292 LOG ($verbose_pbm, "unable to make PBM from $img");
2297 record_success ($load_method, $img, $base);
2300 my $ow = $iw; # used only for error messages
2303 # don't just tack this onto the front of the pipeline -- we want it to
2304 # be able to change the size of the input image.
2307 LOG ($verbose_pbm, "running $filter_cmd");
2309 my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
2311 LOG(($verbose_pbm || $verbose_load), "failed command: \"$filter_cmd\"");
2312 LOG(($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
2315 rename ($image_tmp2, $image_tmp1);
2317 # re-get the width/height in case the filter resized it.
2319 open(IMG, "<$image_tmp1") || return 0;
2322 ($iw, $ih) = m/^(\d+) (\d+)$/;
2324 return 0 unless ($iw && $ih);
2327 my $target_w = $img_width;
2328 my $target_h = $img_height;
2334 # Usually scale the image to fit on the screen -- but sometimes scale it
2335 # to fit on half or a quarter of the screen. Note that we don't merely
2336 # scale it to fit, we instead cut it in half until it fits -- that should
2337 # give a wider distribution of sizes.
2339 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; $scale /= 2; }
2340 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; $scale /= 2; }
2342 if ($iw > $target_w || $ih > $target_h) {
2343 while ($iw > $target_w ||
2348 if ($iw <= 10 || $ih <= 10) {
2349 LOG ($verbose_pbm, "scaling to ${iw}x$ih would have been bogus.");
2353 LOG ($verbose_pbm, "scaling to ${iw}x$ih");
2355 $cmd .= " | pnmscale -xsize $iw -ysize $ih";
2359 my $src = $image_tmp1;
2361 my $crop_x = 0; # the sub-rectangle of the image
2362 my $crop_y = 0; # that we will actually paste.
2366 # The chance that we will randomly crop out a section of an image starts
2367 # out fairly low, but goes up for images that are very large, or images
2368 # that have ratios that make them look like banners (we try to avoid
2369 # banner images entirely, but they slip through when the IMG tags didn't
2370 # have WIDTH and HEIGHT specified.)
2372 my $crop_chance = 0.2;
2373 if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
2374 $crop_chance += 0.2;
2376 if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
2377 $crop_chance += 0.2;
2379 if ($min_ratio && ($iw * $min_ratio) > $ih) {
2380 $crop_chance += 0.7;
2383 if ($crop_chance > 0.1) {
2384 LOG ($verbose_pbm, "crop chance: $crop_chance");
2387 if (rand() < $crop_chance) {
2392 if ($crop_w > $min_width) {
2393 # if it's a banner, select the width linearly.
2394 # otherwise, select a bell.
2395 my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
2398 $crop_w = $min_width + int ($r * ($crop_w - $min_width));
2399 $crop_x = int (rand() * ($ow - $crop_w));
2401 if ($crop_h > $min_height) {
2402 # height always selects as a bell.
2403 $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
2404 $crop_y = int (rand() * ($oh - $crop_h));
2407 if ($crop_x != 0 || $crop_y != 0 ||
2408 $crop_w != $iw || $crop_h != $ih) {
2410 "randomly cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
2414 # Where the image should logically land -- this might be negative.
2416 my $x = int((rand() * ($img_width + $crop_w/2)) - $crop_w*3/4);
2417 my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
2419 # if we have chosen to paste the image outside of the rectangle of the
2420 # screen, then we need to crop it.
2424 $x + $crop_w > $img_width ||
2425 $y + $crop_h > $img_height) {
2428 "cropping for effective paste of ${crop_w}x$crop_h \@ $x,$y");
2430 if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
2431 if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
2433 if ($x + $crop_w >= $img_width) { $crop_w = $img_width - $x - 1; }
2434 if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
2437 # If any cropping needs to happen, add pnmcut.
2439 if ($crop_x != 0 || $crop_y != 0 ||
2440 $crop_w != $iw || $crop_h != $ih) {
2443 $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
2444 LOG ($verbose_pbm, "cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
2447 LOG ($verbose_pbm, "pasting ${iw}x$ih \@ $x,$y in $image_ppm");
2449 $cmd .= " | pnmpaste - $x $y $image_ppm";
2451 $cmd =~ s@^ *\| *@@;
2453 if (defined ($webcollage_helper)) {
2454 $cmd = "$webcollage_helper $image_tmp1 $image_ppm " .
2455 "$scale $opacity " .
2456 "$crop_x $crop_y $x $y " .
2461 # use a PPM pipeline
2463 $_ .= " < $image_tmp1 > $image_tmp2";
2467 $_ = "($_) 2>&1 | sed s'/^/" . blurb() . "/'";
2469 $_ .= " 2> /dev/null";
2472 my $rc = nontrapping_system ($_);
2474 if (defined ($webcollage_helper) && -z $image_ppm) {
2475 LOG (1, "failed command: \"$cmd\"");
2476 print STDERR "\naudit log:\n\n\n";
2477 print STDERR ("#" x 78) . "\n";
2478 print STDERR blurb() . "$image_ppm has zero size\n";
2480 print STDERR "\n\n";
2485 LOG (($verbose_pbm || $verbose_load), "failed command: \"$cmd\"");
2486 LOG (($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
2490 if (!defined ($webcollage_helper)) {
2491 rename ($image_tmp2, $image_ppm) || return;
2494 my $target = "$image_ppm";
2496 # don't just tack this onto the end of the pipeline -- we don't want it
2497 # to end up in $image_ppm, because we don't want the results to be
2500 if ($post_filter_cmd) {
2504 $target = $image_tmp1;
2505 if (!defined ($webcollage_helper)) {
2506 $cmd = "($post_filter_cmd) < $image_ppm > $target";
2508 # Blah, my scripts need the JPEG data, but some other folks need
2509 # the PPM data -- what to do? Ignore the problem, that's what!
2510 # $cmd = "djpeg < $image_ppm | ($post_filter_cmd) > $target";
2511 $cmd = "($post_filter_cmd) < $image_ppm > $target";
2514 $rc = nontrapping_system ($cmd);
2516 LOG ($verbose_pbm, "filter failed: \"$post_filter_cmd\"\n");
2521 if (!$no_output_p) {
2522 my $tsize = (stat($target))[7];
2524 $cmd = "$ppm_to_root_window_cmd $target";
2526 # xv seems to hate being killed. it tends to forget to clean
2527 # up after itself, and leaves windows around and colors allocated.
2528 # I had this same problem with vidwhacker, and I'm not entirely
2529 # sure what I did to fix it. But, let's try this: launch xv
2530 # in the background, so that killing this process doesn't kill it.
2531 # it will die of its own accord soon enough. So this means we
2532 # start pumping bits to the root window in parallel with starting
2533 # the next network retrieval, which is probably a better thing
2538 $rc = nontrapping_system ($cmd);
2541 LOG (($verbose_pbm || $verbose_load), "display failed: \"$cmd\"");
2546 LOG ($verbose_pbm, "$target size is $tsize");
2550 $source .= "-" . stats_of($source);
2551 print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n"
2552 if ($verbose_imgmap);
2562 $SIG{HUP} = \&signal_cleanup;
2563 $SIG{INT} = \&signal_cleanup;
2564 $SIG{QUIT} = \&signal_cleanup;
2565 $SIG{ABRT} = \&signal_cleanup;
2566 $SIG{KILL} = \&signal_cleanup;
2567 $SIG{TERM} = \&signal_cleanup;
2569 # Need this so that if giftopnm dies, we don't die.
2570 $SIG{PIPE} = 'IGNORE';
2573 END { signal_cleanup(); }
2582 my $driftnet_cmd = 0;
2584 $current_state = "init";
2585 $load_method = "none";
2589 # historical suckage: the environment variable name is lower case.
2590 $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
2592 while ($_ = $ARGV[0]) {
2594 if ($_ eq "-display" ||
2600 $ENV{DISPLAY} = shift @ARGV;
2601 } elsif ($_ eq "-root") {
2603 } elsif ($_ eq "-no-output") {
2605 } elsif ($_ eq "-urls-only") {
2608 } elsif ($_ eq "-verbose") {
2610 } elsif (m/^-v+$/) {
2611 $verbose += length($_)-1;
2612 } elsif ($_ eq "-delay") {
2613 $delay = shift @ARGV;
2614 } elsif ($_ eq "-timeout") {
2615 $http_timeout = shift @ARGV;
2616 } elsif ($_ eq "-filter") {
2617 $filter_cmd = shift @ARGV;
2618 } elsif ($_ eq "-filter2") {
2619 $post_filter_cmd = shift @ARGV;
2620 } elsif ($_ eq "-background" || $_ eq "-bg") {
2621 $background = shift @ARGV;
2622 } elsif ($_ eq "-size") {
2624 if (m@^(\d+)x(\d+)$@) {
2628 error "argument to \"-size\" must be of the form \"640x400\"";
2630 } elsif ($_ eq "-proxy" || $_ eq "-http-proxy") {
2631 $http_proxy = shift @ARGV;
2632 } elsif ($_ eq "-dictionary" || $_ eq "-dict") {
2633 $dict = shift @ARGV;
2634 } elsif ($_ eq "-driftnet" || $_ eq "--driftnet") {
2635 @search_methods = ( 100, "driftnet", \&pick_from_driftnet );
2636 if (! ($ARGV[0] =~ m/^-/)) {
2637 $driftnet_cmd = shift @ARGV;
2639 $driftnet_cmd = $default_driftnet_cmd;
2641 } elsif ($_ eq "-debug" || $_ eq "--debug") {
2642 my $which = shift @ARGV;
2643 my @rest = @search_methods;
2646 my $pct = shift @rest;
2647 my $name = shift @rest;
2648 my $tfn = shift @rest;
2650 if ($name eq $which) {
2651 @search_methods = (100, $name, $tfn);
2656 error "no such search method as \"$which\"" unless ($ok);
2657 LOG (1, "DEBUG: using only \"$which\"");
2660 print STDERR "$copyright\nusage: $progname " .
2661 "[-root] [-display dpy] [-verbose] [-debug which]\n" .
2662 "\t\t [-timeout secs] [-delay secs] [-filter cmd] [-filter2 cmd]\n" .
2663 "\t\t [-no-output] [-urls-only] [-background color] [-size WxH]\n" .
2664 "\t\t [-dictionary dictionary-file] [-http-proxy host[:port]]\n" .
2665 "\t\t [-driftnet [driftnet-program-and-args]]\n" .
2671 if ($http_proxy && $http_proxy eq "") {
2672 $http_proxy = undef;
2674 if ($http_proxy && $http_proxy =~ m@^http://([^/]*)/?$@ ) {
2675 # historical suckage: allow "http://host:port" as well as "host:port".
2679 if (!$root_p && !$no_output_p) {
2680 print STDERR $copyright;
2681 error "the -root argument is mandatory (for now.)";
2684 if (!$no_output_p && !$ENV{DISPLAY}) {
2685 error "\$DISPLAY is not set.";
2689 if ($verbose == 1) {
2690 $verbose_imgmap = 1;
2691 $verbose_warnings = 1;
2693 } elsif ($verbose == 2) {
2694 $verbose_imgmap = 1;
2695 $verbose_warnings = 1;
2698 } elsif ($verbose == 3) {
2699 $verbose_imgmap = 1;
2700 $verbose_warnings = 1;
2702 $verbose_filter = 1;
2704 } elsif ($verbose == 4) {
2705 $verbose_imgmap = 1;
2706 $verbose_warnings = 1;
2708 $verbose_filter = 1;
2711 } elsif ($verbose == 5) {
2712 $verbose_imgmap = 1;
2713 $verbose_warnings = 1;
2715 $verbose_filter = 1;
2719 } elsif ($verbose == 6) {
2720 $verbose_imgmap = 1;
2721 $verbose_warnings = 1;
2723 $verbose_filter = 1;
2728 } elsif ($verbose >= 7) {
2729 $verbose_imgmap = 1;
2730 $verbose_warnings = 1;
2732 $verbose_filter = 1;
2740 error ("$dict does not exist") unless (-f $dict);
2748 spawn_driftnet ($driftnet_cmd) if ($driftnet_cmd);