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
15 # To run this as a display mode with xscreensaver, add this to `programs':
17 # default-n: webcollage -root \n\
18 # default-n: webcollage -root -filter 'vidwhacker -stdin -stdout' \n\
24 # We can't "use diagnostics" here, because that library malfunctions if
25 # you signal and catch alarms: it says "Uncaught exception from user code"
26 # and exits, even though I damned well AM catching it!
33 use Fcntl ':flock'; # import LOCK_* constants
34 use POSIX qw(strftime);
37 my $progname = $0; $progname =~ s@.*/@@g;
38 my $version = q{ $Revision: 1.93 $ }; $version =~ s/^[^0-9]+([0-9.]+).*$/$1/;
39 my $copyright = "WebCollage $version, Copyright (c) 1999-2002" .
40 " Jamie Zawinski <jwz\@jwz.org>\n" .
41 " http://www.jwz.org/xscreensaver/\n";
45 my @search_methods = ( 40, "imagevista", \&pick_from_alta_vista_images,
46 30, "altavista", \&pick_from_alta_vista_text,
47 19, "yahoorand", \&pick_from_yahoo_random_link,
48 9, "lycos", \&pick_from_lycos_text,
49 2, "yahoonews", \&pick_from_yahoo_news_text,
51 # Hotbot gives me "no matches" just about every time.
52 # Then I try the same URL again, and it works. I guess
53 # it caches searches, and webcollage always busts its
54 # cache and time out? Or it just sucks.
55 # 0, "hotbot", \&pick_from_hotbot_text,
57 # Google asked (nicely) for me to stop searching them.
58 # 0, "googlenums", \&pick_from_google_image_numbers,
59 # 0, "googleimgs", \&pick_from_google_images,
63 # programs we can use to write to the root window (tried in ascending order.)
65 my @root_displayers = (
66 "chbg -once -xscreensaver -max_size 100",
67 "xv -root -quit -viewonly +noresetroot -quick24 -rmode 5" .
68 " -rfg black -rbg black",
69 "xli -quiet -onroot -center -border black",
70 "xloadimage -quiet -onroot -center -border black",
72 # this lame program wasn't built with vroot.h:
73 # "xsri -scale -keep-aspect -center-horizontal -center-vertical",
77 # Some sites need cookies to work properly. These are they.
80 "www.altavista.com" => "AV_ALL=1", # request uncensored searches
81 "web.altavista.com" => "AV_ALL=1",
83 # log in as "cipherpunk"
84 "www.nytimes.com" => 'NYT-S=18cHMIlJOn2Y1bu5xvEG3Ufuk6E1oJ.' .
85 'FMxWaQV0igaB5Yi/Q/guDnLeoL.pe7i1oakSb' .
86 '/VqfdUdb2Uo27Vzt1jmPn3cpYRlTw9',
90 # If this is set, it's a helper program to use for pasting images together:
91 # this is a lot faster and more efficient than using PPM pipelines, which is
92 # what we do if this program doesn't exist. (We check for "webcollage-helper"
93 # on $PATH at startup, and set this variable appropriately.)
95 my $webcollage_helper = undef;
98 # If we have the webcollage-helper program, then it will paste the images
99 # together with transparency! 0.0 is invisible, 1.0 is totally opaque.
104 # Some sites have managed to poison the search engines. These are they.
105 # (We auto-detect sites that have poisoned the search engines via excessive
106 # keywords or dictionary words, but these are ones that slip through
109 # This can contain full host names, or 2 or 3 component domains.
112 "die.net" => 1, # 'l33t h4ck3r d00dz.
113 "genforum.genealogy.com" => 1, # Cluttering altavista with human names.
114 "rootsweb.com" => 1, # Cluttering altavista with human names.
115 "akamai.net" => 1, # Lots of sites have their images on Akamai.
116 # But those are pretty much all banners.
117 # Since Akamai is super-expensive, let's
118 # go out on a limb and assume that all of
119 # their customers are rich-and-boring.
120 "bartleby.com" => 1, # Dictionary, cluttering altavista.
121 "encyclopedia.com" => 1, # Dictionary, cluttering altavista.
122 "onlinedictionary.datasegment.com" => 1, # Dictionary, cluttering altavista.
123 "hotlinkpics.com" => 1, # Porn site that has poisoned imagevista
124 # (I don't see how they did it, though!)
125 "alwayshotels.com" => 1, # Poisoned Lycos pretty heavily.
129 # When verbosity is turned on, we warn about sites that we seem to be hitting
130 # a lot: usually this means some new poisoner has made it into the search
131 # engines. But sometimes, the warning is just because that site has a lot
132 # of stuff on it. So these are the sites that are immune to the "frequent
133 # site" diagnostic message.
135 my %warningless_sites = (
136 "home.earthlink.net" => 1, # Lots of home pages here.
137 "www.geocities.com" => 1,
138 "www.angelfire.com" => 1,
139 "members.aol.com" => 1,
141 "yimg.com" => 1, # This is where dailynews.yahoo.com stores
142 "eimg.com" => 1, # its images, so pick_from_yahoo_news_text()
143 # hits this every time.
145 "driftnet" => 1, # builtin...
149 ##############################################################################
151 # Various global flags set by command line parameters, or computed
153 ##############################################################################
156 my $current_state = "???"; # for diagnostics
159 my $image_succeeded = -1;
160 my $suppress_audit = 0;
162 my $verbose_imgmap = 0; # print out rectangles and URLs only (stdout)
163 my $verbose_warnings = 0; # print out warnings when things go wrong
164 my $verbose_load = 0; # diagnostics about loading of URLs
165 my $verbose_filter = 0; # diagnostics about page selection/rejection
166 my $verbose_net = 0; # diagnostics about network I/O
167 my $verbose_pbm = 0; # diagnostics about PBM pipelines
168 my $verbose_http = 0; # diagnostics about all HTTP activity
169 my $verbose_exec = 0; # diagnostics about executing programs
171 my $report_performance_interval = 60 * 15; # print some stats every 15 minutes
173 my $http_proxy = undef;
174 my $http_timeout = 30;
175 my $cvt_timeout = 10;
181 my $min_gif_area = (120 * 120);
187 my @pids_to_kill = (); # forked pids we should kill when we exit, if any.
189 my $driftnet_magic = 'driftnet';
190 my $driftnet_dir = undef;
191 my $default_driftnet_cmd = "driftnet -a -m 100";
196 my @tripwire_words = ("aberrate", "abode", "amorphous", "antioch",
197 "arrhenius", "arteriole", "blanket", "brainchild",
198 "burdensome", "carnival", "cherub", "chord", "clever",
199 "dedicate", "dilogarithm", "dolan", "dryden",
203 ##############################################################################
207 ##############################################################################
209 # returns three values: the HTTP response line; the document headers;
210 # and the document body.
213 my ( $url, $referer, $timeout ) = @_;
215 if (!defined($timeout)) { $timeout = $http_timeout; }
216 if ($timeout > $http_timeout) { $timeout = $http_timeout; }
219 LOG (($verbose_net || $verbose_load), "timed out for $url");
223 LOG ($verbose_net, "get_document_1 $url " . ($referer ? $referer : ""));
225 if (! ($url =~ m@^http://@i)) {
226 LOG ($verbose_net, "not an HTTP URL: $url");
230 my ($url_proto, $dummy, $serverstring, $path) = split(/\//, $url, 4);
231 $path = "" unless $path;
233 my ($them,$port) = split(/:/, $serverstring);
234 $port = 80 unless $port;
239 $serverstring = $http_proxy if $http_proxy;
240 ($them2,$port2) = split(/:/, $serverstring);
241 $port2 = 80 unless $port2;
244 my ($remote, $iaddr, $paddr, $proto, $line);
246 if ($port2 =~ /\D/) { $port2 = getservbyname($port2, 'tcp') }
248 LOG (($verbose_net || $verbose_load), "unrecognised port in $url");
251 $iaddr = inet_aton($remote);
253 LOG (($verbose_net || $verbose_load), "host not found: $remote");
256 $paddr = sockaddr_in($port2, $iaddr);
264 local $SIG{ALRM} = sub {
265 LOG (($verbose_net || $verbose_load), "timed out ($timeout) for $url");
270 $proto = getprotobyname('tcp');
271 if (!socket(S, PF_INET, SOCK_STREAM, $proto)) {
272 LOG (($verbose_net || $verbose_load), "socket: $!");
275 if (!connect(S, $paddr)) {
276 LOG (($verbose_net || $verbose_load), "connect($serverstring): $!");
280 select(S); $| = 1; select(STDOUT);
282 my $cookie = $cookies{$them};
284 my $user_agent = "$progname/$version";
285 if ($url =~ m@^http://www\.altavista\.com/@) {
286 # block this, you turkeys.
287 $user_agent = "Mozilla/4.76 [en] (X11; U; Linux 2.2.16-22 i686; Nav)";
290 my $hdrs = "GET " . ($http_proxy ? $url : "/$path") . " HTTP/1.0\r\n" .
292 "User-Agent: $user_agent\r\n";
294 $hdrs .= "Referer: $referer\r\n";
297 my @cc = split(/\r?\n/, $cookie);
298 $hdrs .= "Cookie: " . join('; ', @cc) . "\r\n";
302 foreach (split('\r?\n', $hdrs)) {
303 LOG ($verbose_http, " ==> $_");
306 my $http = <S> || "";
310 LOG ($verbose_http, " <== $_");
316 LOG ($verbose_http, " <== $_");
318 if (m@^Set-cookie:\s*([^;\r\n]+)@i) {
319 set_cookie($them, $1)
330 " <== [ body ]: $lines lines, " . length($body) . " bytes");
335 LOG (($verbose_net || $verbose_load), "null response: $url");
339 return ( $http, $head, $body );
341 die if ($@ && $@ ne "alarm\n"); # propagate errors
356 # returns two values: the document headers; and the document body.
357 # if the given URL did a redirect, returns the redirected-to document.
360 my ( $url, $referer, $timeout ) = @_;
363 if (defined($referer) && $referer eq $driftnet_magic) {
364 return get_driftnet_file ($url);
369 my $max_loop_count = 4;
372 if (defined($timeout) && $timeout <= 0) {
373 LOG (($verbose_net || $verbose_load), "timed out for $url");
378 my ( $http, $head, $body ) = get_document_1 ($url, $referer, $timeout);
380 if (defined ($timeout)) {
382 my $elapsed = $now - $start;
383 $timeout -= $elapsed;
387 return () unless $http; # error message already printed
389 $http =~ s/[\r\n]+$//s;
391 if ( $http =~ m@^HTTP/[0-9.]+ 30[123]@ ) {
393 my ( $location ) = m@^location:[ \t]*(.*)$@im;
395 $location =~ s/[\r\n]$//;
397 LOG ($verbose_net, "redirect from $url to $location");
402 $referer =~ m@^(http://[^/]+)@i;
404 } elsif (! ($url =~ m@^[a-z]+:@i)) {
406 s@[^/]+$@@g if m@^http://[^/]+/@i;
407 $_ .= "/" if m@^http://[^/]+$@i;
412 LOG ($verbose_net, "no Location with \"$http\"");
413 return ( $url, $body );
416 if ($loop_count++ > $max_loop_count) {
418 "too many redirects ($max_loop_count) from $orig_url");
423 } elsif ( $http =~ m@^HTTP/[0-9.]+ ([4-9][0-9][0-9].*)$@ ) {
425 LOG (($verbose_net || $verbose_load), "failed: $1 ($url)");
427 # http errors -- return nothing.
433 LOG (($verbose_net || $verbose_load), "document contains no data: $url");
439 return ( $url, $body );
445 # If we already have a cookie defined for this site, and the site is trying
446 # to overwrite that very same cookie, let it do so. This is because nytimes
447 # expires its cookies - it lets you upgrade to a new cookie without logging
448 # in again, but you have to present the old cookie to get the new cookie.
449 # So, by doing this, the built-in cypherpunks cookie will never go "stale".
452 my ($host, $cookie) = @_;
453 my $oc = $cookies{$host};
456 my ($oc_name, $oc_value) = m@^([^= \t\r\n]+)=(.*)$@;
458 my ($nc_name, $nc_value) = m@^([^= \t\r\n]+)=(.*)$@;
460 if ($oc_name eq $nc_name &&
461 $oc_value ne $nc_value) {
462 $cookies{$host} = $cookie;
463 LOG ($verbose_net, "overwrote ${host}'s $oc_name cookie");
468 ############################################################################
470 # Extracting image URLs from HTML
472 ############################################################################
474 # given a URL and the body text at that URL, selects and returns a random
475 # image from it. returns () if no suitable images found.
477 sub pick_image_from_body {
478 my ( $url, $body ) = @_;
483 # if there's at least one slash after the host, take off the last
485 if ( m@^http://[^/]+/@io ) {
486 $base =~ s@[^/]+$@@go;
489 # if there are no slashes after the host at all, put one on the end.
490 if ( m@^http://[^/]+$@io ) {
496 # strip out newlines, compress whitespace
503 # There are certain web sites that list huge numbers of dictionary
504 # words in their bodies or in their <META NAME=KEYWORDS> tags (surprise!
505 # Porn sites tend not to be reputable!)
507 # I do not want webcollage to filter on content: I want it to select
508 # randomly from the set of images on the web. All the logic here for
509 # rejecting some images is really a set of heuristics for rejecting
510 # images that are not really images: for rejecting *text* that is in
511 # GIF/JPEG form. I don't want text, I want pictures, and I want the
512 # content of the pictures to be randomly selected from among all the
515 # So, filtering out "dirty" pictures by looking for "dirty" keywords
516 # would be wrong: dirty pictures exist, like it or not, so webcollage
517 # should be able to select them.
519 # However, picking a random URL is a hard thing to do. The mechanism I'm
520 # using is to search for a selection of random words. This is not
521 # perfect, but works ok most of the time. The way it breaks down is when
522 # some URLs get precedence because their pages list *every word* as
523 # related -- those URLs come up more often than others.
525 # So, after we've retrieved a URL, if it has too many keywords, reject
526 # it. We reject it not on the basis of what those keywords are, but on
527 # the basis that by having so many, the page has gotten an unfair
528 # advantage against our randomizer.
531 foreach my $trip (@tripwire_words) {
532 $trip_count++ if m/$trip/i;
535 if ($trip_count >= $#tripwire_words - 2) {
536 LOG (($verbose_filter || $verbose_load),
537 "there is probably a dictionary in \"$url\": rejecting.");
538 $rejected_urls{$url} = -1;
548 foreach (split(/ *</)) {
551 # Likewise, reject any web pages that have a KEYWORDS meta tag
554 if (m/name ?= ?\"?keywords\"?/i &&
555 m/content ?= ?\"([^\"]+)\"/) {
558 LOG (($verbose_filter || $verbose_load),
559 "excessive keywords ($L bytes) in $url: rejecting.");
560 $rejected_urls{$url} = $L;
565 LOG ($verbose_filter, " keywords ($L bytes) in $url (ok)");
569 } elsif ( m/^(img|a) .*(src|href) ?= ?\"? ?(.*?)[ >\"]/io ) {
571 my $was_inline = ( "$1" eq "a" || "$1" eq "A" );
573 my ( $width ) = m/width ?=[ \"]*(\d+)/oi;
574 my ( $height ) = m/height ?=[ \"]*(\d+)/oi;
579 ( $site = $base ) =~ s@^(http://[^/]*).*@$1@gio;
581 } elsif ( ! m@^[^/:?]+:@ ) {
584 while (s@/\.\./@/@g) {
589 if ( ! m@^http://@io ) {
594 if ( ! m@[.](gif|jpg|jpeg|pjpg|pjpeg)$@io ) {
598 # skip really short or really narrow images
599 if ( $width && $width < $min_width) {
600 if (!$height) { $height = "?"; }
601 LOG ($verbose_filter, " skip narrow image $_ (${width}x$height)");
605 if ( $height && $height < $min_height) {
606 if (!$width) { $width = "?"; }
607 LOG ($verbose_filter, " skip short image $_ (${width}x$height)");
611 # skip images with ratios that make them look like banners.
612 if ($min_ratio && $width && $height &&
613 ($width * $min_ratio ) > $height) {
614 if (!$height) { $height = "?"; }
615 LOG ($verbose_filter, " skip bad ratio $_ (${width}x$height)");
619 # skip GIFs with a small number of pixels -- those usually suck.
620 if ($width && $height &&
622 ($width * $height) < $min_gif_area) {
623 LOG ($verbose_filter, " skip small GIF $_ (${width}x$height)");
630 if ($unique_urls{$url}) {
631 LOG ($verbose_filter, " skip duplicate image $_");
635 LOG ($verbose_filter,
637 ($width && $height ? " (${width}x${height})" : "") .
638 ($was_inline ? " (inline)" : ""));
640 $urls[++$#urls] = $url;
641 $unique_urls{$url}++;
643 # jpegs are preferable to gifs.
645 if ( ! m@[.]gif$@io ) {
646 $urls[++$#urls] = $url;
649 # pointers to images are preferable to inlined images.
650 if ( ! $was_inline ) {
651 $urls[++$#urls] = $url;
652 $urls[++$#urls] = $url;
657 my $fsp = ($body =~ m@<frameset@i);
662 @urls = depoison (@urls);
665 LOG ($verbose_load, "no images on $base" . ($fsp ? " (frameset)" : ""));
669 # pick a random element of the table
670 my $i = int(rand($#urls+1));
673 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#urls+1) . ": $url");
680 ############################################################################
682 # Subroutines for getting pages and images out of search engines
684 ############################################################################
687 sub pick_dictionary {
688 my @dicts = ("/usr/dict/words",
689 "/usr/share/dict/words",
690 "/usr/share/lib/dict/words");
691 foreach my $f (@dicts) {
697 error ("$dicts[0] does not exist") unless defined($wordlist);
700 # returns a random word from the dictionary
704 if (open (IN, "<$wordlist")) {
705 my $size = (stat(IN))[7];
706 my $pos = rand $size;
707 if (seek (IN, $pos, 0)) {
708 $word = <IN>; # toss partial line
709 $word = <IN>; # keep next line
718 return 0 if (!$word);
720 $word =~ s/^[ \t\n\r]+//;
721 $word =~ s/[ \t\n\r]+$//;
726 $word =~ s/ally$/al/;
727 $word =~ s/izes$/ize/;
728 $word =~ tr/A-Z/a-z/;
730 if ( $word =~ s/[ \t\n\r]/\+/g ) { # convert intra-word spaces to "+".
731 $word = "\%22$word\%22"; # And put quotes (%22) around it.
739 my $sep = ($or_p ? "%20OR%20" : "%20");
740 return (random_word . $sep .
750 $s =~ s|([^-a-zA-Z0-9.\@/_\r\n])|sprintf("%%%02X", ord($1))|ge;
757 $s =~ s/%([a-z0-9]{2})/chr(hex($1))/ige;
762 # Loads the given URL (a search on some search engine) and returns:
763 # - the total number of hits the search engine claimed it had;
764 # - a list of URLs from the page that the search engine returned;
765 # Note that this list contains all kinds of internal search engine
766 # junk URLs too -- caller must prune them.
768 sub pick_from_search_engine {
769 my ( $timeout, $search_url, $words ) = @_;
774 print STDERR "\n\n" if ($verbose_load);
776 LOG ($verbose_load, "words: $_");
777 LOG ($verbose_load, "URL: $search_url");
779 $last_search = $search_url; # for warnings
782 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
783 if (defined ($timeout)) {
784 $timeout -= (time - $start);
787 LOG (($verbose_net || $verbose_load),
788 "timed out (late) for $search_url");
794 return () if (! $body);
799 my $search_count = "?";
800 if ($body =~ m@found (approximately |about )?(<B>)?(\d+)(</B>)? image@) {
802 } elsif ($body =~ m@<NOBR>((\d{1,3})(,\d{3})*) @i) {
804 } elsif ($body =~ m@found ((\d{1,3})(,\d{3})*|\d+) Web p@) {
806 } elsif ($body =~ m@found about ((\d{1,3})(,\d{3})*|\d+) results@) {
808 } elsif ($body =~ m@\b\d+ - \d+ of (\d+)\b@i) { # imagevista
810 } elsif ($body =~ m@About ((\d{1,3})(,\d{3})*) images@i) { # imagevista
812 } elsif ($body =~ m@We found ((\d{1,3})(,\d{3})*|\d+) results@i) { # *vista
814 } elsif ($body =~ m@ of about <B>((\d{1,3})(,\d{3})*)<@i) { # googleimages
816 } elsif ($body =~ m@<B>((\d{1,3})(,\d{3})*)</B> Web sites were found@i) {
817 $search_count = $1; # lycos
818 } elsif ($body =~ m@WEB.*?RESULTS.*?\b((\d{1,3})(,\d{3})*)\b.*?Matches@i) {
819 $search_count = $1; # hotbot
820 } elsif ($body =~ m@no photos were found containing@i) { # imagevista
822 } elsif ($body =~ m@found no document matching@i) { # altavista
825 1 while ($search_count =~ s/^(\d+)(\d{3})/$1,$2/);
827 # if ($search_count eq "?" || $search_count eq "0") {
829 # my $file = "/tmp/wc.html";
830 # open(OUT, ">$file") || error ("writing $file: $!");
833 # print STDERR blurb() . "###### wrote $file\n";
837 my $length = length($body);
846 foreach (split(/\n/)) {
848 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
851 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
852 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
854 if ( $rejected_urls{$u} ) {
855 LOG ($verbose_filter, " pre-rejecting candidate: $u");
859 LOG ($verbose_http, " HREF: $u");
861 $subpages[++$#subpages] = $u;
864 if ( $#subpages < 0 ) {
865 LOG ($verbose_filter,
866 "found nothing on $base ($length bytes, $href_count links).");
870 LOG ($verbose_filter, "" . $#subpages+1 . " links on $search_url");
872 return ($search_count, @subpages);
880 my ($h) = m@^http://([^/: \t\r\n]+)@i;
882 next unless defined($h);
884 if ($poisoners{$h}) {
885 LOG (($verbose_filter), " rejecting poisoner: $_");
888 if ($h =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
890 LOG (($verbose_filter), " rejecting poisoner: $_");
893 if ($h =~ m@([^.]+\.[^.]+)$@ &&
895 LOG (($verbose_filter), " rejecting poisoner: $_");
905 # given a list of URLs, picks one at random; loads it; and returns a
906 # random image from it.
907 # returns the url of the page loaded; the url of the image chosen;
908 # and a debugging description string.
910 sub pick_image_from_pages {
911 my ($base, $total_hit_count, $unfiltered_link_count, $timeout, @pages) = @_;
913 $total_hit_count = "?" unless defined($total_hit_count);
915 @pages = depoison (@pages);
917 "" . ($#pages+1) . " candidates of $unfiltered_link_count links" .
918 " ($total_hit_count total)");
920 return () if ($#pages < 0);
922 my $i = int(rand($#pages+1));
923 my $page = $pages[$i];
925 LOG ($verbose_load, "picked page $page");
929 my ( $base2, $body2 ) = get_document ($page, $base, $timeout);
931 if (!$base2 || !$body2) {
936 my $img = pick_image_from_body ($base2, $body2);
940 return ($base2, $img);
947 ############################################################################
949 # Pick images from random pages returned by the Yahoo Random Link
951 ############################################################################
954 my $yahoo_random_link = "http://random.yahoo.com/bin/ryl";
957 # Picks a random page; picks a random image on that page;
958 # returns two URLs: the page containing the image, and the image.
959 # Returns () if nothing found this time.
961 sub pick_from_yahoo_random_link {
962 my ( $timeout ) = @_;
964 print STDERR "\n\n" if ($verbose_load);
965 LOG ($verbose_load, "URL: $yahoo_random_link");
967 $last_search = $yahoo_random_link; # for warnings
971 my ( $base, $body ) = get_document ($yahoo_random_link, undef, $timeout);
972 if (!$base || !$body) {
977 LOG ($verbose_load, "redirected to: $base");
979 my $img = pick_image_from_body ($base, $body);
983 return ($base, $img);
990 ############################################################################
992 # Pick images by feeding random words into Alta Vista Image Search
994 ############################################################################
997 my $alta_vista_images_url = "http://www.altavista.com/cgi-bin/query" .
999 "&igrph=1" . # graphics
1002 "&micat=1" . # no partner sites
1003 "&imgset=1" . # no partner sites
1004 "&stype=simage" . # do image search
1005 "&mmW=1" . # unknown, but required
1009 sub pick_from_alta_vista_images {
1010 my ( $timeout ) = @_;
1012 my $words = random_words(1);
1013 my $page = (int(rand(9)) + 1);
1014 my $search_url = $alta_vista_images_url . $words;
1017 $search_url .= "&pgno=" . $page; # page number
1018 $search_url .= "&stq=" . (($page-1) * 12); # first hit result on page
1021 my ($search_hit_count, @subpages) =
1022 pick_from_search_engine ($timeout, $search_url, $words);
1024 my @candidates = ();
1025 foreach my $u (@subpages) {
1027 # altavista is encoding their URLs now.
1028 next unless ($u =~ m@^/r.*\&r=([^&]+).*@);
1029 $u = url_unquote($1);
1031 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1032 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
1033 next if ($u =~ m@[/.]doubleclick\.net\b@i); # you cretins
1034 next if ($u =~ m@[/.]clicktomarket\.com\b@i); # more cretins
1036 next if ($u =~ m@[/.]viewimages\.com\b@i); # stacked deck
1037 next if ($u =~ m@[/.]gettyimages\.com\b@i);
1039 LOG ($verbose_filter, " candidate: $u");
1040 push @candidates, $u;
1043 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1044 $timeout, @candidates);
1049 ############################################################################
1051 # Pick images by feeding random words into Google Image Search.
1052 # By Charles Gales <gales@us.ibm.com>
1054 ############################################################################
1057 my $google_images_url = "http://images.google.com/images" .
1058 "?site=images" . # photos
1059 "&btnG=Search" . # graphics
1060 "&safe=off" . # no screening
1065 sub pick_from_google_images {
1066 my ( $timeout ) = @_;
1068 my $words = random_word; # only one word for Google
1069 my $page = (int(rand(9)) + 1);
1070 my $num = 20; # 20 images per page
1071 my $search_url = $google_images_url . $words;
1074 $search_url .= "&start=" . $page*$num; # page number
1075 $search_url .= "&num=" . $num; #images per page
1078 my ($search_hit_count, @subpages) =
1079 pick_from_search_engine ($timeout, $search_url, $words);
1081 my @candidates = ();
1082 foreach my $u (@subpages) {
1083 next unless ($u =~ m@imgres\?imgurl@i); # All pics start with this
1084 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins
1086 if ($u =~ m@^/imgres\?imgurl=(.*?)\&imgrefurl=(.*?)\&@) {
1088 LOG ($verbose_filter, " candidate: $urlf");
1089 push @candidates, $urlf;
1093 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1094 $timeout, @candidates);
1099 ############################################################################
1101 # Pick images by feeding random *numbers* into Google Image Search.
1102 # By jwz, suggested by from Ian O'Donnell.
1104 ############################################################################
1108 sub pick_from_google_image_numbers {
1109 my ( $timeout ) = @_;
1112 my $number = int(rand($max));
1114 $number = sprintf("%04d", $number)
1117 my $words = "$number";
1118 my $page = (int(rand(40)) + 1);
1119 my $num = 20; # 20 images per page
1120 my $search_url = $google_images_url . $words;
1123 $search_url .= "&start=" . $page*$num; # page number
1124 $search_url .= "&num=" . $num; #images per page
1127 my ($search_hit_count, @subpages) =
1128 pick_from_search_engine ($timeout, $search_url, $words);
1130 my @candidates = ();
1132 foreach my $u (@subpages) {
1133 next unless ($u =~ m@imgres\?imgurl@i); # All pics start with this
1134 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins
1136 if ($u =~ m@^/imgres\?imgurl=(.*?)\&imgrefurl=(.*?)\&@) {
1138 my $img = "http://$1";
1140 LOG ($verbose_filter, " candidate: $ref");
1141 push @candidates, $img;
1142 $referers{$img} = $ref;
1146 @candidates = depoison (@candidates);
1147 return () if ($#candidates < 0);
1148 my $i = int(rand($#candidates+1));
1149 my $img = $candidates[$i];
1150 my $ref = $referers{$img};
1152 LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1153 return ($ref, $img);
1158 ############################################################################
1160 # Pick images by feeding random words into Alta Vista Text Search
1162 ############################################################################
1165 my $alta_vista_url_1 = "http://www.altavista.com/cgi-bin/query?pg=q" .
1166 "&text=yes&kl=XX&stype=stext&q=";
1167 my $alta_vista_url_2 = "http://www.altavista.com/sites/search/web?pg=q" .
1168 "&kl=XX&search=Search&q=";
1170 my $alta_vista_url = $alta_vista_url_2;
1173 sub pick_from_alta_vista_text {
1174 my ( $timeout ) = @_;
1176 my $words = random_words(1);
1177 my $page = (int(rand(9)) + 1);
1178 my $search_url = $alta_vista_url . $words;
1181 $search_url .= "&pgno=" . $page;
1182 $search_url .= "&stq=" . (($page-1) * 10);
1185 my ($search_hit_count, @subpages) =
1186 pick_from_search_engine ($timeout, $search_url, $words);
1188 my @candidates = ();
1189 foreach my $u (@subpages) {
1191 # Those altavista fuckers are playing really nasty redirection games
1192 # these days: the filter your clicks through their site, but use
1193 # onMouseOver to make it look like they're not! Well, it makes it
1194 # easier for us to identify search results...
1196 next unless ($u =~ m@^/r.*\&r=([^&]+).*@);
1197 $u = url_unquote($1);
1199 LOG ($verbose_filter, " candidate: $u");
1200 push @candidates, $u;
1203 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1204 $timeout, @candidates);
1209 ############################################################################
1211 # Pick images by feeding random words into Hotbot
1213 ############################################################################
1215 my $hotbot_search_url = "http://hotbot.lycos.com/" .
1227 sub pick_from_hotbot_text {
1228 my ( $timeout ) = @_;
1230 my $words = random_words(0);
1231 my $search_url = $hotbot_search_url . $words;
1233 my ($search_hit_count, @subpages) =
1234 pick_from_search_engine ($timeout, $search_url, $words);
1236 my @candidates = ();
1237 foreach my $u (@subpages) {
1239 # Hotbot plays redirection games too
1240 next unless ($u =~ m@^/director.asp\?target=([^&]+)@);
1241 $u = url_decode($1);
1243 LOG ($verbose_filter, " candidate: $u");
1244 push @candidates, $u;
1247 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1248 $timeout, @candidates);
1253 ############################################################################
1255 # Pick images by feeding random words into Lycos
1257 ############################################################################
1259 my $lycos_search_url = "http://lycospro.lycos.com/srchpro/" .
1264 sub pick_from_lycos_text {
1265 my ( $timeout ) = @_;
1267 my $words = random_words(0);
1268 my $start = int(rand(8)) * 10 + 1;
1269 my $search_url = $lycos_search_url . $words . "&start=$start";
1271 my ($search_hit_count, @subpages) =
1272 pick_from_search_engine ($timeout, $search_url, $words);
1274 my @candidates = ();
1275 foreach my $u (@subpages) {
1277 # Lycos plays exact the same redirection game as hotbot.
1278 # Note that "id=0" is used for internal advertising links,
1279 # and 1+ are used for search results.
1280 next unless ($u =~ m@^http://click.hotbot.com/director.asp
1287 $u = url_decode($1);
1289 LOG ($verbose_filter, " candidate: $u");
1290 push @candidates, $u;
1293 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1294 $timeout, @candidates);
1299 ############################################################################
1301 # Pick images by feeding random words into news.yahoo.com
1303 ############################################################################
1305 my $yahoo_news_url = "http://search.news.yahoo.com/search/news_photos?" .
1306 "&z=&n=100&o=o&2=&3=&p=";
1309 sub pick_from_yahoo_news_text {
1310 my ( $timeout ) = @_;
1312 my $words = random_words(1);
1313 my $search_url = $yahoo_news_url . $words;
1315 my ($search_hit_count, @subpages) =
1316 pick_from_search_engine ($timeout, $search_url, $words);
1318 my @candidates = ();
1319 foreach my $u (@subpages) {
1320 # only accept URLs on Yahoo's news site
1321 next unless ($u =~ m@^http://dailynews\.yahoo\.com/@i ||
1322 $u =~ m@^http://story\.news\.yahoo\.com/@i);
1324 LOG ($verbose_filter, " candidate: $u");
1325 push @candidates, $u;
1328 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1329 $timeout, @candidates);
1335 ############################################################################
1337 # Pick images by waiting for driftnet to populate a temp dir with files.
1338 # Requires driftnet version 0.1.5 or later.
1339 # (Driftnet is a program by Chris Lightfoot that sniffs your local ethernet
1340 # for images being downloaded by others.)
1341 # Driftnet/webcollage integration by jwz.
1343 ############################################################################
1346 sub pick_from_driftnet {
1347 my ( $timeout ) = @_;
1349 my $id = $driftnet_magic;
1350 my $dir = $driftnet_dir;
1354 error ("\$driftnet_dir unset?") unless ($dir);
1357 error ("$dir unreadable") unless (-d "$dir/.");
1359 $timeout = $http_timeout unless ($timeout);
1362 while ($now = time, $now < $start + $timeout) {
1364 opendir (DIR, $dir) || error ("$dir: $!");
1365 while (my $file = readdir(DIR)) {
1366 next if ($file =~ m/^\./);
1367 $file = "$dir/$file";
1369 LOG ($verbose_load, "picked file $file ($id)");
1370 return ($id, $file);
1374 LOG (($verbose_net || $verbose_load), "timed out for $id");
1379 sub get_driftnet_file {
1382 error ("\$driftnet_dir unset?") unless ($driftnet_dir);
1384 my $id = $driftnet_magic;
1385 my $re = qr/$driftnet_dir/;
1386 error ("$id: $file not in $driftnet_dir?")
1387 unless ($file =~ m@^$re@o);
1390 open (IN, $file) || error ("$id: $file: $!");
1392 while (<IN>) { $body .= $_; }
1395 return ($id, $body);
1399 sub spawn_driftnet {
1402 # make a directory to use.
1404 my $tmp = $ENV{TEMPDIR} || "/tmp";
1405 $driftnet_dir = sprintf ("$tmp/driftcollage-%08x", rand(0xffffffff));
1406 LOG ($verbose_exec, "mkdir $driftnet_dir");
1407 last if mkdir ($driftnet_dir, 0700);
1410 if (! ($cmd =~ m/\s/)) {
1411 # if the command didn't have any arguments in it, then it must be just
1412 # a pointer to the executable. Append the default args to it.
1413 my $dargs = $default_driftnet_cmd;
1414 $dargs =~ s/^[^\s]+//;
1418 # point the driftnet command at our newly-minted private directory.
1420 $cmd .= " -d $driftnet_dir";
1421 $cmd .= ">/dev/null" unless ($verbose_exec);
1424 if ($pid < 0) { error ("fork: $!\n"); }
1427 push @pids_to_kill, $pid;
1428 LOG ($verbose_exec, "forked for \"$cmd\"");
1431 nontrapping_system ($cmd) || error ("exec: $!");
1434 # wait a bit, then make sure the process actually started up.
1437 error ("pid $pid failed to start \"$cmd\"")
1438 unless (1 == kill (0, $pid));
1442 ############################################################################
1444 # Pick a random image in a random way
1446 ############################################################################
1449 # Picks a random image on a random page, and returns two URLs:
1450 # the page containing the image, and the image.
1451 # Returns () if nothing found this time.
1455 my ( $timeout ) = @_;
1457 $current_state = "select";
1458 $load_method = "none";
1460 my $n = int(rand(100));
1463 my @rest = @search_methods;
1466 my $pct = shift @rest;
1467 my $name = shift @rest;
1468 my $tfn = shift @rest;
1470 if ($total > $n && !defined($fn)) {
1472 $current_state = $name;
1473 $load_method = $current_state;
1477 if ($total != 100) {
1478 error ("internal error: \@search_methods totals to $total%!");
1481 record_attempt ($current_state);
1482 return $fn->($timeout);
1487 ############################################################################
1489 # Statistics and logging
1491 ############################################################################
1494 return strftime ("%H:%M:%S: ", localtime);
1498 return "$progname: " . timestr() . "$current_state: ";
1503 print STDERR blurb() . "$err\n";
1515 my $head = "$progname: DEBUG: ";
1516 foreach (split (/\n/, $lastlog)) {
1517 print STDERR "$head$_\n";
1523 my ($print, $msg) = @_;
1524 my $blurb = timestr() . "$current_state: ";
1525 $lastlog .= "$blurb$msg\n";
1526 print STDERR "$progname: $blurb$msg\n" if $print;
1531 my %stats_successes;
1534 my $last_state = undef;
1535 sub record_attempt {
1539 record_failure($last_state) unless ($image_succeeded > 0);
1541 $last_state = $name;
1544 report_performance();
1547 $image_succeeded = 0;
1548 $suppress_audit = 0;
1551 sub record_success {
1552 my ($name, $url, $base) = @_;
1553 if (defined($stats_successes{$name})) {
1554 $stats_successes{$name}++;
1556 $stats_successes{$name} = 1;
1559 stop_timer ($name, 1);
1560 my $o = $current_state;
1561 $current_state = $name;
1562 save_recent_url ($url, $base);
1563 $current_state = $o;
1564 $image_succeeded = 1;
1569 sub record_failure {
1572 return if $image_succeeded;
1574 stop_timer ($name, 0);
1575 if ($verbose_load && !$verbose_exec) {
1577 if ($suppress_audit) {
1578 print STDERR "$progname: " . timestr() . "(audit log suppressed)\n";
1582 my $o = $current_state;
1583 $current_state = "DEBUG";
1585 my $line = "#" x 78;
1586 print STDERR "\n\n\n";
1587 print STDERR ("#" x 78) . "\n";
1588 print STDERR blurb() . "failed to get an image. Full audit log:\n";
1591 print STDERR ("-" x 78) . "\n";
1592 print STDERR "\n\n";
1594 $current_state = $o;
1596 $image_succeeded = 0;
1603 my $i = $stats_successes{$name};
1604 my $j = $stats_attempts{$name};
1607 return "" . ($j ? int($i * 100 / $j) : "0") . "%";
1611 my $current_start_time = 0;
1615 $current_start_time = time;
1617 if (defined($stats_attempts{$name})) {
1618 $stats_attempts{$name}++;
1620 $stats_attempts{$name} = 1;
1622 if (!defined($stats_elapsed{$name})) {
1623 $stats_elapsed{$name} = 0;
1628 my ($name, $success) = @_;
1629 $stats_elapsed{$name} += time - $current_start_time;
1633 my $last_report_time = 0;
1634 sub report_performance {
1636 return unless $verbose_warnings;
1639 return unless ($now >= $last_report_time + $report_performance_interval);
1640 my $ot = $last_report_time;
1641 $last_report_time = $now;
1643 return if ($ot == 0);
1645 my $blurb = "$progname: " . timestr();
1648 print STDERR "${blurb}Current standings:\n";
1650 foreach my $name (sort keys (%stats_attempts)) {
1651 my $try = $stats_attempts{$name};
1652 my $suc = $stats_successes{$name} || 0;
1653 my $pct = int($suc * 100 / $try);
1654 my $secs = $stats_elapsed{$name};
1655 my $secs_link = int($secs / $try);
1656 print STDERR sprintf ("$blurb %-12s %4s (%d/%d);\t %2d secs/link\n",
1657 "$name:", "$pct%", $suc, $try, $secs_link);
1663 my $max_recent_images = 400;
1664 my $max_recent_sites = 20;
1665 my @recent_images = ();
1666 my @recent_sites = ();
1668 sub save_recent_url {
1669 my ($url, $base) = @_;
1671 return unless ($verbose_warnings);
1674 my ($site) = m@^http://([^ \t\n\r/:]+)@;
1676 if ($base eq $driftnet_magic) {
1677 $site = $driftnet_magic;
1678 @recent_images = ();
1682 foreach (@recent_images) {
1684 print STDERR blurb() . "WARNING: recently-duplicated image: $url" .
1685 " (on $base via $last_search)\n";
1691 # suppress "duplicate site" warning via %warningless_sites.
1693 if ($warningless_sites{$site}) {
1695 } elsif ($site =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
1696 $warningless_sites{$1}) {
1698 } elsif ($site =~ m@([^.]+\.[^.]+)$@ &&
1699 $warningless_sites{$1}) {
1704 foreach (@recent_sites) {
1706 print STDERR blurb() . "WARNING: recently-duplicated site: $site" .
1707 " ($url on $base via $last_search)\n";
1713 push @recent_images, $url;
1714 push @recent_sites, $site;
1715 shift @recent_images if ($#recent_images >= $max_recent_images);
1716 shift @recent_sites if ($#recent_sites >= $max_recent_sites);
1721 ##############################################################################
1725 ##############################################################################
1732 s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
1737 # Given the raw body of a GIF document, returns the dimensions of the image.
1741 my $type = substr($body, 0, 6);
1743 return () unless ($type =~ /GIF8[7,9]a/);
1744 $s = substr ($body, 6, 10);
1745 my ($a,$b,$c,$d) = unpack ("C"x4, $s);
1746 return (($b<<8|$a), ($d<<8|$c));
1749 # Given the raw body of a JPEG document, returns the dimensions of the image.
1754 my $L = length($body);
1756 my $c1 = substr($body, $i, 1); $i++;
1757 my $c2 = substr($body, $i, 1); $i++;
1758 return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
1761 while (ord($ch) != 0xDA && $i < $L) {
1762 # Find next marker, beginning with 0xFF.
1763 while (ord($ch) != 0xFF) {
1764 return () if (length($body) <= $i);
1765 $ch = substr($body, $i, 1); $i++;
1767 # markers can be padded with any number of 0xFF.
1768 while (ord($ch) == 0xFF) {
1769 return () if (length($body) <= $i);
1770 $ch = substr($body, $i, 1); $i++;
1773 # $ch contains the value of the marker.
1774 my $marker = ord($ch);
1776 if (($marker >= 0xC0) &&
1777 ($marker <= 0xCF) &&
1778 ($marker != 0xC4) &&
1779 ($marker != 0xCC)) { # it's a SOFn marker
1781 return () if (length($body) <= $i);
1782 my $s = substr($body, $i, 4); $i += 4;
1783 my ($a,$b,$c,$d) = unpack("C"x4, $s);
1784 return (($c<<8|$d), ($a<<8|$b));
1787 # We must skip variables, since FFs in variable names aren't
1788 # valid JPEG markers.
1789 return () if (length($body) <= $i);
1790 my $s = substr($body, $i, 2); $i += 2;
1791 my ($c1, $c2) = unpack ("C"x2, $s);
1792 my $length = ($c1 << 8) | $c2;
1793 return () if ($length < 2);
1800 # Given the raw body of a GIF or JPEG document, returns the dimensions of
1805 my ($w, $h) = gif_size ($body);
1806 if ($w && $h) { return ($w, $h); }
1807 return jpeg_size ($body);
1811 # returns the full path of the named program, or undef.
1815 foreach (split (/:/, $ENV{PATH})) {
1816 if (-x "$_/$prog") {
1824 # Like rand(), but chooses numbers with a bell curve distribution.
1827 $_ = 1.0 unless defined($_);
1829 return (rand($_) + rand($_) + rand($_));
1833 sub signal_cleanup {
1835 print STDERR blurb() . (defined($sig)
1836 ? "caught signal $sig."
1843 if (@pids_to_kill) {
1844 print STDERR blurb() . "killing: " . join(' ', @pids_to_kill) . "\n";
1845 kill ('TERM', @pids_to_kill);
1851 ##############################################################################
1853 # Generating a list of urls only
1855 ##############################################################################
1857 sub url_only_output {
1859 my ($base, $img) = pick_image;
1863 print "$img $base\n";
1868 ##############################################################################
1870 # Running as an xscreensaver module
1872 ##############################################################################
1874 my $image_ppm = ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp") . "/webcollage." . $$;
1875 my $image_tmp1 = $image_ppm . "-1";
1876 my $image_tmp2 = $image_ppm . "-2";
1878 my $filter_cmd = undef;
1879 my $post_filter_cmd = undef;
1880 my $background = undef;
1882 my $img_width; # size of the image being generated.
1888 unlink $image_ppm, $image_tmp1, $image_tmp2;
1892 # Like system, but prints status about exit codes, and kills this process
1893 # with whatever signal killed the sub-process, if any.
1895 sub nontrapping_system {
1899 s/\"[^\"]+\"/\"...\"/g;
1901 LOG ($verbose_exec, "executing \"$_\"");
1906 LOG ($verbose_exec, "subproc exited normally.");
1907 } elsif (($rc & 0xff) == 0) {
1909 LOG ($verbose_exec, "subproc exited with status $rc.");
1912 LOG ($verbose_exec, "subproc dumped core.");
1915 LOG ($verbose_exec, "subproc died with signal $rc.");
1916 # die that way ourselves.
1924 # Given the URL of a GIF or JPEG image, and the body of that image, writes a
1925 # PPM to the given output file. Returns the width/height of the image if
1929 my ($url, $body, $output) = @_;
1930 my ($cmd, $cmd2, $w, $h);
1932 if ((@_ = gif_size ($body))) {
1935 } elsif ((@_ = jpeg_size ($body))) {
1939 LOG (($verbose_pbm || $verbose_load),
1940 "not a GIF or JPG" .
1941 (($body =~ m@<(base|html|head|body|script|table|a href)>@i)
1942 ? " (looks like HTML)" : "") .
1944 $suppress_audit = 1;
1948 $cmd2 = "exec $cmd"; # yes, this really is necessary. if we don't
1949 # do this, the process doesn't die properly.
1950 if (!$verbose_pbm) {
1952 # We get a "giftopnm: got a 'Application Extension' extension"
1953 # warning any time it's an animgif.
1955 # Note that "giftopnm: EOF / read error on image data" is not
1956 # always a fatal error -- sometimes the image looks fine anyway.
1958 $cmd2 .= " 2>/dev/null";
1961 # There exist corrupted GIF and JPEG files that can make giftopnm and
1962 # djpeg lose their minds and go into a loop. So this gives those programs
1963 # a small timeout -- if they don't complete in time, kill them.
1969 local $SIG{ALRM} = sub {
1971 "timed out ($cvt_timeout) for $cmd on \"$url\" in pid $pid");
1972 kill ('TERM', $pid) if ($pid);
1977 if (($pid = open(PIPE, "| $cmd2 > $output"))) {
1984 LOG ($verbose_exec, "awaiting $pid");
1986 LOG ($verbose_exec, "$pid completed");
1988 my $size = (stat($output))[7];
1989 $size = -1 unless defined($size);
1991 LOG ($verbose_pbm, "$cmd on ${w}x$h \"$url\" failed ($size bytes)");
1995 LOG ($verbose_pbm, "created ${w}x$h $output ($cmd)");
1998 print STDERR blurb() . "$cmd failed: $!\n";
2002 die if ($@ && $@ ne "alarm\n"); # propagate errors
2015 sub pick_root_displayer {
2018 foreach my $cmd (@root_displayers) {
2020 my ($name) = m/^([^ ]+)/;
2021 push @names, "\"$name\"";
2022 LOG ($verbose_exec, "looking for $name...");
2023 foreach my $dir (split (/:/, $ENV{PATH})) {
2024 LOG ($verbose_exec, " checking $dir/$name");
2025 return $cmd if (-x "$dir/$name");
2029 $names[$#names] = "or " . $names[$#names];
2030 error "none of: " . join (", ", @names) . " were found on \$PATH.";
2034 my $ppm_to_root_window_cmd = undef;
2037 sub x_or_pbm_output {
2039 # Check for our helper program, to see whether we need to use PPM pipelines.
2041 $_ = "webcollage-helper";
2042 if (defined ($webcollage_helper) || which ($_)) {
2043 $webcollage_helper = $_ unless (defined($webcollage_helper));
2044 LOG ($verbose_pbm, "found \"$webcollage_helper\"");
2045 $webcollage_helper .= " -v";
2047 LOG (($verbose_pbm || $verbose_load), "no $_ program");
2050 # make sure the various programs we execute exist, right up front.
2052 my @progs = ("ppmmake"); # always need this one
2054 if (!defined($webcollage_helper)) {
2055 # Only need these others if we don't have the helper.
2056 @progs = (@progs, "giftopnm", "djpeg", "pnmpaste", "pnmscale", "pnmcut");
2060 which ($_) || error "$_ not found on \$PATH.";
2063 # find a root-window displayer program.
2065 $ppm_to_root_window_cmd = pick_root_displayer();
2067 if (!$img_width || !$img_height) {
2069 which ($_) || error "$_ not found on \$PATH.";
2071 ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
2072 if (!defined($img_height)) {
2073 error "xdpyinfo failed.";
2077 my $bgcolor = "#000000";
2078 my $bgimage = undef;
2081 if ($background =~ m/^\#[0-9a-f]+$/i) {
2082 $bgcolor = $background;
2084 } elsif (-r $background) {
2085 $bgimage = $background;
2087 } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
2088 error "not a color or readable file: $background";
2091 # default to assuming it's a color
2092 $bgcolor = $background;
2096 # Create the sold-colored base image.
2098 $_ = "ppmmake '$bgcolor' $img_width $img_height";
2099 LOG ($verbose_pbm, "creating base image: $_");
2100 nontrapping_system "$_ > $image_ppm";
2102 # Paste the default background image in the middle of it.
2109 open(IMG, "<$bgimage") || error "couldn't open $bgimage: $!";
2111 while (<IMG>) { $body .= $_; }
2114 if ((@_ = gif_size ($body))) {
2116 $cmd = "giftopnm |";
2118 } elsif ((@_ = jpeg_size ($body))) {
2122 } elsif ($body =~ m/^P\d\n(\d+) (\d+)\n/) {
2128 error "$bgimage is not a GIF, JPEG, or PPM.";
2131 my $x = int (($img_width - $iw) / 2);
2132 my $y = int (($img_height - $ih) / 2);
2134 "pasting $bgimage (${iw}x$ih) into base image at $x,$y");
2136 $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
2137 open (IMG, "| $cmd") || error "running $cmd: $!";
2141 LOG ($verbose_exec, "subproc exited normally.");
2142 rename ($image_tmp1, $image_ppm) ||
2143 error "renaming $image_tmp1 to $image_ppm: $!";
2149 my ($base, $img) = pick_image();
2150 my $source = $current_state;
2151 $current_state = "loadimage";
2153 my ($headers, $body) = get_document ($img, $base);
2155 paste_image ($base, $img, $body, $source);
2159 $current_state = "idle";
2160 $load_method = "none";
2162 unlink $image_tmp1, $image_tmp2;
2168 my ($base, $img, $body, $source) = @_;
2170 $current_state = "paste";
2172 $suppress_audit = 0;
2174 LOG ($verbose_pbm, "got $img (" . length($body) . ")");
2178 # If we are using the webcollage-helper, then we do not need to convert this
2179 # image to a PPM. But, if we're using a filter command, we still must, since
2180 # that's what the filters expect (webcollage-helper can read PPMs, so that's
2183 if (defined ($webcollage_helper) &&
2184 !defined ($filter_cmd)) {
2186 ($iw, $ih) = image_size ($body);
2188 LOG (($verbose_pbm || $verbose_load),
2189 "not a GIF or JPG" .
2190 (($body =~ m@<(base|html|head|body|script|table|a href)>@i)
2191 ? " (looks like HTML)" : "") .
2193 $suppress_audit = 1;
2199 open (OUT, ">$image_tmp1") || error ("writing $image_tmp1: $!");
2200 print OUT $body || error ("writing $image_tmp1: $!");
2201 close OUT || error ("writing $image_tmp1: $!");
2204 ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
2207 LOG ($verbose_pbm, "unable to make PBM from $img");
2212 record_success ($load_method, $img, $base);
2215 my $ow = $iw; # used only for error messages
2218 # don't just tack this onto the front of the pipeline -- we want it to
2219 # be able to change the size of the input image.
2222 LOG ($verbose_pbm, "running $filter_cmd");
2224 my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
2226 LOG(($verbose_pbm || $verbose_load), "failed command: \"$filter_cmd\"");
2227 LOG(($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
2230 rename ($image_tmp2, $image_tmp1);
2232 # re-get the width/height in case the filter resized it.
2234 open(IMG, "<$image_tmp1") || return 0;
2237 ($iw, $ih) = m/^(\d+) (\d+)$/;
2239 return 0 unless ($iw && $ih);
2242 my $target_w = $img_width;
2243 my $target_h = $img_height;
2249 # Usually scale the image to fit on the screen -- but sometimes scale it
2250 # to fit on half or a quarter of the screen. Note that we don't merely
2251 # scale it to fit, we instead cut it in half until it fits -- that should
2252 # give a wider distribution of sizes.
2254 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; $scale /= 2; }
2255 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; $scale /= 2; }
2257 if ($iw > $target_w || $ih > $target_h) {
2258 while ($iw > $target_w ||
2263 if ($iw <= 10 || $ih <= 10) {
2264 LOG ($verbose_pbm, "scaling to ${iw}x$ih would have been bogus.");
2268 LOG ($verbose_pbm, "scaling to ${iw}x$ih");
2270 $cmd .= " | pnmscale -xsize $iw -ysize $ih";
2274 my $src = $image_tmp1;
2276 my $crop_x = 0; # the sub-rectangle of the image
2277 my $crop_y = 0; # that we will actually paste.
2281 # The chance that we will randomly crop out a section of an image starts
2282 # out fairly low, but goes up for images that are very large, or images
2283 # that have ratios that make them look like banners (we try to avoid
2284 # banner images entirely, but they slip through when the IMG tags didn't
2285 # have WIDTH and HEIGHT specified.)
2287 my $crop_chance = 0.2;
2288 if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
2289 $crop_chance += 0.2;
2291 if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
2292 $crop_chance += 0.2;
2294 if ($min_ratio && ($iw * $min_ratio) > $ih) {
2295 $crop_chance += 0.7;
2298 if ($crop_chance > 0.1) {
2299 LOG ($verbose_pbm, "crop chance: $crop_chance");
2302 if (rand() < $crop_chance) {
2307 if ($crop_w > $min_width) {
2308 # if it's a banner, select the width linearly.
2309 # otherwise, select a bell.
2310 my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
2313 $crop_w = $min_width + int ($r * ($crop_w - $min_width));
2314 $crop_x = int (rand() * ($ow - $crop_w));
2316 if ($crop_h > $min_height) {
2317 # height always selects as a bell.
2318 $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
2319 $crop_y = int (rand() * ($oh - $crop_h));
2322 if ($crop_x != 0 || $crop_y != 0 ||
2323 $crop_w != $iw || $crop_h != $ih) {
2325 "randomly cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
2329 # Where the image should logically land -- this might be negative.
2331 my $x = int((rand() * ($img_width + $crop_w/2)) - $crop_w*3/4);
2332 my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
2334 # if we have chosen to paste the image outside of the rectangle of the
2335 # screen, then we need to crop it.
2339 $x + $crop_w > $img_width ||
2340 $y + $crop_h > $img_height) {
2343 "cropping for effective paste of ${crop_w}x$crop_h \@ $x,$y");
2345 if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
2346 if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
2348 if ($x + $crop_w >= $img_width) { $crop_w = $img_width - $x - 1; }
2349 if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
2352 # If any cropping needs to happen, add pnmcut.
2354 if ($crop_x != 0 || $crop_y != 0 ||
2355 $crop_w != $iw || $crop_h != $ih) {
2358 $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
2359 LOG ($verbose_pbm, "cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
2362 LOG ($verbose_pbm, "pasting ${iw}x$ih \@ $x,$y in $image_ppm");
2364 $cmd .= " | pnmpaste - $x $y $image_ppm";
2366 $cmd =~ s@^ *\| *@@;
2368 if (defined ($webcollage_helper)) {
2369 $cmd = "$webcollage_helper $image_tmp1 $image_ppm " .
2370 "$scale $opacity " .
2371 "$crop_x $crop_y $x $y " .
2376 # use a PPM pipeline
2378 $_ .= " < $image_tmp1 > $image_tmp2";
2382 $_ = "($_) 2>&1 | sed s'/^/" . blurb() . "/'";
2384 $_ .= " 2> /dev/null";
2387 my $rc = nontrapping_system ($_);
2389 if (defined ($webcollage_helper) && -z $image_ppm) {
2390 LOG (1, "failed command: \"$cmd\"");
2391 print STDERR "\naudit log:\n\n\n";
2392 print STDERR ("#" x 78) . "\n";
2393 print STDERR blurb() . "$image_ppm has zero size\n";
2395 print STDERR "\n\n";
2400 LOG (($verbose_pbm || $verbose_load), "failed command: \"$cmd\"");
2401 LOG (($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
2405 if (!defined ($webcollage_helper)) {
2406 rename ($image_tmp2, $image_ppm) || return;
2409 my $target = "$image_ppm";
2411 # don't just tack this onto the end of the pipeline -- we don't want it
2412 # to end up in $image_ppm, because we don't want the results to be
2415 if ($post_filter_cmd) {
2419 $target = $image_tmp1;
2420 if (!defined ($webcollage_helper)) {
2421 $cmd = "($post_filter_cmd) < $image_ppm > $target";
2423 # Blah, my scripts need the JPEG data, but some other folks need
2424 # the PPM data -- what to do? Ignore the problem, that's what!
2425 # $cmd = "djpeg < $image_ppm | ($post_filter_cmd) > $target";
2426 $cmd = "($post_filter_cmd) < $image_ppm > $target";
2429 $rc = nontrapping_system ($cmd);
2431 LOG ($verbose_pbm, "filter failed: \"$post_filter_cmd\"\n");
2436 if (!$no_output_p) {
2437 my $tsize = (stat($target))[7];
2439 $cmd = "$ppm_to_root_window_cmd $target";
2441 # xv seems to hate being killed. it tends to forget to clean
2442 # up after itself, and leaves windows around and colors allocated.
2443 # I had this same problem with vidwhacker, and I'm not entirely
2444 # sure what I did to fix it. But, let's try this: launch xv
2445 # in the background, so that killing this process doesn't kill it.
2446 # it will die of its own accord soon enough. So this means we
2447 # start pumping bits to the root window in parallel with starting
2448 # the next network retrieval, which is probably a better thing
2453 $rc = nontrapping_system ($cmd);
2456 LOG (($verbose_pbm || $verbose_load), "display failed: \"$cmd\"");
2461 LOG ($verbose_pbm, "$target size is $tsize");
2465 $source .= "-" . stats_of($source);
2466 print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n"
2467 if ($verbose_imgmap);
2477 $SIG{HUP} = \&signal_cleanup;
2478 $SIG{INT} = \&signal_cleanup;
2479 $SIG{QUIT} = \&signal_cleanup;
2480 $SIG{ABRT} = \&signal_cleanup;
2481 $SIG{KILL} = \&signal_cleanup;
2482 $SIG{TERM} = \&signal_cleanup;
2484 # Need this so that if giftopnm dies, we don't die.
2485 $SIG{PIPE} = 'IGNORE';
2488 END { signal_cleanup(); }
2497 my $driftnet_cmd = 0;
2499 $current_state = "init";
2500 $load_method = "none";
2504 # historical suckage: the environment variable name is lower case.
2505 $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
2507 while ($_ = $ARGV[0]) {
2509 if ($_ eq "-display" ||
2515 $ENV{DISPLAY} = shift @ARGV;
2516 } elsif ($_ eq "-root") {
2518 } elsif ($_ eq "-no-output") {
2520 } elsif ($_ eq "-urls-only") {
2523 } elsif ($_ eq "-verbose") {
2525 } elsif (m/^-v+$/) {
2526 $verbose += length($_)-1;
2527 } elsif ($_ eq "-delay") {
2528 $delay = shift @ARGV;
2529 } elsif ($_ eq "-timeout") {
2530 $http_timeout = shift @ARGV;
2531 } elsif ($_ eq "-filter") {
2532 $filter_cmd = shift @ARGV;
2533 } elsif ($_ eq "-filter2") {
2534 $post_filter_cmd = shift @ARGV;
2535 } elsif ($_ eq "-background" || $_ eq "-bg") {
2536 $background = shift @ARGV;
2537 } elsif ($_ eq "-size") {
2539 if (m@^(\d+)x(\d+)$@) {
2543 error "argument to \"-size\" must be of the form \"640x400\"";
2545 } elsif ($_ eq "-proxy" || $_ eq "-http-proxy") {
2546 $http_proxy = shift @ARGV;
2547 } elsif ($_ eq "-dictionary" || $_ eq "-dict") {
2548 $dict = shift @ARGV;
2549 } elsif ($_ eq "-driftnet" || $_ eq "--driftnet") {
2550 @search_methods = ( 100, "driftnet", \&pick_from_driftnet );
2551 if (! ($ARGV[0] =~ m/^-/)) {
2552 $driftnet_cmd = shift @ARGV;
2554 $driftnet_cmd = $default_driftnet_cmd;
2556 } elsif ($_ eq "-debug" || $_ eq "--debug") {
2557 my $which = shift @ARGV;
2558 my @rest = @search_methods;
2561 my $pct = shift @rest;
2562 my $name = shift @rest;
2563 my $tfn = shift @rest;
2565 if ($name eq $which) {
2566 @search_methods = (100, $name, $tfn);
2571 error "no such search method as \"$which\"" unless ($ok);
2572 LOG (1, "DEBUG: using only \"$which\"");
2575 print STDERR "$copyright\nusage: $progname " .
2576 "[-root] [-display dpy] [-verbose] [-debug which]\n" .
2577 "\t\t [-timeout secs] [-delay secs] [-filter cmd] [-filter2 cmd]\n" .
2578 "\t\t [-no-output] [-urls-only] [-background color] [-size WxH]\n" .
2579 "\t\t [-dictionary dictionary-file] [-http-proxy host[:port]]\n" .
2580 "\t\t [-driftnet [driftnet-program-and-args]]\n" .
2586 if ($http_proxy && $http_proxy eq "") {
2587 $http_proxy = undef;
2589 if ($http_proxy && $http_proxy =~ m@^http://([^/]*)/?$@ ) {
2590 # historical suckage: allow "http://host:port" as well as "host:port".
2594 if (!$root_p && !$no_output_p) {
2595 print STDERR $copyright;
2596 error "the -root argument is mandatory (for now.)";
2599 if (!$no_output_p && !$ENV{DISPLAY}) {
2600 error "\$DISPLAY is not set.";
2604 if ($verbose == 1) {
2605 $verbose_imgmap = 1;
2606 $verbose_warnings = 1;
2608 } elsif ($verbose == 2) {
2609 $verbose_imgmap = 1;
2610 $verbose_warnings = 1;
2613 } elsif ($verbose == 3) {
2614 $verbose_imgmap = 1;
2615 $verbose_warnings = 1;
2617 $verbose_filter = 1;
2619 } elsif ($verbose == 4) {
2620 $verbose_imgmap = 1;
2621 $verbose_warnings = 1;
2623 $verbose_filter = 1;
2626 } elsif ($verbose == 5) {
2627 $verbose_imgmap = 1;
2628 $verbose_warnings = 1;
2630 $verbose_filter = 1;
2634 } elsif ($verbose == 6) {
2635 $verbose_imgmap = 1;
2636 $verbose_warnings = 1;
2638 $verbose_filter = 1;
2643 } elsif ($verbose >= 7) {
2644 $verbose_imgmap = 1;
2645 $verbose_warnings = 1;
2647 $verbose_filter = 1;
2655 error ("$dict does not exist") unless (-f $dict);
2663 spawn_driftnet ($driftnet_cmd) if ($driftnet_cmd);