3 # webcollage, Copyright (c) 1999-2004 by Jamie Zawinski <jwz@jwz.org>
4 # This program decorates the screen with random images from the web.
5 # One satisfied customer described it as "a nonstop pop culture brainbath."
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':
19 # webcollage -root -filter 'vidwhacker -stdin -stdout'
22 # You can see this in action at http://www.jwz.org/webcollage/ --
23 # it auto-reloads about once a minute. To make a page similar to
24 # that on your own system, do this:
26 # webcollage -size '800x600' -imagemap $HOME/www/webcollage/index
29 # If you have the "driftnet" program installed, webcollage can display a
30 # collage of images sniffed off your local ethernet, instead of pulled out
31 # of search engines: in that way, your screensaver can display the images
32 # that your co-workers are downloading!
34 # Driftnet is available here: http://www.ex-parrot.com/~chris/driftnet/
37 # webcollage -root -driftnet
39 # Driftnet is the Unix implementation of the MacOS "EtherPEG" program.
45 # We can't "use diagnostics" here, because that library malfunctions if
46 # you signal and catch alarms: it says "Uncaught exception from user code"
47 # and exits, even though I damned well AM catching it!
54 use Fcntl ':flock'; # import LOCK_* constants
55 use POSIX qw(strftime);
57 use bytes; # Larry can take Unicode and shove it up his ass sideways.
58 # Perl 5.8.0 causes us to start getting incomprehensible
59 # errors about UTF-8 all over the place without this.
62 my $progname = $0; $progname =~ s@.*/@@g;
63 my $version = q{ $Revision: 1.114 $ }; $version =~ s/^[^0-9]+([0-9.]+).*$/$1/;
64 my $copyright = "WebCollage $version, Copyright (c) 1999-2004" .
65 " Jamie Zawinski <jwz\@jwz.org>\n" .
66 " http://www.jwz.org/webcollage/\n";
70 my @search_methods = ( 72, "altavista", \&pick_from_alta_vista_random_link,
71 10, "livejournal", \&pick_from_livejournal_images,
72 10, "yahoorand", \&pick_from_yahoo_random_link,
73 8, "yahoonews", \&pick_from_yahoo_news_text,
75 # Alta Vista has a new "random link" URL now.
76 # They added it specifically to better support webcollage!
77 # That was super cool of them. This is how we used to do
80 # 0, "avimages", \&pick_from_alta_vista_images,
81 # 0, "avtext", \&pick_from_alta_vista_text,
83 # Google asked (nicely) for me to stop searching them.
84 # I asked them to add a "random link" url. They said
85 # "that would be easy, we'll think about it" and then
86 # never wrote back. Booo Google! Booooo!
88 # 0, "googlenums", \&pick_from_google_image_numbers,
89 # 0, "googleimgs", \&pick_from_google_images,
91 # I suspect Hotbot is actually the same search engine
94 # 0, "hotbot", \&pick_from_hotbot_text,
96 # Eh, Lycos sucks anyway.
97 # 0, "lycos", \&pick_from_lycos_text,
100 # programs we can use to write to the root window (tried in ascending order.)
102 my @root_displayers = (
103 "xscreensaver-getimage -root -file",
104 "chbg -once -xscreensaver -max_size 100",
105 "xv -root -quit -viewonly +noresetroot -quick24 -rmode 5" .
106 " -rfg black -rbg black",
107 "xli -quiet -onroot -center -border black",
108 "xloadimage -quiet -onroot -center -border black",
110 # this lame program wasn't built with vroot.h:
111 # "xsri -scale -keep-aspect -center-horizontal -center-vertical",
115 # Some sites need cookies to work properly. These are they.
118 "www.altavista.com" => "AV_ALL=1", # request uncensored searches
119 "web.altavista.com" => "AV_ALL=1",
121 # log in as "cipherpunk"
122 "www.nytimes.com" => 'NYT-S=18cHMIlJOn2Y1bu5xvEG3Ufuk6E1oJ.' .
123 'FMxWaQV0igaB5Yi/Q/guDnLeoL.pe7i1oakSb' .
124 '/VqfdUdb2Uo27Vzt1jmPn3cpYRlTw9',
128 # If this is set, it's a helper program to use for pasting images together:
129 # this is a lot faster and more efficient than using PPM pipelines, which is
130 # what we do if this program doesn't exist. (We check for "webcollage-helper"
131 # on $PATH at startup, and set this variable appropriately.)
133 my $webcollage_helper = undef;
136 # If we have the webcollage-helper program, then it will paste the images
137 # together with transparency! 0.0 is invisible, 1.0 is totally opaque.
142 # Some sites have managed to poison the search engines. These are they.
143 # (We auto-detect sites that have poisoned the search engines via excessive
144 # keywords or dictionary words, but these are ones that slip through
147 # This can contain full host names, or 2 or 3 component domains.
150 "die.net" => 1, # 'l33t h4ck3r d00dz.
151 "genforum.genealogy.com" => 1, # Cluttering avtext with human names.
152 "rootsweb.com" => 1, # Cluttering avtext with human names.
153 "akamai.net" => 1, # Lots of sites have their images on Akamai.
154 "akamaitech.net" => 1, # But those are pretty much all banners.
155 # Since Akamai is super-expensive, let's
156 # go out on a limb and assume that all of
157 # their customers are rich-and-boring.
158 "bartleby.com" => 1, # Dictionary, cluttering avtext.
159 "encyclopedia.com" => 1, # Dictionary, cluttering avtext.
160 "onlinedictionary.datasegment.com" => 1, # Dictionary, cluttering avtext.
161 "hotlinkpics.com" => 1, # Porn site that has poisoned avimages
162 # (I don't see how they did it, though!)
163 "alwayshotels.com" => 1, # Poisoned Lycos pretty heavily.
164 "nextag.com" => 1, # Poisoned Alta Vista real good.
168 # When verbosity is turned on, we warn about sites that we seem to be hitting
169 # a lot: usually this means some new poisoner has made it into the search
170 # engines. But sometimes, the warning is just because that site has a lot
171 # of stuff on it. So these are the sites that are immune to the "frequent
172 # site" diagnostic message.
174 my %warningless_sites = (
175 "home.earthlink.net" => 1, # Lots of home pages here.
176 "www.geocities.com" => 1,
177 "www.angelfire.com" => 1,
178 "members.aol.com" => 1,
180 "yimg.com" => 1, # This is where dailynews.yahoo.com stores
181 "eimg.com" => 1, # its images, so pick_from_yahoo_news_text()
182 # hits this every time.
184 "driftnet" => 1, # builtin...
188 ##############################################################################
190 # Various global flags set by command line parameters, or computed
192 ##############################################################################
195 my $current_state = "???"; # for diagnostics
198 my $image_succeeded = -1;
199 my $suppress_audit = 0;
201 my $verbose_imgmap = 0; # print out rectangles and URLs only (stdout)
202 my $verbose_warnings = 0; # print out warnings when things go wrong
203 my $verbose_load = 0; # diagnostics about loading of URLs
204 my $verbose_filter = 0; # diagnostics about page selection/rejection
205 my $verbose_net = 0; # diagnostics about network I/O
206 my $verbose_pbm = 0; # diagnostics about PBM pipelines
207 my $verbose_http = 0; # diagnostics about all HTTP activity
208 my $verbose_exec = 0; # diagnostics about executing programs
210 my $report_performance_interval = 60 * 15; # print some stats every 15 minutes
212 my $http_proxy = undef;
213 my $http_timeout = 30;
214 my $cvt_timeout = 10;
220 my $min_gif_area = (120 * 120);
225 my $imagemap_base = undef;
227 my @pids_to_kill = (); # forked pids we should kill when we exit, if any.
229 my $driftnet_magic = 'driftnet';
230 my $driftnet_dir = undef;
231 my $default_driftnet_cmd = "driftnet -a -m 100";
236 my @tripwire_words = ("aberrate", "abode", "amorphous", "antioch",
237 "arrhenius", "arteriole", "blanket", "brainchild",
238 "burdensome", "carnival", "cherub", "chord", "clever",
239 "dedicate", "dilogarithm", "dolan", "dryden",
243 ##############################################################################
247 ##############################################################################
249 # returns three values: the HTTP response line; the document headers;
250 # and the document body.
253 my ( $url, $referer, $timeout ) = @_;
255 if (!defined($timeout)) { $timeout = $http_timeout; }
256 if ($timeout > $http_timeout) { $timeout = $http_timeout; }
259 LOG (($verbose_net || $verbose_load), "timed out for $url");
263 LOG ($verbose_net, "get_document_1 $url " . ($referer ? $referer : ""));
265 if (! ($url =~ m@^http://@i)) {
266 LOG ($verbose_net, "not an HTTP URL: $url");
270 my ($url_proto, $dummy, $serverstring, $path) = split(/\//, $url, 4);
271 $path = "" unless $path;
273 if (!$url_proto || !$serverstring) {
274 LOG (($verbose_net || $verbose_load), "unparsable URL: $url");
278 my ($them,$port) = split(/:/, $serverstring);
279 $port = 80 unless $port;
284 $serverstring = $http_proxy if $http_proxy;
285 $serverstring =~ s@^[a-z]+://@@;
286 ($them2,$port2) = split(/:/, $serverstring);
287 $port2 = 80 unless $port2;
290 my ($remote, $iaddr, $paddr, $proto, $line);
292 if ($port2 =~ /\D/) { $port2 = getservbyname($port2, 'tcp') }
294 LOG (($verbose_net || $verbose_load), "unrecognised port in $url");
297 $iaddr = inet_aton($remote);
299 LOG (($verbose_net || $verbose_load), "host not found: $remote");
302 $paddr = sockaddr_in($port2, $iaddr);
310 local $SIG{ALRM} = sub {
311 LOG (($verbose_net || $verbose_load), "timed out ($timeout) for $url");
316 $proto = getprotobyname('tcp');
317 if (!socket(S, PF_INET, SOCK_STREAM, $proto)) {
318 LOG (($verbose_net || $verbose_load), "socket: $!");
321 if (!connect(S, $paddr)) {
322 LOG (($verbose_net || $verbose_load), "connect($serverstring): $!");
326 select(S); $| = 1; select(STDOUT);
328 my $cookie = $cookies{$them};
330 my $user_agent = "$progname/$version";
332 if ($url =~ m@^http://www\.altavista\.com/@ ||
333 $url =~ m@^http://random\.yahoo\.com/@) {
334 # block this, you turkeys.
335 $user_agent = "Mozilla/4.76 [en] (X11; U; Linux 2.2.16-22 i686; Nav)";
338 my $hdrs = "GET " . ($http_proxy ? $url : "/$path") . " HTTP/1.0\r\n" .
340 "User-Agent: $user_agent\r\n";
342 $hdrs .= "Referer: $referer\r\n";
345 my @cc = split(/\r?\n/, $cookie);
346 $hdrs .= "Cookie: " . join('; ', @cc) . "\r\n";
350 foreach (split('\r?\n', $hdrs)) {
351 LOG ($verbose_http, " ==> $_");
354 my $http = <S> || "";
356 # Kludge: the Yahoo Random Link is now returning as its first
357 # line "Status: 301" instead of "HTTP/1.0 301 Found". Fix it...
359 $http =~ s@^Status:\s+(\d+)\b@HTTP/1.0 $1@i;
363 LOG ($verbose_http, " <== $_");
369 LOG ($verbose_http, " <== $_");
371 if (m@^Set-cookie:\s*([^;\r\n]+)@i) {
372 set_cookie($them, $1)
383 " <== [ body ]: $lines lines, " . length($body) . " bytes");
388 LOG (($verbose_net || $verbose_load), "null response: $url");
392 return ( $http, $head, $body );
394 die if ($@ && $@ ne "alarm\n"); # propagate errors
409 # returns two values: the document headers; and the document body.
410 # if the given URL did a redirect, returns the redirected-to document.
413 my ( $url, $referer, $timeout ) = @_;
416 if (defined($referer) && $referer eq $driftnet_magic) {
417 return get_driftnet_file ($url);
422 my $max_loop_count = 4;
425 if (defined($timeout) && $timeout <= 0) {
426 LOG (($verbose_net || $verbose_load), "timed out for $url");
431 my ( $http, $head, $body ) = get_document_1 ($url, $referer, $timeout);
433 if (defined ($timeout)) {
435 my $elapsed = $now - $start;
436 $timeout -= $elapsed;
440 return () unless $http; # error message already printed
442 $http =~ s/[\r\n]+$//s;
444 if ( $http =~ m@^HTTP/[0-9.]+ 30[123]@ ) {
447 my ( $location ) = m@^location:[ \t]*(.*)$@im;
449 $location =~ s/[\r\n]$//;
451 LOG ($verbose_net, "redirect from $url to $location");
456 $referer =~ m@^(http://[^/]+)@i;
458 } elsif (! ($url =~ m@^[a-z]+:@i)) {
460 s@[^/]+$@@g if m@^http://[^/]+/@i;
461 $_ .= "/" if m@^http://[^/]+$@i;
466 LOG ($verbose_net, "no Location with \"$http\"");
467 return ( $url, $body );
470 if ($loop_count++ > $max_loop_count) {
472 "too many redirects ($max_loop_count) from $orig_url");
477 } elsif ( $http =~ m@^HTTP/[0-9.]+ ([4-9][0-9][0-9].*)$@ ) {
479 LOG (($verbose_net || $verbose_load), "failed: $1 ($url)");
481 # http errors -- return nothing.
487 LOG (($verbose_net || $verbose_load), "document contains no data: $url");
493 return ( $url, $body );
499 # If we already have a cookie defined for this site, and the site is trying
500 # to overwrite that very same cookie, let it do so. This is because nytimes
501 # expires its cookies - it lets you upgrade to a new cookie without logging
502 # in again, but you have to present the old cookie to get the new cookie.
503 # So, by doing this, the built-in cypherpunks cookie will never go "stale".
506 my ($host, $cookie) = @_;
507 my $oc = $cookies{$host};
510 my ($oc_name, $oc_value) = m@^([^= \t\r\n]+)=(.*)$@;
512 my ($nc_name, $nc_value) = m@^([^= \t\r\n]+)=(.*)$@;
514 if ($oc_name eq $nc_name &&
515 $oc_value ne $nc_value) {
516 $cookies{$host} = $cookie;
517 LOG ($verbose_net, "overwrote ${host}'s $oc_name cookie");
522 ############################################################################
524 # Extracting image URLs from HTML
526 ############################################################################
528 # given a URL and the body text at that URL, selects and returns a random
529 # image from it. returns () if no suitable images found.
531 sub pick_image_from_body {
532 my ( $url, $body ) = @_;
537 # if there's at least one slash after the host, take off the last
539 if ( m@^http://[^/]+/@io ) {
540 $base =~ s@[^/]+$@@go;
543 # if there are no slashes after the host at all, put one on the end.
544 if ( m@^http://[^/]+$@io ) {
550 # strip out newlines, compress whitespace
557 # There are certain web sites that list huge numbers of dictionary
558 # words in their bodies or in their <META NAME=KEYWORDS> tags (surprise!
559 # Porn sites tend not to be reputable!)
561 # I do not want webcollage to filter on content: I want it to select
562 # randomly from the set of images on the web. All the logic here for
563 # rejecting some images is really a set of heuristics for rejecting
564 # images that are not really images: for rejecting *text* that is in
565 # GIF/JPEG/PNG form. I don't want text, I want pictures, and I want
566 # the content of the pictures to be randomly selected from among all
567 # the available content.
569 # So, filtering out "dirty" pictures by looking for "dirty" keywords
570 # would be wrong: dirty pictures exist, like it or not, so webcollage
571 # should be able to select them.
573 # However, picking a random URL is a hard thing to do. The mechanism I'm
574 # using is to search for a selection of random words. This is not
575 # perfect, but works ok most of the time. The way it breaks down is when
576 # some URLs get precedence because their pages list *every word* as
577 # related -- those URLs come up more often than others.
579 # So, after we've retrieved a URL, if it has too many keywords, reject
580 # it. We reject it not on the basis of what those keywords are, but on
581 # the basis that by having so many, the page has gotten an unfair
582 # advantage against our randomizer.
585 foreach my $trip (@tripwire_words) {
586 $trip_count++ if m/$trip/i;
589 if ($trip_count >= $#tripwire_words - 2) {
590 LOG (($verbose_filter || $verbose_load),
591 "there is probably a dictionary in \"$url\": rejecting.");
592 $rejected_urls{$url} = -1;
602 foreach (split(/ *</)) {
605 # Likewise, reject any web pages that have a KEYWORDS meta tag
608 if (m/name ?= ?\"?keywords\"?/i &&
609 m/content ?= ?\"([^\"]+)\"/) {
612 LOG (($verbose_filter || $verbose_load),
613 "excessive keywords ($L bytes) in $url: rejecting.");
614 $rejected_urls{$url} = $L;
619 LOG ($verbose_filter, " keywords ($L bytes) in $url (ok)");
623 } elsif ( m/^(img|a) .*(src|href) ?= ?\"? ?(.*?)[ >\"]/io ) {
625 my $was_inline = (! ( "$1" eq "a" || "$1" eq "A" ));
627 my ( $width ) = m/width ?=[ \"]*(\d+)/oi;
628 my ( $height ) = m/height ?=[ \"]*(\d+)/oi;
633 ( $site = $base ) =~ s@^(http://[^/]*).*@$1@gio;
635 } elsif ( ! m@^[^/:?]+:@ ) {
638 1 while (s@/[^/]+/\.\./@/@g);
642 if ( ! m@^http://@io ) {
647 if ( ! m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@io ) {
651 # skip really short or really narrow images
652 if ( $width && $width < $min_width) {
653 if (!$height) { $height = "?"; }
654 LOG ($verbose_filter, " skip narrow image $_ (${width}x$height)");
658 if ( $height && $height < $min_height) {
659 if (!$width) { $width = "?"; }
660 LOG ($verbose_filter, " skip short image $_ (${width}x$height)");
664 # skip images with ratios that make them look like banners.
665 if ($min_ratio && $width && $height &&
666 ($width * $min_ratio ) > $height) {
667 if (!$height) { $height = "?"; }
668 LOG ($verbose_filter, " skip bad ratio $_ (${width}x$height)");
672 # skip GIFs with a small number of pixels -- those usually suck.
673 if ($width && $height &&
675 ($width * $height) < $min_gif_area) {
676 LOG ($verbose_filter, " skip small GIF $_ (${width}x$height)");
683 if ($unique_urls{$url}) {
684 LOG ($verbose_filter, " skip duplicate image $_");
688 LOG ($verbose_filter,
690 ($width && $height ? " (${width}x${height})" : "") .
691 ($was_inline ? " (inline)" : ""));
693 $urls[++$#urls] = $url;
694 $unique_urls{$url}++;
696 # JPEGs are preferable to GIFs and PNGs.
698 if ( ! m@[.](gif|png)$@io ) {
699 $urls[++$#urls] = $url;
702 # pointers to images are preferable to inlined images.
703 if ( ! $was_inline ) {
704 $urls[++$#urls] = $url;
705 $urls[++$#urls] = $url;
710 my $fsp = ($body =~ m@<frameset@i);
715 @urls = depoison (@urls);
718 LOG ($verbose_load, "no images on $base" . ($fsp ? " (frameset)" : ""));
722 # pick a random element of the table
723 my $i = int(rand($#urls+1));
726 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#urls+1) . ": $url");
733 ############################################################################
735 # Subroutines for getting pages and images out of search engines
737 ############################################################################
740 sub pick_dictionary {
741 my @dicts = ("/usr/dict/words",
742 "/usr/share/dict/words",
743 "/usr/share/lib/dict/words");
744 foreach my $f (@dicts) {
750 error ("$dicts[0] does not exist") unless defined($wordlist);
753 # returns a random word from the dictionary
757 if (open (IN, "<$wordlist")) {
758 my $size = (stat(IN))[7];
759 my $pos = rand $size;
760 if (seek (IN, $pos, 0)) {
761 $word = <IN>; # toss partial line
762 $word = <IN>; # keep next line
771 return 0 if (!$word);
773 $word =~ s/^[ \t\n\r]+//;
774 $word =~ s/[ \t\n\r]+$//;
779 $word =~ s/ally$/al/;
780 $word =~ s/izes$/ize/;
781 $word =~ tr/A-Z/a-z/;
783 if ( $word =~ s/[ \t\n\r]/\+/g ) { # convert intra-word spaces to "+".
784 $word = "\%22$word\%22"; # And put quotes (%22) around it.
792 my $sep = ($or_p ? "%20OR%20" : "%20");
793 return (random_word . $sep .
803 $s =~ s|([^-a-zA-Z0-9.\@/_\r\n])|sprintf("%%%02X", ord($1))|ge;
810 $s =~ s/%([a-z0-9]{2})/chr(hex($1))/ige;
819 $s =~ s/\"/"/gi;
825 $s =~ s/</</gi; # far from exhaustive...
827 $s =~ s/"/\"/gi;
833 # Loads the given URL (a search on some search engine) and returns:
834 # - the total number of hits the search engine claimed it had;
835 # - a list of URLs from the page that the search engine returned;
836 # Note that this list contains all kinds of internal search engine
837 # junk URLs too -- caller must prune them.
839 sub pick_from_search_engine {
840 my ( $timeout, $search_url, $words ) = @_;
845 print STDERR "\n\n" if ($verbose_load);
847 LOG ($verbose_load, "words: $_");
848 LOG ($verbose_load, "URL: $search_url");
850 $last_search = $search_url; # for warnings
853 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
854 if (defined ($timeout)) {
855 $timeout -= (time - $start);
858 LOG (($verbose_net || $verbose_load),
859 "timed out (late) for $search_url");
865 return () if (! $body);
870 my $search_count = "?";
871 if ($body =~ m@found (approximately |about )?(<B>)?(\d+)(</B>)? image@) {
873 } elsif ($body =~ m@<NOBR>((\d{1,3})(,\d{3})*) @i) {
875 } elsif ($body =~ m@found ((\d{1,3})(,\d{3})*|\d+) Web p@) {
877 } elsif ($body =~ m@found about ((\d{1,3})(,\d{3})*|\d+) results@) {
879 } elsif ($body =~ m@\b\d+ - \d+ of (\d+)\b@i) { # avimages
881 } elsif ($body =~ m@About ((\d{1,3})(,\d{3})*) images@i) { # avimages
883 } elsif ($body =~ m@We found ((\d{1,3})(,\d{3})*|\d+) results@i) { # *vista
885 } elsif ($body =~ m@ of about <B>((\d{1,3})(,\d{3})*)<@i) { # googleimages
887 } elsif ($body =~ m@<B>((\d{1,3})(,\d{3})*)</B> Web sites were found@i) {
888 $search_count = $1; # lycos
889 } elsif ($body =~ m@WEB.*?RESULTS.*?\b((\d{1,3})(,\d{3})*)\b.*?Matches@i) {
890 $search_count = $1; # hotbot
891 } elsif ($body =~ m@no photos were found containing@i) { # avimages
893 } elsif ($body =~ m@found no document matching@i) { # avtext
896 1 while ($search_count =~ s/^(\d+)(\d{3})/$1,$2/);
898 # if ($search_count eq "?" || $search_count eq "0") {
900 # my $file = "/tmp/wc.html";
901 # open(OUT, ">$file") || error ("writing $file: $!");
904 # print STDERR blurb() . "###### wrote $file\n";
908 my $length = length($body);
917 foreach (split(/\n/)) {
919 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
922 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
923 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
925 if ( $rejected_urls{$u} ) {
926 LOG ($verbose_filter, " pre-rejecting candidate: $u");
930 LOG ($verbose_http, " HREF: $u");
932 $subpages[++$#subpages] = $u;
935 if ( $#subpages < 0 ) {
936 LOG ($verbose_filter,
937 "found nothing on $base ($length bytes, $href_count links).");
941 LOG ($verbose_filter, "" . $#subpages+1 . " links on $search_url");
943 return ($search_count, @subpages);
951 my ($h) = m@^http://([^/: \t\r\n]+)@i;
953 next unless defined($h);
955 if ($poisoners{$h}) {
956 LOG (($verbose_filter), " rejecting poisoner: $_");
959 if ($h =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
961 LOG (($verbose_filter), " rejecting poisoner: $_");
964 if ($h =~ m@([^.]+\.[^.]+)$@ &&
966 LOG (($verbose_filter), " rejecting poisoner: $_");
976 # given a list of URLs, picks one at random; loads it; and returns a
977 # random image from it.
978 # returns the url of the page loaded; the url of the image chosen;
979 # and a debugging description string.
981 sub pick_image_from_pages {
982 my ($base, $total_hit_count, $unfiltered_link_count, $timeout, @pages) = @_;
984 $total_hit_count = "?" unless defined($total_hit_count);
986 @pages = depoison (@pages);
988 "" . ($#pages+1) . " candidates of $unfiltered_link_count links" .
989 " ($total_hit_count total)");
991 return () if ($#pages < 0);
993 my $i = int(rand($#pages+1));
994 my $page = $pages[$i];
996 LOG ($verbose_load, "picked page $page");
1000 my ( $base2, $body2 ) = get_document ($page, $base, $timeout);
1002 if (!$base2 || !$body2) {
1007 my $img = pick_image_from_body ($base2, $body2);
1011 return ($base2, $img);
1018 ############################################################################
1020 # Pick images from random pages returned by the Yahoo Random Link
1022 ############################################################################
1025 my $yahoo_random_link = "http://random.yahoo.com/fast/ryl";
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_yahoo_random_link {
1033 my ( $timeout ) = @_;
1035 print STDERR "\n\n" if ($verbose_load);
1036 LOG ($verbose_load, "URL: $yahoo_random_link");
1038 $last_search = $yahoo_random_link; # for warnings
1040 $suppress_audit = 1;
1042 my ( $base, $body ) = get_document ($yahoo_random_link, undef, $timeout);
1043 if (!$base || !$body) {
1048 LOG ($verbose_load, "redirected to: $base");
1050 my $img = pick_image_from_body ($base, $body);
1054 return ($base, $img);
1061 ############################################################################
1063 # Pick images from random pages returned by the Alta Vista Random Link
1065 ############################################################################
1068 my $alta_vista_random_link = "http://www.altavista.com/image/randomlink";
1071 # Picks a random page; picks a random image on that page;
1072 # returns two URLs: the page containing the image, and the image.
1073 # Returns () if nothing found this time.
1075 sub pick_from_alta_vista_random_link {
1076 my ( $timeout ) = @_;
1078 print STDERR "\n\n" if ($verbose_load);
1079 LOG ($verbose_load, "URL: $alta_vista_random_link");
1081 $last_search = $alta_vista_random_link; # for warnings
1083 $suppress_audit = 1;
1085 my ( $base, $body ) = get_document ($alta_vista_random_link,
1087 if (!$base || !$body) {
1092 LOG ($verbose_load, "redirected to: $base");
1094 my $img = pick_image_from_body ($base, $body);
1098 return ($base, $img);
1105 ############################################################################
1107 # Pick images by feeding random words into Alta Vista Image Search
1109 ############################################################################
1112 my $alta_vista_images_url = "http://www.altavista.com/image/results" .
1113 "?ipht=1" . # photos
1114 "&igrph=1" . # graphics
1117 "&micat=1" . # no partner sites
1118 "&sc=on" . # "site collapse"
1122 sub pick_from_alta_vista_images {
1123 my ( $timeout ) = @_;
1125 my $words = random_words(0);
1126 my $page = (int(rand(9)) + 1);
1127 my $search_url = $alta_vista_images_url . $words;
1130 $search_url .= "&pgno=" . $page; # page number
1131 $search_url .= "&stq=" . (($page-1) * 12); # first hit result on page
1134 my ($search_hit_count, @subpages) =
1135 pick_from_search_engine ($timeout, $search_url, $words);
1137 my @candidates = ();
1138 foreach my $u (@subpages) {
1140 # avtext is encoding their URLs now.
1141 next unless ($u =~ m@^/r.*\&r=([^&]+).*@);
1142 $u = url_unquote($1);
1144 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1145 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
1146 next if ($u =~ m@[/.]doubleclick\.net\b@i); # you cretins
1147 next if ($u =~ m@[/.]clicktomarket\.com\b@i); # more cretins
1149 next if ($u =~ m@[/.]viewimages\.com\b@i); # stacked deck
1150 next if ($u =~ m@[/.]gettyimages\.com\b@i);
1152 LOG ($verbose_filter, " candidate: $u");
1153 push @candidates, $u;
1156 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1157 $timeout, @candidates);
1162 ############################################################################
1164 # Pick images by feeding random words into Google Image Search.
1165 # By Charles Gales <gales@us.ibm.com>
1167 ############################################################################
1170 my $google_images_url = "http://images.google.com/images" .
1171 "?site=images" . # photos
1172 "&btnG=Search" . # graphics
1173 "&safe=off" . # no screening
1178 sub pick_from_google_images {
1179 my ( $timeout ) = @_;
1181 my $words = random_word; # only one word for Google
1182 my $page = (int(rand(9)) + 1);
1183 my $num = 20; # 20 images per page
1184 my $search_url = $google_images_url . $words;
1187 $search_url .= "&start=" . $page*$num; # page number
1188 $search_url .= "&num=" . $num; #images per page
1191 my ($search_hit_count, @subpages) =
1192 pick_from_search_engine ($timeout, $search_url, $words);
1194 my @candidates = ();
1195 foreach my $u (@subpages) {
1196 next unless ($u =~ m@imgres\?imgurl@i); # All pics start with this
1197 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins
1199 if ($u =~ m@^/imgres\?imgurl=(.*?)\&imgrefurl=(.*?)\&@) {
1201 LOG ($verbose_filter, " candidate: $urlf");
1202 push @candidates, $urlf;
1206 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1207 $timeout, @candidates);
1212 ############################################################################
1214 # Pick images by feeding random *numbers* into Google Image Search.
1215 # By jwz, suggested by Ian O'Donnell.
1217 ############################################################################
1221 sub pick_from_google_image_numbers {
1222 my ( $timeout ) = @_;
1225 my $number = int(rand($max));
1227 $number = sprintf("%04d", $number)
1230 my $words = "$number";
1231 my $page = (int(rand(40)) + 1);
1232 my $num = 20; # 20 images per page
1233 my $search_url = $google_images_url . $words;
1236 $search_url .= "&start=" . $page*$num; # page number
1237 $search_url .= "&num=" . $num; #images per page
1240 my ($search_hit_count, @subpages) =
1241 pick_from_search_engine ($timeout, $search_url, $words);
1243 my @candidates = ();
1245 foreach my $u (@subpages) {
1246 next unless ($u =~ m@imgres\?imgurl@i); # All pics start with this
1247 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins
1249 if ($u =~ m@^/imgres\?imgurl=(.*?)\&imgrefurl=(.*?)\&@) {
1251 my $img = "http://$1";
1253 LOG ($verbose_filter, " candidate: $ref");
1254 push @candidates, $img;
1255 $referers{$img} = $ref;
1259 @candidates = depoison (@candidates);
1260 return () if ($#candidates < 0);
1261 my $i = int(rand($#candidates+1));
1262 my $img = $candidates[$i];
1263 my $ref = $referers{$img};
1265 LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1266 return ($ref, $img);
1271 ############################################################################
1273 # Pick images by feeding random words into Alta Vista Text Search
1275 ############################################################################
1278 my $alta_vista_url = "http://www.altavista.com/web/results" .
1282 "&sc=on" . # "site collapse"
1287 sub pick_from_alta_vista_text {
1288 my ( $timeout ) = @_;
1290 my $words = random_words(0);
1291 my $page = (int(rand(9)) + 1);
1292 my $search_url = $alta_vista_url . $words;
1295 $search_url .= "&pgno=" . $page;
1296 $search_url .= "&stq=" . (($page-1) * 10);
1299 my ($search_hit_count, @subpages) =
1300 pick_from_search_engine ($timeout, $search_url, $words);
1302 my @candidates = ();
1303 foreach my $u (@subpages) {
1305 # Those altavista fuckers are playing really nasty redirection games
1306 # these days: the filter your clicks through their site, but use
1307 # onMouseOver to make it look like they're not! Well, it makes it
1308 # easier for us to identify search results...
1310 next unless ($u =~ m@^/r.*\&r=([^&]+).*@);
1311 $u = url_unquote($1);
1313 LOG ($verbose_filter, " candidate: $u");
1314 push @candidates, $u;
1317 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1318 $timeout, @candidates);
1323 ############################################################################
1325 # Pick images by feeding random words into Hotbot
1327 ############################################################################
1329 my $hotbot_search_url =("http://hotbot.lycos.com/default.asp" .
1331 "&descriptiontype=0" .
1338 "&cobrand=undefined" .
1341 sub pick_from_hotbot_text {
1342 my ( $timeout ) = @_;
1344 $last_search = $hotbot_search_url; # for warnings
1346 # lycos seems to always give us back dictionaries and word lists if
1347 # we search for more than one word...
1349 my $words = random_word();
1351 my $start = int(rand(8)) * 10 + 1;
1352 my $search_url = $hotbot_search_url . $words . "&first=$start&page=more";
1354 my ($search_hit_count, @subpages) =
1355 pick_from_search_engine ($timeout, $search_url, $words);
1357 my @candidates = ();
1358 foreach my $u (@subpages) {
1360 # Hotbot plays redirection games too
1361 next unless ($u =~ m@/director.asp\?.*\btarget=([^&]+)@);
1362 $u = url_decode($1);
1364 LOG ($verbose_filter, " candidate: $u");
1365 push @candidates, $u;
1368 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1369 $timeout, @candidates);
1374 ############################################################################
1376 # Pick images by feeding random words into Lycos
1378 ############################################################################
1380 my $lycos_search_url = "http://search.lycos.com/default.asp" .
1386 sub pick_from_lycos_text {
1387 my ( $timeout ) = @_;
1389 $last_search = $lycos_search_url; # for warnings
1391 # lycos seems to always give us back dictionaries and word lists if
1392 # we search for more than one word...
1394 my $words = random_word();
1396 my $start = int(rand(8)) * 10 + 1;
1397 my $search_url = $lycos_search_url . $words . "&first=$start&page=more";
1399 my ($search_hit_count, @subpages) =
1400 pick_from_search_engine ($timeout, $search_url, $words);
1402 my @candidates = ();
1403 foreach my $u (@subpages) {
1405 # Lycos plays redirection games.
1406 next unless ($u =~ m@^http://click.lycos.com/director.asp
1411 $u = url_decode($1);
1413 LOG ($verbose_filter, " candidate: $u");
1414 push @candidates, $u;
1417 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1418 $timeout, @candidates);
1423 ############################################################################
1425 # Pick images by feeding random words into news.yahoo.com
1427 ############################################################################
1429 my $yahoo_news_url = "http://search.news.yahoo.com/search/news" .
1432 "&s=-%24s%2C-date" .
1440 sub pick_from_yahoo_news_text {
1441 my ( $timeout ) = @_;
1443 $last_search = $yahoo_news_url; # for warnings
1445 my $words = random_words(0);
1446 my $search_url = $yahoo_news_url . $words;
1448 my ($search_hit_count, @subpages) =
1449 pick_from_search_engine ($timeout, $search_url, $words);
1451 my @candidates = ();
1452 foreach my $u (@subpages) {
1453 # only accept URLs on Yahoo's news site
1454 next unless ($u =~ m@^http://dailynews\.yahoo\.com/@i ||
1455 $u =~ m@^http://story\.news\.yahoo\.com/@i);
1457 LOG ($verbose_filter, " candidate: $u");
1458 push @candidates, $u;
1461 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1462 $timeout, @candidates);
1467 ############################################################################
1469 # Pick images from LiveJournal's list of recently-posted images.
1471 ############################################################################
1473 my $livejournal_img_url = "http://www.livejournal.com/stats/latest-img.bml";
1476 sub pick_from_livejournal_images {
1477 my ( $timeout ) = @_;
1479 $last_search = $livejournal_img_url; # for warnings
1481 my ( $base, $body ) = get_document ($livejournal_img_url, undef, $timeout);
1482 return () unless $body;
1484 my @candidates = ();
1487 $body =~ s/(<recent-image)\b/\n$1/gsi;
1489 foreach (split (/\n/, $body)) {
1490 next unless (m/^<recent-image\b/);
1491 next unless (m/\bIMG=[\'\"]([^\'\"]+)[\'\"]/si);
1492 my $img = html_unquote ($1);
1493 next unless (m/\bURL=[\'\"]([^\'\"]+)[\'\"]/si);
1494 my $page = html_unquote ($1);
1495 my @pair = ($img, $page);
1496 LOG ($verbose_filter, " candidate: $img");
1497 push @candidates, \@pair;
1500 return () if ($#candidates == -1);
1502 my $i = int(rand($#candidates+1));
1503 my ($img, $page) = @{$candidates[$i]};
1505 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#candidates+1) .
1508 return ($page, $img);
1512 ############################################################################
1514 # Pick images by waiting for driftnet to populate a temp dir with files.
1515 # Requires driftnet version 0.1.5 or later.
1516 # (Driftnet is a program by Chris Lightfoot that sniffs your local ethernet
1517 # for images being downloaded by others.)
1518 # Driftnet/webcollage integration by jwz.
1520 ############################################################################
1523 sub pick_from_driftnet {
1524 my ( $timeout ) = @_;
1526 my $id = $driftnet_magic;
1527 my $dir = $driftnet_dir;
1531 error ("\$driftnet_dir unset?") unless ($dir);
1534 error ("$dir unreadable") unless (-d "$dir/.");
1536 $timeout = $http_timeout unless ($timeout);
1539 while ($now = time, $now < $start + $timeout) {
1541 opendir (DIR, $dir) || error ("$dir: $!");
1542 while (my $file = readdir(DIR)) {
1543 next if ($file =~ m/^\./);
1544 $file = "$dir/$file";
1546 LOG ($verbose_load, "picked file $file ($id)");
1547 return ($id, $file);
1551 LOG (($verbose_net || $verbose_load), "timed out for $id");
1556 sub get_driftnet_file {
1559 error ("\$driftnet_dir unset?") unless ($driftnet_dir);
1561 my $id = $driftnet_magic;
1562 my $re = qr/$driftnet_dir/;
1563 error ("$id: $file not in $driftnet_dir?")
1564 unless ($file =~ m@^$re@o);
1567 open (IN, $file) || error ("$id: $file: $!");
1569 while (<IN>) { $body .= $_; }
1570 close IN || error ("$id: $file: $!");
1571 unlink ($file) || error ("$id: $file: rm: $!");
1572 return ($id, $body);
1576 sub spawn_driftnet {
1579 # make a directory to use.
1581 my $tmp = $ENV{TEMPDIR} || "/tmp";
1582 $driftnet_dir = sprintf ("$tmp/driftcollage-%08x", rand(0xffffffff));
1583 LOG ($verbose_exec, "mkdir $driftnet_dir");
1584 last if mkdir ($driftnet_dir, 0700);
1587 if (! ($cmd =~ m/\s/)) {
1588 # if the command didn't have any arguments in it, then it must be just
1589 # a pointer to the executable. Append the default args to it.
1590 my $dargs = $default_driftnet_cmd;
1591 $dargs =~ s/^[^\s]+//;
1595 # point the driftnet command at our newly-minted private directory.
1597 $cmd .= " -d $driftnet_dir";
1598 $cmd .= ">/dev/null" unless ($verbose_exec);
1601 if ($pid < 0) { error ("fork: $!\n"); }
1604 push @pids_to_kill, $pid;
1605 LOG ($verbose_exec, "forked for \"$cmd\"");
1608 nontrapping_system ($cmd) || error ("exec: $!");
1611 # wait a bit, then make sure the process actually started up.
1614 error ("pid $pid failed to start \"$cmd\"")
1615 unless (1 == kill (0, $pid));
1619 ############################################################################
1621 # Pick a random image in a random way
1623 ############################################################################
1626 # Picks a random image on a random page, and returns two URLs:
1627 # the page containing the image, and the image.
1628 # Returns () if nothing found this time.
1632 my ( $timeout ) = @_;
1634 $current_state = "select";
1635 $load_method = "none";
1637 my $n = int(rand(100));
1640 my @rest = @search_methods;
1643 my $pct = shift @rest;
1644 my $name = shift @rest;
1645 my $tfn = shift @rest;
1647 if ($total > $n && !defined($fn)) {
1649 $current_state = $name;
1650 $load_method = $current_state;
1654 if ($total != 100) {
1655 error ("internal error: \@search_methods totals to $total%!");
1658 record_attempt ($current_state);
1659 return $fn->($timeout);
1664 ############################################################################
1666 # Statistics and logging
1668 ############################################################################
1671 return strftime ("%H:%M:%S: ", localtime);
1675 return "$progname: " . timestr() . "$current_state: ";
1680 print STDERR blurb() . "$err\n";
1692 my $head = "$progname: DEBUG: ";
1693 foreach (split (/\n/, $lastlog)) {
1694 print STDERR "$head$_\n";
1700 my ($print, $msg) = @_;
1701 my $blurb = timestr() . "$current_state: ";
1702 $lastlog .= "$blurb$msg\n";
1703 print STDERR "$progname: $blurb$msg\n" if $print;
1708 my %stats_successes;
1711 my $last_state = undef;
1712 sub record_attempt {
1716 record_failure($last_state) unless ($image_succeeded > 0);
1718 $last_state = $name;
1721 report_performance();
1724 $image_succeeded = 0;
1725 $suppress_audit = 0;
1728 sub record_success {
1729 my ($name, $url, $base) = @_;
1730 if (defined($stats_successes{$name})) {
1731 $stats_successes{$name}++;
1733 $stats_successes{$name} = 1;
1736 stop_timer ($name, 1);
1737 my $o = $current_state;
1738 $current_state = $name;
1739 save_recent_url ($url, $base);
1740 $current_state = $o;
1741 $image_succeeded = 1;
1746 sub record_failure {
1749 return if $image_succeeded;
1751 stop_timer ($name, 0);
1752 if ($verbose_load && !$verbose_exec) {
1754 if ($suppress_audit) {
1755 print STDERR "$progname: " . timestr() . "(audit log suppressed)\n";
1759 my $o = $current_state;
1760 $current_state = "DEBUG";
1762 my $line = "#" x 78;
1763 print STDERR "\n\n\n";
1764 print STDERR ("#" x 78) . "\n";
1765 print STDERR blurb() . "failed to get an image. Full audit log:\n";
1768 print STDERR ("-" x 78) . "\n";
1769 print STDERR "\n\n";
1771 $current_state = $o;
1773 $image_succeeded = 0;
1780 my $i = $stats_successes{$name};
1781 my $j = $stats_attempts{$name};
1784 return "" . ($j ? int($i * 100 / $j) : "0") . "%";
1788 my $current_start_time = 0;
1792 $current_start_time = time;
1794 if (defined($stats_attempts{$name})) {
1795 $stats_attempts{$name}++;
1797 $stats_attempts{$name} = 1;
1799 if (!defined($stats_elapsed{$name})) {
1800 $stats_elapsed{$name} = 0;
1805 my ($name, $success) = @_;
1806 $stats_elapsed{$name} += time - $current_start_time;
1810 my $last_report_time = 0;
1811 sub report_performance {
1813 return unless $verbose_warnings;
1816 return unless ($now >= $last_report_time + $report_performance_interval);
1817 my $ot = $last_report_time;
1818 $last_report_time = $now;
1820 return if ($ot == 0);
1822 my $blurb = "$progname: " . timestr();
1825 print STDERR "${blurb}Current standings:\n";
1827 foreach my $name (sort keys (%stats_attempts)) {
1828 my $try = $stats_attempts{$name};
1829 my $suc = $stats_successes{$name} || 0;
1830 my $pct = int($suc * 100 / $try);
1831 my $secs = $stats_elapsed{$name};
1832 my $secs_link = int($secs / $try);
1833 print STDERR sprintf ("$blurb %-12s %4s (%d/%d);\t %2d secs/link\n",
1834 "$name:", "$pct%", $suc, $try, $secs_link);
1840 my $max_recent_images = 400;
1841 my $max_recent_sites = 20;
1842 my @recent_images = ();
1843 my @recent_sites = ();
1845 sub save_recent_url {
1846 my ($url, $base) = @_;
1848 return unless ($verbose_warnings);
1851 my ($site) = m@^http://([^ \t\n\r/:]+)@;
1852 return unless defined ($site);
1854 if ($base eq $driftnet_magic) {
1855 $site = $driftnet_magic;
1856 @recent_images = ();
1860 foreach (@recent_images) {
1862 print STDERR blurb() . "WARNING: recently-duplicated image: $url" .
1863 " (on $base via $last_search)\n";
1869 # suppress "duplicate site" warning via %warningless_sites.
1871 if ($warningless_sites{$site}) {
1873 } elsif ($site =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
1874 $warningless_sites{$1}) {
1876 } elsif ($site =~ m@([^.]+\.[^.]+)$@ &&
1877 $warningless_sites{$1}) {
1882 foreach (@recent_sites) {
1884 print STDERR blurb() . "WARNING: recently-duplicated site: $site" .
1885 " ($url on $base via $last_search)\n";
1891 push @recent_images, $url;
1892 push @recent_sites, $site;
1893 shift @recent_images if ($#recent_images >= $max_recent_images);
1894 shift @recent_sites if ($#recent_sites >= $max_recent_sites);
1899 ##############################################################################
1903 ##############################################################################
1910 s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
1915 # Given the raw body of a GIF document, returns the dimensions of the image.
1919 my $type = substr($body, 0, 6);
1921 return () unless ($type =~ /GIF8[7,9]a/);
1922 $s = substr ($body, 6, 10);
1923 my ($a,$b,$c,$d) = unpack ("C"x4, $s);
1924 return (($b<<8|$a), ($d<<8|$c));
1927 # Given the raw body of a JPEG document, returns the dimensions of the image.
1932 my $L = length($body);
1934 my $c1 = substr($body, $i, 1); $i++;
1935 my $c2 = substr($body, $i, 1); $i++;
1936 return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
1939 while (ord($ch) != 0xDA && $i < $L) {
1940 # Find next marker, beginning with 0xFF.
1941 while (ord($ch) != 0xFF) {
1942 return () if (length($body) <= $i);
1943 $ch = substr($body, $i, 1); $i++;
1945 # markers can be padded with any number of 0xFF.
1946 while (ord($ch) == 0xFF) {
1947 return () if (length($body) <= $i);
1948 $ch = substr($body, $i, 1); $i++;
1951 # $ch contains the value of the marker.
1952 my $marker = ord($ch);
1954 if (($marker >= 0xC0) &&
1955 ($marker <= 0xCF) &&
1956 ($marker != 0xC4) &&
1957 ($marker != 0xCC)) { # it's a SOFn marker
1959 return () if (length($body) <= $i);
1960 my $s = substr($body, $i, 4); $i += 4;
1961 my ($a,$b,$c,$d) = unpack("C"x4, $s);
1962 return (($c<<8|$d), ($a<<8|$b));
1965 # We must skip variables, since FFs in variable names aren't
1966 # valid JPEG markers.
1967 return () if (length($body) <= $i);
1968 my $s = substr($body, $i, 2); $i += 2;
1969 my ($c1, $c2) = unpack ("C"x2, $s);
1970 my $length = ($c1 << 8) | $c2;
1971 return () if ($length < 2);
1978 # Given the raw body of a PNG document, returns the dimensions of the image.
1982 return () unless ($body =~ m/^\211PNG\r/);
1983 my ($bits) = ($body =~ m/^.{12}(.{12})/s);
1984 return () unless defined ($bits);
1985 return () unless ($bits =~ /^IHDR/);
1986 my ($ign, $w, $h) = unpack("a4N2", $bits);
1991 # Given the raw body of a GIF, JPEG, or PNG document, returns the dimensions
1996 my ($w, $h) = gif_size ($body);
1997 if ($w && $h) { return ($w, $h); }
1998 ($w, $h) = jpeg_size ($body);
1999 if ($w && $h) { return ($w, $h); }
2000 return png_size ($body);
2004 # returns the full path of the named program, or undef.
2008 foreach (split (/:/, $ENV{PATH})) {
2009 if (-x "$_/$prog") {
2017 # Like rand(), but chooses numbers with a bell curve distribution.
2020 $_ = 1.0 unless defined($_);
2022 return (rand($_) + rand($_) + rand($_));
2026 sub signal_cleanup {
2028 print STDERR blurb() . (defined($sig)
2029 ? "caught signal $sig."
2036 if (@pids_to_kill) {
2037 print STDERR blurb() . "killing: " . join(' ', @pids_to_kill) . "\n";
2038 kill ('TERM', @pids_to_kill);
2044 ##############################################################################
2046 # Generating a list of urls only
2048 ##############################################################################
2050 sub url_only_output {
2052 my ($base, $img) = pick_image;
2056 print "$img $base\n";
2061 ##############################################################################
2063 # Running as an xscreensaver module
2065 ##############################################################################
2067 my $image_ppm = sprintf ("%s/webcollage-%08x",
2068 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2070 my $image_tmp1 = sprintf ("%s/webcollage-1-%08x",
2071 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2073 my $image_tmp2 = sprintf ("%s/webcollage-2-%08x",
2074 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2077 my $filter_cmd = undef;
2078 my $post_filter_cmd = undef;
2079 my $background = undef;
2081 my @imagemap_areas = ();
2082 my $imagemap_html_tmp = undef;
2083 my $imagemap_jpg_tmp = undef;
2086 my $img_width; # size of the image being generated.
2092 unlink $image_ppm, $image_tmp1, $image_tmp2;
2093 unlink $imagemap_html_tmp, $imagemap_jpg_tmp
2094 if (defined ($imagemap_html_tmp));
2098 # Like system, but prints status about exit codes, and kills this process
2099 # with whatever signal killed the sub-process, if any.
2101 sub nontrapping_system {
2105 s/\"[^\"]+\"/\"...\"/g;
2107 LOG ($verbose_exec, "executing \"$_\"");
2112 LOG ($verbose_exec, "subproc exited normally.");
2113 } elsif (($rc & 0xff) == 0) {
2115 LOG ($verbose_exec, "subproc exited with status $rc.");
2118 LOG ($verbose_exec, "subproc dumped core.");
2121 LOG ($verbose_exec, "subproc died with signal $rc.");
2122 # die that way ourselves.
2130 # Given the URL of a GIF, JPEG, or PNG image, and the body of that image,
2131 # writes a PPM to the given output file. Returns the width/height of the
2132 # image if successful.
2135 my ($url, $body, $output) = @_;
2136 my ($cmd, $cmd2, $w, $h);
2138 if ((@_ = gif_size ($body))) {
2141 } elsif ((@_ = jpeg_size ($body))) {
2144 } elsif ((@_ = png_size ($body))) {
2148 LOG (($verbose_pbm || $verbose_load),
2149 "not a GIF, JPG, or PNG" .
2150 (($body =~ m@<(base|html|head|body|script|table|a href)>@i)
2151 ? " (looks like HTML)" : "") .
2153 $suppress_audit = 1;
2157 $cmd2 = "exec $cmd"; # yes, this really is necessary. if we don't
2158 # do this, the process doesn't die properly.
2159 if (!$verbose_pbm) {
2161 # We get a "giftopnm: got a 'Application Extension' extension"
2162 # warning any time it's an animgif.
2164 # Note that "giftopnm: EOF / read error on image data" is not
2165 # always a fatal error -- sometimes the image looks fine anyway.
2167 $cmd2 .= " 2>/dev/null";
2170 # There exist corrupted GIF and JPEG files that can make giftopnm and
2171 # djpeg lose their minds and go into a loop. So this gives those programs
2172 # a small timeout -- if they don't complete in time, kill them.
2178 local $SIG{ALRM} = sub {
2180 "timed out ($cvt_timeout) for $cmd on \"$url\" in pid $pid");
2181 kill ('TERM', $pid) if ($pid);
2186 if (($pid = open(PIPE, "| $cmd2 > $output"))) {
2193 LOG ($verbose_exec, "awaiting $pid");
2195 LOG ($verbose_exec, "$pid completed");
2197 my $size = (stat($output))[7];
2198 $size = -1 unless defined($size);
2200 LOG ($verbose_pbm, "$cmd on ${w}x$h \"$url\" failed ($size bytes)");
2204 LOG ($verbose_pbm, "created ${w}x$h $output ($cmd)");
2207 print STDERR blurb() . "$cmd failed: $!\n";
2211 die if ($@ && $@ ne "alarm\n"); # propagate errors
2224 sub pick_root_displayer {
2227 foreach my $cmd (@root_displayers) {
2229 my ($name) = m/^([^ ]+)/;
2230 push @names, "\"$name\"";
2231 LOG ($verbose_exec, "looking for $name...");
2232 foreach my $dir (split (/:/, $ENV{PATH})) {
2233 LOG ($verbose_exec, " checking $dir/$name");
2234 return $cmd if (-x "$dir/$name");
2238 $names[$#names] = "or " . $names[$#names];
2239 error "none of: " . join (", ", @names) . " were found on \$PATH.";
2243 my $ppm_to_root_window_cmd = undef;
2246 sub x_or_pbm_output {
2248 # Check for our helper program, to see whether we need to use PPM pipelines.
2250 $_ = "webcollage-helper";
2251 if (defined ($webcollage_helper) || which ($_)) {
2252 $webcollage_helper = $_ unless (defined($webcollage_helper));
2253 LOG ($verbose_pbm, "found \"$webcollage_helper\"");
2254 $webcollage_helper .= " -v";
2256 LOG (($verbose_pbm || $verbose_load), "no $_ program");
2259 # make sure the various programs we execute exist, right up front.
2261 my @progs = ("ppmmake"); # always need this one
2263 if (!defined($webcollage_helper)) {
2264 # Only need these others if we don't have the helper.
2266 "giftopnm", "pngtopnm", "djpeg",
2267 "pnmpaste", "pnmscale", "pnmcut");
2271 which ($_) || error "$_ not found on \$PATH.";
2274 # find a root-window displayer program.
2276 $ppm_to_root_window_cmd = pick_root_displayer();
2278 if (!$img_width || !$img_height) {
2280 which ($_) || error "$_ not found on \$PATH.";
2282 ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
2283 if (!defined($img_height)) {
2284 error "xdpyinfo failed.";
2288 my $bgcolor = "#000000";
2289 my $bgimage = undef;
2292 if ($background =~ m/^\#[0-9a-f]+$/i) {
2293 $bgcolor = $background;
2295 } elsif (-r $background) {
2296 $bgimage = $background;
2298 } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
2299 error "not a color or readable file: $background";
2302 # default to assuming it's a color
2303 $bgcolor = $background;
2307 # Create the sold-colored base image.
2309 $_ = "ppmmake '$bgcolor' $img_width $img_height";
2310 LOG ($verbose_pbm, "creating base image: $_");
2311 nontrapping_system "$_ > $image_ppm";
2313 # Paste the default background image in the middle of it.
2320 open(IMG, "<$bgimage") || error "couldn't open $bgimage: $!";
2322 while (<IMG>) { $body .= $_; }
2325 if ((@_ = gif_size ($body))) {
2327 $cmd = "giftopnm |";
2329 } elsif ((@_ = jpeg_size ($body))) {
2333 } elsif ((@_ = png_size ($body))) {
2335 $cmd = "pngtopnm |";
2337 } elsif ($body =~ m/^P\d\n(\d+) (\d+)\n/) {
2343 error "$bgimage is not a GIF, JPEG, PNG, or PPM.";
2346 my $x = int (($img_width - $iw) / 2);
2347 my $y = int (($img_height - $ih) / 2);
2349 "pasting $bgimage (${iw}x$ih) into base image at $x,$y");
2351 $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
2352 open (IMG, "| $cmd") || error "running $cmd: $!";
2356 LOG ($verbose_exec, "subproc exited normally.");
2357 rename ($image_tmp1, $image_ppm) ||
2358 error "renaming $image_tmp1 to $image_ppm: $!";
2364 my ($base, $img) = pick_image();
2365 my $source = $current_state;
2366 $current_state = "loadimage";
2368 my ($headers, $body) = get_document ($img, $base);
2370 paste_image ($base, $img, $body, $source);
2374 $current_state = "idle";
2375 $load_method = "none";
2377 unlink $image_tmp1, $image_tmp2;
2383 my ($base, $img, $body, $source) = @_;
2385 $current_state = "paste";
2387 $suppress_audit = 0;
2389 LOG ($verbose_pbm, "got $img (" . length($body) . ")");
2393 # If we are using the webcollage-helper, then we do not need to convert this
2394 # image to a PPM. But, if we're using a filter command, we still must, since
2395 # that's what the filters expect (webcollage-helper can read PPMs, so that's
2398 if (defined ($webcollage_helper) &&
2399 !defined ($filter_cmd)) {
2401 ($iw, $ih) = image_size ($body);
2403 LOG (($verbose_pbm || $verbose_load),
2404 "not a GIF, JPG, or PNG" .
2405 (($body =~ m@<(base|html|head|body|script|table|a href)>@i)
2406 ? " (looks like HTML)" : "") .
2408 $suppress_audit = 1;
2414 open (OUT, ">$image_tmp1") || error ("writing $image_tmp1: $!");
2415 print OUT $body || error ("writing $image_tmp1: $!");
2416 close OUT || error ("writing $image_tmp1: $!");
2419 ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
2422 LOG ($verbose_pbm, "unable to make PBM from $img");
2427 record_success ($load_method, $img, $base);
2430 my $ow = $iw; # used only for error messages
2433 # don't just tack this onto the front of the pipeline -- we want it to
2434 # be able to change the size of the input image.
2437 LOG ($verbose_pbm, "running $filter_cmd");
2439 my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
2441 LOG(($verbose_pbm || $verbose_load), "failed command: \"$filter_cmd\"");
2442 LOG(($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
2445 rename ($image_tmp2, $image_tmp1);
2447 # re-get the width/height in case the filter resized it.
2449 open(IMG, "<$image_tmp1") || return 0;
2452 ($iw, $ih) = m/^(\d+) (\d+)$/;
2454 return 0 unless ($iw && $ih);
2457 my $target_w = $img_width; # max rectangle into which the image must fit
2458 my $target_h = $img_height;
2464 # Usually scale the image to fit on the screen -- but sometimes scale it
2465 # to fit on half or a quarter of the screen. (We do this by reducing the
2466 # size of the target rectangle.) Note that the image is not merely scaled
2467 # to fit; we instead cut the image in half repeatedly until it fits in the
2468 # target rectangle -- that gives a wider distribution of sizes.
2470 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; } # reduce target rect
2471 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
2473 if ($iw > $target_w || $ih > $target_h) {
2474 while ($iw > $target_w ||
2480 if ($iw <= 10 || $ih <= 10) {
2481 LOG ($verbose_pbm, "scaling to ${iw}x$ih would have been bogus.");
2485 LOG ($verbose_pbm, "scaling to ${iw}x$ih ($scale)");
2487 $cmd .= " | pnmscale -xsize $iw -ysize $ih";
2491 my $src = $image_tmp1;
2493 my $crop_x = 0; # the sub-rectangle of the image
2494 my $crop_y = 0; # that we will actually paste.
2498 # The chance that we will randomly crop out a section of an image starts
2499 # out fairly low, but goes up for images that are very large, or images
2500 # that have ratios that make them look like banners (we try to avoid
2501 # banner images entirely, but they slip through when the IMG tags didn't
2502 # have WIDTH and HEIGHT specified.)
2504 my $crop_chance = 0.2;
2505 if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
2506 $crop_chance += 0.2;
2508 if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
2509 $crop_chance += 0.2;
2511 if ($min_ratio && ($iw * $min_ratio) > $ih) {
2512 $crop_chance += 0.7;
2515 if ($crop_chance > 0.1) {
2516 LOG ($verbose_pbm, "crop chance: $crop_chance");
2519 if (rand() < $crop_chance) {
2524 if ($crop_w > $min_width) {
2525 # if it's a banner, select the width linearly.
2526 # otherwise, select a bell.
2527 my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
2530 $crop_w = $min_width + int ($r * ($crop_w - $min_width));
2531 $crop_x = int (rand() * ($ow - $crop_w));
2533 if ($crop_h > $min_height) {
2534 # height always selects as a bell.
2535 $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
2536 $crop_y = int (rand() * ($oh - $crop_h));
2539 if ($crop_x != 0 || $crop_y != 0 ||
2540 $crop_w != $iw || $crop_h != $ih) {
2542 "randomly cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
2546 # Where the image should logically land -- this might be negative.
2548 my $x = int((rand() * ($img_width + $crop_w/2)) - $crop_w*3/4);
2549 my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
2551 # if we have chosen to paste the image outside of the rectangle of the
2552 # screen, then we need to crop it.
2556 $x + $crop_w > $img_width ||
2557 $y + $crop_h > $img_height) {
2560 "cropping for effective paste of ${crop_w}x$crop_h \@ $x,$y");
2562 if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
2563 if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
2565 if ($x + $crop_w >= $img_width) { $crop_w = $img_width - $x - 1; }
2566 if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
2569 # If any cropping needs to happen, add pnmcut.
2571 if ($crop_x != 0 || $crop_y != 0 ||
2572 $crop_w != $iw || $crop_h != $ih) {
2575 $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
2576 LOG ($verbose_pbm, "cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
2579 LOG ($verbose_pbm, "pasting ${iw}x$ih \@ $x,$y in $image_ppm");
2581 $cmd .= " | pnmpaste - $x $y $image_ppm";
2583 $cmd =~ s@^ *\| *@@;
2585 if (defined ($webcollage_helper)) {
2586 $cmd = "$webcollage_helper $image_tmp1 $image_ppm " .
2587 "$scale $opacity " .
2588 "$crop_x $crop_y $x $y " .
2593 # use a PPM pipeline
2595 $_ .= " < $image_tmp1 > $image_tmp2";
2599 $_ = "($_) 2>&1 | sed s'/^/" . blurb() . "/'";
2601 $_ .= " 2> /dev/null";
2604 my $rc = nontrapping_system ($_);
2606 if (defined ($webcollage_helper) && -z $image_ppm) {
2607 LOG (1, "failed command: \"$cmd\"");
2608 print STDERR "\naudit log:\n\n\n";
2609 print STDERR ("#" x 78) . "\n";
2610 print STDERR blurb() . "$image_ppm has zero size\n";
2612 print STDERR "\n\n";
2617 LOG (($verbose_pbm || $verbose_load), "failed command: \"$cmd\"");
2618 LOG (($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
2622 if (!defined ($webcollage_helper)) {
2623 rename ($image_tmp2, $image_ppm) || return;
2626 my $target = "$image_ppm";
2628 # don't just tack this onto the end of the pipeline -- we don't want it
2629 # to end up in $image_ppm, because we don't want the results to be
2632 if ($post_filter_cmd) {
2636 $target = $image_tmp1;
2637 if (!defined ($webcollage_helper)) {
2638 $cmd = "($post_filter_cmd) < $image_ppm > $target";
2640 # Blah, my scripts need the JPEG data, but some other folks need
2641 # the PPM data -- what to do? Ignore the problem, that's what!
2642 # $cmd = "djpeg < $image_ppm | ($post_filter_cmd) > $target";
2643 $cmd = "($post_filter_cmd) < $image_ppm > $target";
2646 $rc = nontrapping_system ($cmd);
2648 LOG ($verbose_pbm, "filter failed: \"$post_filter_cmd\"\n");
2653 if (!$no_output_p) {
2654 my $tsize = (stat($target))[7];
2656 $cmd = "$ppm_to_root_window_cmd $target";
2658 # xv seems to hate being killed. it tends to forget to clean
2659 # up after itself, and leaves windows around and colors allocated.
2660 # I had this same problem with vidwhacker, and I'm not entirely
2661 # sure what I did to fix it. But, let's try this: launch xv
2662 # in the background, so that killing this process doesn't kill it.
2663 # it will die of its own accord soon enough. So this means we
2664 # start pumping bits to the root window in parallel with starting
2665 # the next network retrieval, which is probably a better thing
2670 $rc = nontrapping_system ($cmd);
2673 LOG (($verbose_pbm || $verbose_load), "display failed: \"$cmd\"");
2678 LOG ($verbose_pbm, "$target size is $tsize");
2682 $source .= "-" . stats_of($source);
2683 print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n"
2684 if ($verbose_imgmap);
2686 if ($imagemap_base) {
2687 update_imagemap ($base, $x, $y, $iw, $ih,
2688 $image_ppm, $img_width, $img_height);
2697 sub update_imagemap {
2698 my ($url, $x, $y, $w, $h, $image_ppm, $image_width, $image_height) = @_;
2700 $current_state = "imagemap";
2702 my $max_areas = 200;
2704 $url = html_quote ($url);
2707 my $area = "<AREA SHAPE=RECT COORDS=\"$x,$y,$x2,$y2\" HREF=\"$url\">";
2708 unshift @imagemap_areas, $area; # put one on the front
2709 if ($#imagemap_areas >= $max_areas) {
2710 pop @imagemap_areas; # take one off the back.
2713 LOG ($verbose_pbm, "area: $x,$y,$x2,$y2 (${w}x$h)");
2715 my $map_name = $imagemap_base;
2716 $map_name =~ s@^.*/@@;
2717 $map_name = 'collage' if ($map_name eq '');
2719 my $imagemap_html = $imagemap_base . ".html";
2720 my $imagemap_jpg = $imagemap_base . ".jpg";
2722 if (!defined ($imagemap_html_tmp)) {
2723 $imagemap_html_tmp = $imagemap_html . sprintf (".%08x", rand(0xffffffff));
2724 $imagemap_jpg_tmp = $imagemap_jpg . sprintf (".%08x", rand(0xffffffff));
2727 # Read the imagemap html file (if any) to get a template.
2729 my $template_html = '';
2732 if (open (IN, "<$imagemap_html")) {
2733 while (<IN>) { $template_html .= $_; }
2735 LOG ($verbose_pbm, "read template $imagemap_html");
2738 if ($template_html =~ m/^\s*$/s) {
2739 $template_html = ("<MAP NAME=\"$map_name\"></MAP>\n" .
2740 "<IMG SRC=\"$imagemap_base.jpg\"" .
2741 " USEMAP=\"$map_name\">\n");
2742 LOG ($verbose_pbm, "created dummy template");
2746 # Write the jpg to a tmp file
2749 #my $cmd = "cjpeg < $image_ppm > $imagemap_jpg_tmp";
2750 my $cmd = "cp -p $image_ppm $imagemap_jpg_tmp";
2751 my $rc = nontrapping_system ($cmd);
2753 error ("imagemap jpeg failed: \"$cmd\"\n");
2757 # Write the html to a tmp file
2760 my $body = $template_html;
2761 my $areas = join ("\n\t", @imagemap_areas);
2762 my $map = ("<MAP NAME=\"$map_name\">\n\t$areas\n</MAP>");
2763 my $img = ("<IMG SRC=\"$imagemap_base.jpg\" " .
2765 "WIDTH=$image_width HEIGHT=$image_height " .
2766 "USEMAP=\"#$map_name\">");
2767 $body =~ s@(<MAP\s+NAME=\"[^\"]*\"\s*>).*?(</MAP>)@$map@is;
2768 $body =~ s@<IMG\b[^<>]*\bUSEMAP\b[^<>]*>@$img@is;
2770 # if there are magic webcollage spans in the html, update those too.
2773 my @st = stat ($imagemap_jpg_tmp);
2774 my $date = strftime("%d-%b-%Y %l:%M:%S %p %Z", localtime($st[9]));
2775 my $size = int(($st[7] / 1024) + 0.5) . "K";
2776 $body =~ s@(<SPAN\s+CLASS=\"webcollage_date\">).*?(</SPAN>)@$1$date$2@si;
2777 $body =~ s@(<SPAN\s+CLASS=\"webcollage_size\">).*?(</SPAN>)@$1$size$2@si;
2781 open (OUT, ">$imagemap_html_tmp") || error ("$imagemap_html_tmp: $!");
2782 print OUT $body || error ("$imagemap_html_tmp: $!");
2783 close OUT || error ("$imagemap_html_tmp: $!");
2784 LOG ($verbose_pbm, "wrote $imagemap_html_tmp");
2787 # Rename the two tmp files to the real files
2789 rename ($imagemap_html_tmp, $imagemap_html) ||
2790 error "renaming $imagemap_html_tmp to $imagemap_html";
2791 LOG ($verbose_pbm, "wrote $imagemap_html");
2792 rename ($imagemap_jpg_tmp, $imagemap_jpg) ||
2793 error "renaming $imagemap_jpg_tmp to $imagemap_jpg";
2794 LOG ($verbose_pbm, "wrote $imagemap_jpg");
2800 $SIG{HUP} = \&signal_cleanup;
2801 $SIG{INT} = \&signal_cleanup;
2802 $SIG{QUIT} = \&signal_cleanup;
2803 $SIG{ABRT} = \&signal_cleanup;
2804 $SIG{KILL} = \&signal_cleanup;
2805 $SIG{TERM} = \&signal_cleanup;
2807 # Need this so that if giftopnm dies, we don't die.
2808 $SIG{PIPE} = 'IGNORE';
2811 END { signal_cleanup(); }
2820 my $driftnet_cmd = 0;
2822 $current_state = "init";
2823 $load_method = "none";
2827 # historical suckage: the environment variable name is lower case.
2828 $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
2830 while ($_ = $ARGV[0]) {
2832 if ($_ eq "-display" ||
2838 $ENV{DISPLAY} = shift @ARGV;
2839 } elsif ($_ eq "-root") {
2841 } elsif ($_ eq "-no-output") {
2843 } elsif ($_ eq "-urls-only") {
2846 } elsif ($_ eq "-imagemap") {
2847 $imagemap_base = shift @ARGV;
2849 } elsif ($_ eq "-verbose") {
2851 } elsif (m/^-v+$/) {
2852 $verbose += length($_)-1;
2853 } elsif ($_ eq "-delay") {
2854 $delay = shift @ARGV;
2855 } elsif ($_ eq "-timeout") {
2856 $http_timeout = shift @ARGV;
2857 } elsif ($_ eq "-filter") {
2858 $filter_cmd = shift @ARGV;
2859 } elsif ($_ eq "-filter2") {
2860 $post_filter_cmd = shift @ARGV;
2861 } elsif ($_ eq "-background" || $_ eq "-bg") {
2862 $background = shift @ARGV;
2863 } elsif ($_ eq "-size") {
2865 if (m@^(\d+)x(\d+)$@) {
2869 error "argument to \"-size\" must be of the form \"640x400\"";
2871 } elsif ($_ eq "-proxy" || $_ eq "-http-proxy") {
2872 $http_proxy = shift @ARGV;
2873 } elsif ($_ eq "-dictionary" || $_ eq "-dict") {
2874 $dict = shift @ARGV;
2875 } elsif ($_ eq "-driftnet" || $_ eq "--driftnet") {
2876 @search_methods = ( 100, "driftnet", \&pick_from_driftnet );
2877 if (! ($ARGV[0] =~ m/^-/)) {
2878 $driftnet_cmd = shift @ARGV;
2880 $driftnet_cmd = $default_driftnet_cmd;
2882 } elsif ($_ eq "-debug" || $_ eq "--debug") {
2883 my $which = shift @ARGV;
2884 my @rest = @search_methods;
2887 my $pct = shift @rest;
2888 my $name = shift @rest;
2889 my $tfn = shift @rest;
2891 if ($name eq $which) {
2892 @search_methods = (100, $name, $tfn);
2897 error "no such search method as \"$which\"" unless ($ok);
2898 LOG (1, "DEBUG: using only \"$which\"");
2901 print STDERR "$copyright\nusage: $progname " .
2902 "[-root] [-display dpy] [-verbose] [-debug which]\n" .
2903 "\t\t [-timeout secs] [-delay secs] [-size WxH]\n" .
2904 "\t\t [-no-output] [-urls-only] [-imagemap filename]\n" .
2905 "\t\t [-filter cmd] [-filter2 cmd] [-background color]\n" .
2906 "\t\t [-dictionary dictionary-file] [-http-proxy host[:port]]\n" .
2907 "\t\t [-driftnet [driftnet-program-and-args]]\n" .
2913 if ($http_proxy && $http_proxy eq "") {
2914 $http_proxy = undef;
2916 if ($http_proxy && $http_proxy =~ m@^http://([^/]*)/?$@ ) {
2917 # historical suckage: allow "http://host:port" as well as "host:port".
2921 if (!$root_p && !$no_output_p) {
2922 print STDERR $copyright;
2923 error "the -root argument is mandatory (for now.)";
2926 if (!$no_output_p && !$ENV{DISPLAY}) {
2927 error "\$DISPLAY is not set.";
2931 if ($verbose == 1) {
2932 $verbose_imgmap = 1;
2933 $verbose_warnings = 1;
2935 } elsif ($verbose == 2) {
2936 $verbose_imgmap = 1;
2937 $verbose_warnings = 1;
2940 } elsif ($verbose == 3) {
2941 $verbose_imgmap = 1;
2942 $verbose_warnings = 1;
2944 $verbose_filter = 1;
2946 } elsif ($verbose == 4) {
2947 $verbose_imgmap = 1;
2948 $verbose_warnings = 1;
2950 $verbose_filter = 1;
2953 } elsif ($verbose == 5) {
2954 $verbose_imgmap = 1;
2955 $verbose_warnings = 1;
2957 $verbose_filter = 1;
2961 } elsif ($verbose == 6) {
2962 $verbose_imgmap = 1;
2963 $verbose_warnings = 1;
2965 $verbose_filter = 1;
2970 } elsif ($verbose >= 7) {
2971 $verbose_imgmap = 1;
2972 $verbose_warnings = 1;
2974 $verbose_filter = 1;
2982 error ("$dict does not exist") unless (-f $dict);
2990 spawn_driftnet ($driftnet_cmd) if ($driftnet_cmd);