) && next;
&Warn(q~missing end comment "-->"~, $link);
last REDIR;
}
next REDIR;
};
last if m#^(/head|body|h\d|font)#i;
s/^meta//i || next;
/\shttp-equiv\s*=\s*"?refresh/i || next;
/\scontent\s*=\s*"([^"]*)"/i || next;
$1 =~ /url\s*=\s*([^"\s]+)/i || next;
$url = &UniqueUrl($1);
$url =~ m#^\w+://# ||
&Warn("re-direct $url should be absolute", $link);
last;
}
$/ = "\n"; # use "\n" as newline separator
return $url; # return value
}
#--------------------------------------------------------------------------
# $path = LookupDir($dir)
#
# $dir and $path are both relative to server root.
# Find a default index file in $dir. Returns $path of default file
# on success or return 0 on failure. Caches results in $DefDir.
# Fills %LASTDIR with last successful directory listing.
#--------------------------------------------------------------------------
sub LookupDir
{
local($absdir) = @_;
$absdir =~ s#/$##;
local($dir) = $absdir . '/';
defined $DefDir{$dir} && return $DefDir{$dir}; # was cached
local(%file, $lc);
&Progress("looking for $dir(default)");
opendir(DIR, "$ServerRoot$absdir") ||
return $DefDir{$dir} = $LASTDIR = '';
%LASTDIR = ();
foreach (grep(!/^\./, readdir(DIR))) { # all files in directory
($lc = $_) =~ tr/A-Z/a-z/; # lower case version
$IgnoreCase && ($_ = $lc);
$LASTDIR{ "$dir$_" }++;
$file{$DefCaseSens ? $_ : $lc} = $_;
}
closedir(DIR);
$LASTDIR = '1';
foreach (@DefIndex) {
next unless $file{$_} && -f "$ServerRoot$dir$file{$_}";
return $DefDir{$dir} = "$dir$file{$_}";
}
return $DefDir{$dir} = '';
}
#--------------------------------------------------------------------------
# CheckOrphan(*dirlist, *orphlist, *badcase, $checkorphan, $checkcase)
#
# Checks every directory in dirlist and creates a list of
# all files that have not been checked by linklint.
#
# If CheckCase is set we first check the case of all found files
# in that directory.
#--------------------------------------------------------------------------
sub CheckOrphan
{
local(*dirlist, *orphlist, *badcase, $checkorphan, $checkcase) = @_;
%dirlist || return;
$checkorphan || $checkcase || return;
local($msg) = ' for';
$msg .= " orphans" if $checkorphan;
$msg .= " and" if $checkorphan && $checkcase;
$msg .= " case mismatch" if $checkcase;
local(@files, %files, $file, $link, $absdir, $reldir);
foreach $dir (sort keys %dirlist) {
&Progress("checking $dir");
&Progress($msg);
$reldir = $dir eq '(root)' ? '' : $dir;
$absdir = $ServerRoot . $reldir;
&PushDir($absdir) || next;
opendir(DIR, '.') || do {
&Warn(qq~could not read directory "$absdir"~, 'sys');
next;
};
@files = grep(!/^\./, readdir(DIR));
$IgnoreCase && grep( tr/A-Z/a-z/ && 0, @files);
closedir(DIR);
$checkcase && do {
%files = ();
grep($files{"$reldir/$_"}++, @files);
foreach $link ( grep( m#^$reldir/[^/]+$#i, keys %FileList) ) {
next if $files{$link};
($file) = grep(/$link/i, keys %files); # get "real" filename
$file = $file || $link; # just in case
$badcase{$file} = $FileList{$link}; # add to list
}
};
next unless $checkorphan;
foreach $file (@files) {
$DefIndexRE and $file =~ m/$DefIndexRE/o and next;
$link = "$reldir/$file";
next if $FileList{$link} || $dirlist{$link} ||
$badcase{$link};
-d $file && ($link .= "/"); # let them know it's a dir
$orphlist{$link} = "\n";
next unless $link =~ /\.($HtmlExts)$/io;
#----- parse html files for possible redirects
open($file, $file) || do {
&Warn(qq~could not open orphan "$link"~, 'sys');
next;
};
local($equiv) = &ParseRedirect($file, $link);
close($file);
$equiv && ($PrintAddenda{$link} = " => $equiv");
}
&PopDir;
}
}
#--------------------------------------------------------------------------
# ProcessLocal()
#
# Does the work needed between gathering links and printing.
#--------------------------------------------------------------------------
sub ProcessLocal {
local($file, $anch, $ref);
&Progress("\nProcessing ...");
#---- Resolve named anchors
$Arg{no_anchors} or do {
&HashUnique(*WantAnch);
&ResolveAnch(*WantAnch, *Anchor, *LostAnch, 1);
};
#---- resolve named image maps
&HashUnique(*WantMap);
&ResolveAnch(*WantMap, *ImgMap, *LostMap, 0);
&HashUnique(*FileList); # pathinfo and dirlookup can cause extras.
&HashUnique(*LostFile); # pathinfo and dirlookup can cause extras.
&HashUnique(*Action);
&HashUnique(*Forward);
&InvertKeys(*LostFile, *ErrF);
&InvertKeys(*BadCase, *CaseF);
&InvertKeys(*WarnList, *WarnF);
$Parsed = keys %Parsed;
$Parsed >= $Limit && ! $Arg{'limit'} &&
$Hints{"use -limit to check more than $Limit files."}++;
@PRINTFORM = @SiteForm;
&PrintFiles(0, 0, 0, 0); # count elements in local arrays
$ErrTot = $LostFile + $LostAnch + $BadCase;
$Fetched = keys %Fetched;
}
###########################################################################
#
# PRINTING ROUTINES
#
# Entry through PrintOutput() function.
#
###########################################################################
#--------------------------------------------------------------------------
# PrintOutput(*form, *summary, $docdir, $sumfile, $indexfile, $title)
#
# A wrapper for a printing routines. Computes counts of # of elements
# in all hashes (need scalars). Inverts some hashes for forward
# results. Prints output to files in $DocDir or to "std" output.
#--------------------------------------------------------------------------
sub PrintOutput
{
local(*printform) = shift;
@PRINTFORM = @printform; # used globally below
local(*SUMMARY) = @_; # Summary routine: used and passed on.
&PrintFiles(0, 0, 0, 0); # count elements in all hashes
&PrintDocDir(@_); # All -doc files
$LogFile && do {
print "\n";
&PrintFiles(@SumPrint); # summary list of results
print "\n";
&SUMMARY; # text summary at top of file zz ?
print "\n";
};
&PrintFiles(0,0,0, $PrnFlag); # print as user requested
return if $Silent; # -silent: no summary on screen
$lastsel = select(STDERR);
print "\n";
&PrintFiles(@SumPrint); # list summary
print "\n";
&SUMMARY; # text summary at bottom of screen
select($lastsel);
}
#--------------------------------------------------------------------------
# PrintFiles($DocDir, $DOCHEAD, $SUM, $flags)
#
# Prints all or part of the output according to the flags supplied.
# If $DocDir is supplied output goes to the files specified in the
# OpenDoc() calls, otherwise output goes to currently selected output.
# PrintFile is called several times to print lists to STDOUT,
# doc files, summary, and summary file. Passes globals to OpenDoc(),
# PrintLISTS() and PrintList().
# where to print:
# $DocDir send output to seperate files in $DocDir.
# summarize:
# $DOCHEAD add filenames to headers.
# $SUM 1: summary form, 2: summarize printLISTS to one line
#
#--------------------------------------------------------------------------
sub PrintFiles
{
local($docdir, $DOCHEAD, $SUM, $flags) = @_;
local($file, $data, $mask, $prog, @params);
foreach (@PRINTFORM) {
($file, $data, $mask, $prog, @params) = split(/;\s*/, $_);
$Dont_Output and $file =~ m/$Dont_Output/o and next;
$mask = oct($mask);
$flags || (eval("\$$data = \$$data || keys \%$data"), next);
&OpenDoc($docdir, $file, $data) || next;
next unless ($flags & $mask) == $mask;
$prog == 1 && &PrintList($data, @params);
$prog == 2 && &PrintLISTS($data, @params);
$prog == 3 && &PrintUrl($data, @params);
}
}
#--------------------------------------------------------------------------
# $flag = OpenDoc($docdir, $file, *list)
#
# A co-conspirator with PrintFiles().
# $file is the name of a file (sans extension) to be written in
# $DocDir. $anydata tells us if there is any data to be written
# to the file. Always erase old copies of all the files but save
# a backup copy if the file might be theirs.
# If $DocDir is 0 then create the filename $DOCFILE and return
# $anydata. If $anydata is 0 don't create a new file and return ''.
#--------------------------------------------------------------------------
sub OpenDoc
{
local($docdir, $name, *data) = @_;
local($anydata) = $data || ($data = scalar keys %data);
$DOCFILE = "$name.txt"; # global used in PrintList()
return $anydata unless $docdir; # and output will to current select()
local($htmlfile) = $name;
$htmlfile .= $Dos ? '.htm' : '.html';
# $Clean && do {
-e $DOCFILE && unlink($DOCFILE);
-e $htmlfile && unlink($htmlfile);
# };
return '' unless $anydata; # don't create new file w/ no data
## print STDERR ">>>$DOCFILE\n";
open(DOC, ">$DOCFILE") || do {
&Warn(qq~could not open "$DOCFILE" for output~, 'sys');
return '';
};
$DOCFILES++; # count files created
$DOCFILES{$DOCFILE} = $htmlfile; # keep a list of .txt files
select(DOC); # print's will default to DOC
print "file: $DOCFILE\n"; # indentify filename
print &Preamble; # print a file header
}
sub Preamble
{
$TimeStr = $TimeStr || &TimeStr('(local)');
join('',
$HeaderRoot ? "root: $HeaderRoot\n" : '',
$ServerHost ? "host: $ServerHost\n" : '',
"date: $TimeStr\n",
"Linklint version: $version\n",
"\n"
);
}
#--------------------------------------------------------------------------
# SiteSummary
#
# Prints the textual summary of what has happened.
#--------------------------------------------------------------------------
sub SiteSummary
{
%Hints && print "hint: ", join("\nhint: ", keys %Hints), "\n\n";
$FileList && print
"Linklint found ",
&Plural($FileList, "%d file%s"),
$DirList ? &Plural($DirList, " in %d director%y") : '',
$Parsed ? &Plural($Parsed, " and checked %d html file%s") : '',
".\n";
$CheckCase && $BadCase == 0 &&
print &Plural($BadCase, "There %w %n file%s with mismatched case.\n");
$CheckOrphan && $OrphList == 0 &&
print &Plural($OrphList, "There %w %n director%y with orphans.\n");
print &Plural($LostFile, "There %w %n missing file%s.");
print &Plural($ErrF, " %N file%s had broken links.\n");
print &Plural($ErrTot, "%N error%s, ");
print &Plural($WarnList, "%n warning%s.");
$Http || $Time && $Parsed && $Time > 4 &&
printf(" Parsed ~ %1.1f files/second.", $Parsed /$Time);
print "\n";
}
#--------------------------------------------------------------------------
# PrintDocDir(*SUMMARY, $docdir, $sumfile, $indexfile, $title)
#
# Prints complete documentation in $DocDir directory.
#--------------------------------------------------------------------------
sub PrintDocDir
{
local(*SUMMARY, $docdir, $sumfile, $indexfile, $logfile, $title) = @_;
$docdir && &PushDir($docdir) || return;
local($indexhtml) = $indexfile;
$indexhtml .= $Dos ? ".htm" : ".html";
$DOCFILES = 0;
%DOCFILES = ();
&Progress("\nwriting files to $Arg{'doc'}"); # abbreviated $DocDir
local($lastselect) = select; # save "std" output
&PrintFiles($docdir, 0, 0, $DocFlag); # print almost all doc files
local($dum) = '1'; # used to fool OpenDoc()
&OpenDoc($docdir, $sumfile, *dum) && do {
&SUMMARY; # text summary at top of file
print "\n";
&PrintFiles(@SumPrint); # list summary
};
&OpenDoc($docdir, $indexfile, *dum) && do {
printf("%12s: %s\n", "$sumfile.txt", 'summary of results');
$Arg{'out'} || printf("%12s: %s\n", "$logfile.txt", 'log of progress');
&PrintFiles('', 1, 2, $DocFlag); # list index to all files
};
close(DOC); # close the last one
select($lastselect); # restore "std" output
&Progress(&Plural($DOCFILES, "wrote %n txt file%s"));
$Arg{'textonly'} || do {
delete $DOCFILES{"$sumfile.txt"};
delete $DOCFILES{"$indexfile.txt"};
delete $DOCFILES{"dir.txt"};
foreach $txt (keys %DOCFILES) {
&HtmlDoc($txt, $DOCFILES{$txt}, *DefDir, *Action, $DocBase );
$Arg{'htmlonly'} && $txt !~ /^remote/ && unlink($txt);
};
&Progress(&Plural(scalar keys %DOCFILES, "wrote %n html file%s"));
&HtmlSummary("${indexfile}.txt", $indexhtml, $title, *DOCFILES) &&
&Progress("wrote index file $indexhtml");
$Arg{'htmlonly'} && unlink("${indexfile}.txt");
};
&PopDir;
}
#--------------------------------------------------------------------------
# HtmlDoc($in, $out, *map, *skip, $base)
#
# Reads txt file $in, writes html file $out, adding anchors
# to lines that start with "/" or "scheme:". Sets the base
# to $base if provided, maps links found in %map, does not
# add anchors to links found in *skip.
#--------------------------------------------------------------------------
sub HtmlDoc
{
local($in, $out, *map, *skip, $base) = @_;
local($title) = "Linklint - $out";
#---- Open files
open(IN, $in) || do {
&Warn(qq~\ncould not read back "$infile"~, 'sys');
return '';
};
### print STDERR ">> HTML >> $out\n";
open(OUT, ">$out") || do {
&Warn(qq~\ncould not open "$outfile" for output~, 'sys');
close(IN);
return '';
};
my $base_tag = $Arg{output_frames} ? "" : "";
#----- print html header
print OUT "\n$title\n\n";
print OUT $base_tag;
print OUT "\n\n\n";
#---- read/print text file header
$_ = ; # skip "file: filename.txt"
while () {
print OUT $_;
last unless /\S/;
}
#---- read/print out the list with anchor tags
local($file);
while() {
s/^(\s+)// && print OUT $1;
s/^(=>\s*)// && print OUT $1;
m#^(/|\w+:).*# || do { print OUT $_; next; };
s/\s+$//;
$file = $map{$_} || $_;
$skip{$file} && do { print OUT "$_\n"; next; };
$file =~ m#^/# && ($file = $base .$file);
print OUT qq~$_\n~;
}
close(IN);
print OUT @tab, "\n";
close(OUT);
return 1;
}
#--------------------------------------------------------------------------
# TimeStr($gmt, $time)
#
# Returns a string formated "weekday, month day year hh:mm:ss"
#--------------------------------------------------------------------------
sub TimeStr
{
local($gmt, $time) = @_;
defined $time || ($time = time);
local($sec, $min, $hour, $mday, $mon, $year, $wday ) =
($gmt =~ m/GMT/) ? gmtime($time) : localtime($time);
local(@mon) = ( 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
local(@wday) = ( 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' );
$year < 50 && ($year += 2000);
$year < 1900 && ($year += 1900);
sprintf("$wday[$wday], %02d $mon[$mon] $year %02d:%02d:%02d %s",
$mday, $hour, $min, $sec, $gmt);
}
#--------------------------------------------------------------------------
# HtmlSummary($infile, $outfile, $title, $docfiles)
#
# Creates a simple html summary file by reading back the linklint.txt
# file that was already created.
#--------------------------------------------------------------------------
sub HtmlSummary
{
local($infile, $outfile, $title, *docfiles) = @_;
local(%head);
open(IN, $infile) || do {
&Warn(qq~\ncould not read back "$infile"~, 'sys');
return '';
};
open(OUT,">$outfile") || do {
&Warn(qq~\ncould not open "$outfile" for output~, 'sys');
close(IN);
return '';
};
while () {
last unless /\S/;
/\s*(\S+):\s*(\S+.*\S+)\s*$/ && ($head{$1} = $2);
}
local($title2) = $title;
$head{'root'} && ($title2 .= "for $head{'root'}");
my $target = $Arg{output_frames} ? "" : "";
print OUT qq~\n
$title\n
$target
\n
$title2
\n
\n
$head{'date'}
Linklint version: $version
~;
local($file);
while() {
last unless /\S/;
s|(ERROR )|$1|;
s|^\s*(\S+):||;
$file = $docfiles{$1} || $1;
$file =~ s~[^/]+/~~;
print OUT " " x (13 - length($file));
print OUT "$file:", $_;
}
close(IN);
print OUT @tab, "\n\n\n";
close(OUT);
return 1;
}
#--------------------------------------------------------------------------
# Plural($cnt,$msg)
#
# Returns a pluralized version of $msg.
#
# %w -> was : were %d -> $cnt
# %s -> : s %n -> no : $cnt
# %y -> y : ies %N -> No : $cnt
# %es -> : es
#--------------------------------------------------------------------------
sub Plural
{
local($cnt,$_) = @_;
$cnt == 1 ? s/\%w/was/g : s/\%w/were/g; # %w -> 'was' or 'were'
$cnt == 1 ? s/\%s//g : s/\%s/s/g; # %s -> '' or 's'
$cnt == 1 ? s/\%y/y/g : s/\%y/ies/g; # %y -> 'y' or 'ies'
$cnt == 1 ? s/\%es//g : s/\%es/es/g; # %y -> 'y' or 'ies'
s/\%n/\%d/ && ($cnt = $cnt || 'no' ); # %n -> "no" or $cnt
s/\%N/\%d/ && ($cnt = $cnt || 'No' ); # %N -> "No" or $cnt
s/\%d/$cnt/; # %d -> $cnt
s/(\%\d+d)/sprintf($1,$cnt)/e; # %3d -> $cnt
return $_;
}
#--------------------------------------------------------------------------
# PrintList(*list, $header, $xref, $subhead)
#
# Print out keys (and values if $xref) of %list. Prepend "$DOCFILE: "
# to header if $DOCHEAD is set. Append "(cross referenced)" to header
# if $xref == 2. Only print header if $SUM is set.
#--------------------------------------------------------------------------
sub PrintList
{
local(*list, $header, $xref, $subhead) = @_;
$subhead = $subhead || "used in %d file%s:";
return unless %list;
local(@major) = sort keys %list;
local($headtext) = &Plural(scalar @major, $header);
$xref == 2 && ($headtext .= " (cross referenced)");
$DOCHEAD && ($headtext = sprintf("%13s: ", $DOCFILE) . $headtext);
$SUM && do { print "$headtext\n"; return; };
print "$Headline# $headtext\n$Headline";
foreach (@major) {
s/&cr;/\n/g;
print "$_\n";
$PrintAddenda{$_} && print "$PrintAddenda{$_}\n";
$xref && &PrintSubList($list{$_}, $subhead, 4);
}
print "\n" unless $xref;
}
#--------------------------------------------------------------------------
# PrintSubList($sublist, $subhead, $indent)
#
# Prints out all elements of $sublist split by "\n". Prints out the
# number of elements in pluralized $subhead.
#--------------------------------------------------------------------------
sub PrintSubList
{
local($sublist, $subhead, $indent) = @_;
$indent = " " x $indent;
$sublist =~ s/^\n+//;
$sublist || return;
(local(@items) = sort split(/\n+/,$sublist)) || return;
grep( s/&cr;/\n/g, @items);
print $indent , &Plural(scalar @items, $subhead), "\n", $indent;
print join("\n$indent", @items) , "\n\n";
}
#--------------------------------------------------------------------------
# PrintLISTS(*list, *heads, $xref)
#
# Split %list into sublists and then prints each sublist. The
# splitting is controlled by @heads. Each line of @heads must be in the
# form "$heading::$regexp" All keys of %list that match %regexp are
# printed out under the heading $heading. If regexp contains 'unknown'
# then all remaining items in %list are printed out under its $heading.
# If $SUM == 2 then a summary of all keys %list is printed using the
# first heading format which is otherwise ignored.
#--------------------------------------------------------------------------
sub PrintLISTS
{
local(*listname, *heads, $xref) = @_;
local(%sublist, @items, $heading, $regexp);
local(%list) = %listname;
foreach ( $SUM == 2 ? @heads[0 .. 0] : @heads[1 .. $#heads] ) {
($heading,$regexp) = split(/::/, $_);
(@items = $regexp =~ /unknown/ ? keys %list
: grep(/$regexp/i, keys %list)) || next;
%sublist = ();
foreach ( @items ) {
$sublist{$_} = $list{$_}; # transfer to %temp
delete $list{$_}; # and delete from %list
}
&PrintList(*sublist, $heading, $xref);
}
}
#--------------------------------------------------------------------------
# PrintUrl(*list, $header, $xref, $posthead, $subhead)
#
# Prints out URLs (and references if $xref) in %list.
#--------------------------------------------------------------------------
sub PrintUrl
{
local(*list, $header, $xref, $posthead, $subhead) = @_;
($list = $list || scalar keys %list) || return;
$header .= ':';
local(@items, %invert);
local($headtext) = &Plural($list, $header);
$DOCHEAD && ($headtext = sprintf("%13s: ", $DOCFILE) . $headtext);
$headtext .= " " . &Plural($list, $posthead);
$subhead = $subhead || "%d url%s:";
$xref == 2 && ($headtext .= " (cross referenced)");
$SUM == 2 && ((print "$headtext\n"), return);
&InvertKeys(*list, *invert);
$SUM || print "$Headline# $headtext\n$Headline";
foreach (sort keys %invert) {
@items = sort split(/\n/, $invert{$_} );
print &Plural(scalar @items, $SUM ? $header : $subhead), " $_\n";
$SUM && next;
&PrintSubUrl(*items, $xref);
}
print "\n" unless $SUM;
}
#--------------------------------------------------------------------------
# PrintSubUrl
#
# Prints out all elements of $sublist split by "\n". Prints out the
# number of elements in pluralized $subhead.
#--------------------------------------------------------------------------
sub PrintSubUrl
{
local(*items, $xref) = @_;
foreach ( @items ) {
print " ", $_;
&PrintUrlRedir($_);
print "\n";
($xref && defined $ExtLink{$_} ) || next;
&PrintSubList($ExtLink{$_}, "used in %d file%s:", 8);
}
print "\n" unless $xref && defined $ExtLink{$_};
}
#---------------------------------------------------------------------------
# PrintUrlRedir($url)
#
# Prints "linked list" of where $url was moved to due to 3XX status
# codes. Always returns if an infinite loop ( a -> b -> a ...)
# occurs.
#---------------------------------------------------------------------------
sub PrintUrlRedir
{
local($url) = @_;
local(%checked);
while ( $url = $UrlRedirect{$url} ) {
$checked{$url}++ && return;
print "\n => ", $url;
}
}
#---------------------------------------------------------------------------
# UrlSummary()
#
# Print Textual summary of checking remote url status.
#---------------------------------------------------------------------------
sub UrlSummary
{
$TotFail = $UrlFail;
$CheckedUrls && print
&Plural($CheckedUrls, "Linklink checked %d url%s:\n"),
&Plural($UrlOk," %d %w ok, "),
$TotFail, " failed",
$UrlMoved ? &Plural($UrlMoved, ". %N url%s moved") : '',
".\n";
$HostFail && print
&Plural($HostFail, " %n host%s failed:"),
&Plural($UrlRetry, " %N url%s could be retried.\n");
%ExtLink && print &Plural($UrlFailedF , "%N file%s had failed urls.\n");
$ErrF && $UrlFailF && print
&Plural($ErrF + $UrlFailedF,
"There were %n file%s with broken links.\n");
$CacheNet && print
&Plural($UrlMod," %N url%s %w modified since last reset.\n");
}
#---------------------------------------------------------------------------
# Abbrev($max, $str)
#
#---------------------------------------------------------------------------
sub Abbrev
{
local($max, $str) = @_;
length($str) > $max && ($str = substr($str, 0, $max - 4) . " ...");
$str;
}
#---------------------------------------------------------------------------
# LogFile($filename)
#
# Changes log file to filename for logging progress.
#---------------------------------------------------------------------------
sub LogFile
{
local($name) = @_;
$name || return;
$LogFile && $LogFile eq $name && return; # don't reopen same file.
select(STDERR);
$LogFile && close($LogFile);
$LogFile = $name;
open($LogFile, ">$LogFile") ||
&Error(qq~could not open file "$LogFile" for output~, 'sys');
select($LogFile);
}
###########################################################################
#
# Utilities
#
###########################################################################
#---------------------------------------------------------------------------
# $outcnt = InvertKeys(*in, *out)
#
# Assumes %in is filled with values like "file1\nfile2\n..."
# Fills %out with keys file1, file2, ... and each key has values
# of the keys from %in that refer to it.
#---------------------------------------------------------------------------
sub InvertKeys
{
local(*in, *out) = @_;
%in || return %out ? scalar keys %out : 0;
local(%temp);
foreach $in (keys %in) {
%temp = ();
grep( $temp{$_}++, split(/\n+/, $in{$in}));
foreach (keys %temp) {
/\S/ || next;
$out{$_} ? ($out{$_} .= "\n$in") : ($out{$_} = $in);
}
}
scalar keys %out;
}
#--------------------------------------------------------------------------
# ResolveAnch(*want, *found, *lost, $empty_ok)
#
# named anchors wanted: %want{link#frag} = "ref1 \n ref2 \n ..."
# named anchors found: %found{link#frag} = 1
# Fills *found and *lost as appropriate for found and lost named
# anchors. Works for named maps too.
#--------------------------------------------------------------------------
sub ResolveAnch
{
local(*want, *found, *lost, $empty_ok) = @_;
foreach ( keys %want) {
/^([^#]*)(#.*)/; # $1 will contain filename
$file = $1;
$anch = $2;
$empty_ok and length($anch) == 0 and next;
$Ignore && $url =~ /$Ignore/o && next; # ignore ignored files
$Skipped{$file} && next; # skip anchors in skipped files
$ref = $want{$_};
$Mapped{$file} && do {
$file = $Mapped{$file};
$Ignore && $url =~ /$Ignore/o && next; # ignore ignored files
$Skipped{$file} && next; # skip skipped files
$_ = "$file$anch";
};
$found{$_} ? ($found{$_} = $ref) : ($lost{$_} = $ref);
}
}
#--------------------------------------------------------------------------
# HashUnique(*hash)
#
# Assumes values in hash are "val1 \n val2 \n ..."
# Ensures that each val occurs at most once in each hash value.
#--------------------------------------------------------------------------
sub HashUnique
{
local(*hash) = @_;
local(%temp, $key, $val);
while ( ($key, $val) = each %hash) {
%temp = ();
grep($temp{$_}++, split(/\n+/, $val));
$hash{$key} = join("\n", keys %temp);
}
}
#--------------------------------------------------------------------------
# Warn(@msg)
#
# Registers this warning in %Warn. If $link is supplied we cross
# reference the warning to $link.
#--------------------------------------------------------------------------
sub Warn
{
local($msg, $link) = @_;
(!$link || $link eq 'sys') && do {
$WarnList{$msg} = "\n";
&Progress("WARNING: $msg");
$link && $! && print STDERR " System message: $!\n";
return;
};
&AppendList(*WarnList,$msg, $link);
}
#--------------------------------------------------------------------------
# WantNumber($val, $flag)
#--------------------------------------------------------------------------
sub WantNumber
{
local($val, $flag) = @_;
$val || return;
$val =~ /^\d+$/ && return;
&Error("$flag must be followed by an integer");
}
#--------------------------------------------------------------------------
# exit_with(@msg)
#--------------------------------------------------------------------------
sub exit_with { print @_; exit;}
#--------------------------------------------------------------------------
# Error(@msg)
# Print @msg and exit.
#--------------------------------------------------------------------------
sub Error
{
local($msg, $flag) = @_;
print STDERR "\n$prog error: $msg\n";
@_ > 1 && $flag eq 'sys' && $! && (print STDERR "\nSystem message: $!\n");
exit;
}
#--------------------------------------------------------------------------
# Progress(@msg)
#--------------------------------------------------------------------------
sub Progress
{
local($msg) = @_;
$LogProgress && print $msg, "\n";
$Quiet && return;
print STDERR &Abbrev(75, $msg), "\n";
}
#--------------------------------------------------------------------------
# AppendList(*list, $key, $value)
#
# Adds $value to $list{$key} separates values with "\n" as needed.
#--------------------------------------------------------------------------
sub AppendList
{
local(*list, $key, $value) = @_;
$list{$key} ? ( $list{$key} .= "\n$value" ) : ($list{$key} = $value);
}
#--------------------------------------------------------------------------
# PushDir($newdir)
#
# Pushes current directory onto a stack @DIRS and then
# chdir's to $newdir. We Assume that $newdir is a full path!
# Returns O if there is an error.
#--------------------------------------------------------------------------
sub PushDir
{
local($new) = @_;
push(@DIRS,$CWD);
return $CWD if $new eq $CWD;
chdir($new) || do {
&Warn(qq~(pushdir) could not chdir to "$new"~, 'sys');
return '';
};
return($CWD = $new);
}
#--------------------------------------------------------------------------
# PopDir
#
# Pops most recent directory off of stack @DIRS and
# changes $CWD and current directory accordingly.
#--------------------------------------------------------------------------
sub PopDir
{
local($new) = pop(@DIRS);
return $CWD if $new eq $CWD;
chdir($new) || do {
&Warn(qq~(popdir) could not chdir to "$new"~, 'sys');
return '';
};
$CWD = $new;
}
#--------------------------------------------------------------------------
# GetCwd
#
# Returns a string containing the current working directory
# "\" is changed to "/" for consistency if $DOS.
# Sets $CWD to the current working directory.
#--------------------------------------------------------------------------
sub GetCwd
{
local($_) = `$pwdprog`; # different prog's for Dos/Unix
$Dos && do {
s|\\|\/|g; # replace \ with /
s/^([a-zA-Z])://; # remove drive:
$DosDrive = $1; # save drive letter for dochtml printout
};
s/\n$//; # remove trailing \n
$CWD = $_;
}
#--------------------------------------------------------------------------
# Regular($exp, $flag)
#
#--------------------------------------------------------------------------
sub Regular
{
local($exp) = @_;
$exp =~ s#([^\w/])#\\$1#g;
$exp;
}
#--------------------------------------------------------------------------
# LinkSet($flag, *in)
#
# Fills $out with regular exppression made out that is the or'ed
# of the the specs in @in. Fills %out with all of the keys
# that were literal expresions.
#--------------------------------------------------------------------------
sub LinkSet
{
local($flag, *in) = @_;
%in = ( '/*', '1' ) if $in{'/*'}; # keep it simple
local($out) = join( '|', grep( $_ = &LinkSet1($_, $flag), keys %in));
$Arg{$flag} = $out;
$out;
}
#--------------------------------------------------------------------------
# LinkSet1($exp)
#
# If $exp does not contain ()[]^| or $ then it is converted to a
# literal expression. If this expression contains ? or * then these
# are converted to [^/]* and .* and the whole thing is anchored to the
# start and end. Otherwise check $exp to be a valid regular expression.
#--------------------------------------------------------------------------
sub LinkSet1
{
local($_, $flag) = @_;
s!([^\w\@#/])!\\$1!g; # protect special characters
s!\@!.*!g; # @ to .* (match any)
s!#/!#/?!g; # make / behind # optional
s!#![^/]*!g; # '#' to [^/]* (match any but /)
$_ = "^$_\$";
}
###########################################################################
#
# User Input Routines
#
###########################################################################
#--------------------------------------------------------------------------
# @linkset = ReadFile($file)
#
# Every infile that starts with "@" is read and its contents are
# are added to the end of the @infiles list. If an @file contains
# lines starting with - then the entire line is read in as commands.
#--------------------------------------------------------------------------
sub ReadFile
{
local($file) = @_;
local(@argv, @out);
local($lastarg, $lastflag, $arg);
$CheckedIn{$file}++ && next;
if ($file eq "STDIN") {
$file = \*STDIN;
}
elsif ($file) {
open($file, $file) || &Error(qq~could not open file-list "$file"~, 'sys');
}
else {
$file = \*STDIN;
}
while (<$file>) {
s/^#! ?// && do {print STDERR $_; next; }; # print comments
m/^#/ && next;
s/\s+$//; # trailing whitespace
s/^\s+//; # leading whitespace
s/^@@// && ( push(@HttpFiles, $_), next);
s/^@// && ( push(@out, &ReadFile($_)), next);
m/^-/ || (push(@out, split(/\s+/, $_)), next);
while( s/("([^"]*)"|(\S+))\s*//) {
$arg = $+;
$arg =~ /^-/ && (push(@argv, $lastflag = $lastarg = $arg), next);
$lastflag && $lastarg !~ /^-/ && $lastflag =~ /-($HashOpts)/o &&
push(@argv, $lastflag);
push(@argv, $lastarg = $arg);
}
}
close($file);
@argv && &ReadArgs(@argv);
@out;
}
#--------------------------------------------------------------------------
# ReadHttp($file)
#
# Reads $file and returns every "http://..." it can find.
# returns the list of links in an array.
#--------------------------------------------------------------------------
sub ReadHttp
{
local($file) = @_;
local(@out);
$file || do {
$Arg{'doc'} || &Error("@@ must be preceded by -doc linkdoc");
$file = "$Arg{'doc'}/remoteX.txt";
};
$CheckedIn{$file}++ && return;
open($file, $file) || &Error(qq~could not open http-list "$file"~, 'sys');
while (<$file>) {
/^file: remoteX.txt/ && $. == 1 && return &ReadBack($file);
while ( s#(http://[^\s"><']+)##i) { push(@out, $1); }
}
close($file);
@out;
}
#--------------------------------------------------------------------------
# ReadBack($file)
#
# Reads in $file as if it were the remoteX.txt file generated by
# Linklint. %ExtLink if filled with the cross references found
# in the file. Returns a list of all urls found.
#--------------------------------------------------------------------------
sub ReadBack
{
local($file) = @_;
local($url, @out);
while (<$file>) {
/^#/ && ($url = '', next); # new section
s/\s+$//; # trailing \n
/^http:/ && (push(@out, $url = $_), next); # a url to check
s#^ ## || next; # sublist indent
m#^/# && &AppendList(*ExtLink, $url, $_); # local link
}
close($file);
@out;
}
#--------------------------------------------------------------------------
# SetHash('name', $key, $value)
#
# Sets $name{$key} = $value.
#--------------------------------------------------------------------------
sub SetHash
{
local(*hash, $key, $val) = @_;
$hash{$key} = $val;
}
#--------------------------------------------------------------------------
# ReadArgs(@args)
#
# Reads arguments from @args (all start with "-") returns the
# remainder of @args. We first check for full flags and options.
# If these don't match exactly we go through the argument looking
# for short flags and options 'globbed' together. Flags set
# $Arg{'X'} to 1. For short flags X is the flag, for full flags X
# is the first character. Short options set $Arg{'X'} to the next
# argument. Full options set $X to the next argument where X
# is the value from %fullopts. ZZZ Has been modified.
#--------------------------------------------------------------------------
sub ReadArgs
{
local($name, @out);
while ( @_ && ($_ = shift)) {
s/^@@// && ( push(@HttpFiles, $_), next);
s/^@// && ( push(@out, &ReadFile($_)), next);
(m#^/# || m#\.html?$#i || s#^http://#http://#i ) &&
(push(@out, $_), next);
s/^-// || &Error( qq~at "$_"~ .
qq~\nexpected: "-flag" or "/linkset" or "http: ..."\n~ . $ErrUsage);
if ( /^($MiscFlags)$/o ) {
$Arg{$1}++;
}
elsif (/^($FullOpts)$/o) {
(@_ < 1 || $_[0] =~/^-/) &&
&Error("expected parameter after -$_\n" . $ErrUsage);
$Arg{$_} = shift;
}
elsif (/^($HashOpts)$/o) {
(@_ < 1 || $_[0] =~/^-/) &&
&Error("expected parameter after -$_\n" . $ErrUsage);
($name = $_) =~ tr/a-z/A-Z/;
&SetHash( $name , shift, 1);
}
elsif (/^password$/) {
(@_ < 2 || $_[0] =~ /^-/ || $_[1] =~ /^-/ ) &&
&Error("expected 2 parameters after -$_\n" . $ErrUsage);
$_[1] =~ /:/ ||
&Error(qq~expected username:password at "$_[1]"\n~ .
$ErrUsage);
$PASSWORD{$_[0]} = $_[1];
shift; shift;
}
elsif (s/^db//) {
while($_) {
s/^([\d])// ||
&Error("expected a digit after -db\n" . $ErrUsage);
$DB{$1}++;
}
}
else {
&Error("unknown flag -$_\n" . $ErrUsage);
}
}
return (@out, @_);
}
sub HttpInit
{
local($arg, $db, $pw, $headers, $agent) = @_;
defined &Http'Init || do {
unshift(@INC, $HOME);
require "linkhttp.pl";
};
&Http'Init($arg, $db, $pw, $headers, $agent);
}
#==========================================================================
# End of linklint
#==========================================================================
###########################################################################
#
# Http Package
#
# Init(*arg, *db, *pw, *headers, $agent);
# 'timeout' abort request after timeout seconds
# 'delay' delay between requests to same host
# 'netset' resets last modified state in cache
# 'redirect' search for redirects in files
# 'ignore'
# 'VERSION'
# 'DOS'
#
# OpenBot($botfile)
#
# OpenCache($cachefile)
#
# FlushCache(*validurls)
#
# UrlsFromCache($ok, $retry, $fail)
# Returns @urls with urls from cache depending on status in cache.
#
# CheckURLS(*urls)
# Check all http:// urls in @urls and returns %UrlStatus
# filled with urls and status code.
#
# StatusMsg(*status, *ok, *fail, *warn)
# Fills %ok, %fail %warn, with urls and error messages
# from *status.
#
# OtherStatus(*urlmod, *urlmoved, *hostfail, *redirect)
# Fills hashes with modified, moved, and host fail messeges
# Fills *redirect with redirected urls and destinations.
#
# WriteCaches()
#
###########################################################################
package Http;
use Socket;
#--------------------------------------------------------------------------
# Init(*arg, *db, *pw, *headers, $agent)
#
# Sets up global variables. Can be called more than once.
#--------------------------------------------------------------------------
sub Init
{
local(*arg, *db, *pw, *headers, $agent) = @_;
%Arg = %arg;
%DB = %db;
@Base64 = ('A'..'Z', 'a'..'z', '0'..'9', '+', '/');
foreach(keys %pw) {
$PassWord{$_} = &Base64Encode($pw{$_});
}
$TimeOut = $Arg{'DOS'} ? 0 : $Arg{'timeout'} || 0;
$Delay = $Arg{'delay'};
$ResetCache = $Arg{'netset'};
$UserAgent = "LinkLint-$agent";
$Arg{'VERSION'} && ($UserAgent .= "/$Arg{'VERSION'}");
$Proxy = $Arg{'proxy'} || '';
$Proxy_Port = ($Proxy and $Proxy =~ s/:(\d*)$//) ? $1 : '';
($DB{7} || $DB{8}) && do {
print "TimeOut: $TimeOut\n";
print "User-Agent: $UserAgent\n";
$Proxy && print "Proxy: $Proxy\n";
$Proxy_Port && print "Proxy Port: $Proxy_Port\n";
};
$TimeOut && do {
$SIG{'ALRM'} = *AlarmHandler;
$SIG{'INT'} = *IntHandler;
};
$Init++ && return;
$CRLF = $Arg{'DOS'} ? "\n" : pack("cc", 13, 10);
for my $header_line (keys %headers) {
my ($name, $value) = $header_line =~ m/^([\w\-]+):\s*(.*)/;
$name && $value or do {
&main'Warn("Could not parse -http_header $header_line");
next;
};
$name = join "-", map ucfirst, map lc, split /-/, $name;
$USER_REQ_HEAD{$name} = $value;
$USER_HEADERS .= "${CRLF}$name: $value";
};
$StatType = "url last-modified cache";
$BotType = "robot exclusion cache";
$NOW = time;
%FlagOk = (
200, 'ok (200)',
201, 'ok created (201)',
202, 'ok accepted (202)',
304, 'ok not modified (304)',
-2000, 'ok parsed html',
-2001, 'ok skipped',
-3005, 'ok last-modified date unchanged',
-3006, 'ok did not compute checksum',
-3007, 'ok checksum matched',
);
%FlagNotMod = (
304, 1,
-3005, 1,
-3006, 1,
-3007, 1,
);
%FlagMoved = (
301, 'moved permanently (301)',
302, 'moved temporarily (302)',
-3003, 'redirected',
);
%FlagRetry = (
-1, 'could not find ip address',
-2, 'could not open socket',
-3, 'could not bind socket',
-4, 'could not connect to host',
-5, 'timed out waiting for data',
-8, 'malformed status line',
-12, 'timed out before anything could happen',
-14, 'timed out connecting to host',
-15, 'timed out waiting for data',
-16, 'timed out reading status',
-17, 'timed out reading header',
-18, 'timed out reading data',
-19, 'timed out getting host ip address',
502, 'server temporarily overloaded (502)',
503, 'gateway timeout (503)',
);
%FlagWarn = (
-6, 'not an http link',
-7, 'no status. Will try GET method',
-10, 'Disallowed by robots.txt',
-11, 'infinite redirect loop',
401, 'access not authorized (401)',
-4000, 'moved to non-local server',
-4010, 'invalid username/password (401)',
-4020, 'unknown authorization scheme (401)',
-5000, 'user interrupt',
-6000, 'unknown internal error',
);
%FlagFail = (
204, 'had no content (204)',
301, 'moved permanently, no new URL (301)',
302, 'moved temporarily, no new URL (302)',
400, 'bad request (400)',
403, 'access forbidden (403)',
404, 'not found (404)',
500, 'internal server error (500)',
501, 'service not implemented on server (501)',
);
%FlagBad = (%FlagRetry, %FlagWarn, %FlagFail);
@FlagDebug = (
keys %FlagOk, keys %FlagMoved, keys %FlagRetry, keys %FlagFail,
keys %FlagWarn,
);
}
#--------------------------------------------------------------------------
# OpenBot($botfile)
#
# Reads cache of robot exclusion info from $botfile filling %BotExclude.
# Must be run after Init.
#--------------------------------------------------------------------------
sub OpenBot
{
local($botfile) = @_;
&ReadCache($botfile, $BotType, *BotExclude);
}
#--------------------------------------------------------------------------
# OpenCache($cachefile)
#
# Reads status/last-modified cache from $cachefile int %StatCache
#--------------------------------------------------------------------------
sub OpenCache
{
local($statfile) = @_;
&ReadCache($statfile, $StatType, *StatCache);
}
#--------------------------------------------------------------------------
# FlushCache(@valid)
#
# Removes all entrys in StatCache that do not also occur in *valid
#--------------------------------------------------------------------------
sub FlushCache
{
@_ || do {
&main'Warn("Won't flush entire cache.");
return;
};
local(%valid);
grep( $valid{$_}++, @_);
local(@delete) = grep( !$valid{$_}, keys %StatCache);
foreach( @delete) {
delete $StatCache{$_};
}
local($cnt) = scalar @delete;
&main'Progress("Deleted $cnt entries from cache.");
@delete && $TaintCache{$StatType}++;
}
#--------------------------------------------------------------------------
# CheckURLS(@urls)
#
# Checks all http links in @urls
# Returns hash of urls and status codes.
#--------------------------------------------------------------------------
sub CheckURLS
{
local($flag, %http);
grep(s#^http://#http://#i && $http{$_}++, @_);
local(%checked);
&main'Progress(
&main'Plural(scalar keys %http, "\nchecking %d url%s ...\n"));
foreach $url (sort keys %http) {
next unless $url =~ m#^http://#i;
$Arg{'ignore'} && $url =~ m/$Arg{'ignore'}/o && next;
next if $checked{$url}++;
$flag = &CheckUrl($url, 0);
$flag = &UrlMoved($flag, $url);
$UrlStatus{$url} = $flag;
if ($Arg{concise_url}) {
$FlagBad{$flag} and do {
&main'Progress($url);
&main'Progress(" " . &ErrorMsg($flag));
};
}
else {
&main'Progress(" " . &ErrorMsg($flag) );
}
}
%UrlStatus;
}
#--------------------------------------------------------------------------
# $flag = UrlMoved($flag, $url)
#
# Process 3XX status. Recheck $url given back in Location field
# of HEADER. Continue until
# a) non-3XX status, b) infinite loop c) already checked.
#--------------------------------------------------------------------------
sub UrlMoved
{
local($flag, $url) = @_;
local(%checked, $next);
while ( $FlagMoved{$flag} ) {
$checked{$url}++ && return -11; # infinite loop
($next = $HEADER{'location'}) || return $flag; # this is an error
$UrlMoved{$url} = $FlagMoved{$flag};
$Redirect{$url} = $next;
$UrlStatus{$next} && return $UrlStatus{$next};
$flag = &CheckUrl($url = $next, 1);
}
return $flag;
}
#--------------------------------------------------------------------------
# Parse($host, $link, $referer, *list, *anchlist, *wantanchor)
#
#
#--------------------------------------------------------------------------
sub Parse
{
local($thishost, $oldlink, $REFERER, @param) = @_;
local($port) = $thishost =~ s/:(\d+)$// ? $1 : 80;
local($host) = $thishost;
local($scheme);
local($LINK) = $oldlink;
local($url) = "http://$thishost:$port$LINK"; # for warning messages
# $HostError{$host} && return ($HostError{$host}, $LINK);
local(%checked);
($flag = &Disallowed($url, 0.5)) && return ($flag, $LINK);
$flag = &Request($host, $port, $LINK, 'GET', *GetParse, @param);
while ( $FlagMoved{$flag} ) {
$checked{$LINK}++ && return (-11, $LINK); # infinite loop
($url = $HEADER{'location'}) || return ($flag, $LINK);
($scheme, $host, $port, $LINK) = &SplitUrl($url);
($host ne $thishost) && return (-4000, $url); # non-local server
&main'WasCached($LINK, $REFERER) && return (0, $LINK);
$flag = &Request($host, $port, $LINK, 'GET', *GetParse, @param);
}
return($flag, $LINK);
}
#--------------------------------------------------------------------------
# $flag = CheckUrl($url, $recheck)
#
# Returns status of a URL. Uses the robots.txt protocol.
# If $Arg{'redirect'} uses "GET" with html files otherwise
# tries a "HEAD" first and if that fails tries "GET".
#--------------------------------------------------------------------------
sub CheckUrl
{
local($url, $recheck) = @_;
local($scheme, $host, $port, $path) = &SplitUrlQ($url);
return -6 if $scheme ne "http";
$REQHEAD{'Host'} = $host;
if ($Arg{concise_url}) {
}
elsif ($recheck) {
&main'Progress(" moved");
&main'Progress(" $host$path");
}
else {
&main'Progress("$host$path");
}
$OpenedCache{$StatType} && ! $recheck && return &CheckModified($url);
return $Arg{'redirect'} ?
&Request($host, $port, $path, 'GET', "GetRedirect", $url)
: &Request($host, $port, $path, "GET" );
}
#--------------------------------------------------------------------------
# CheckModified($url)
#
# Outer wrapper to see if $url has been modified.
# Always update status in cache. Always update cache for new entries.
# Update time, last-mod, checksum if new entry or reset.
#--------------------------------------------------------------------------
sub CheckModified
{
local($url) = @_;
local($flag);
local($_, $time, $mod, $csum) = $StatCache{$url} ?
split(/\s+/, $StatCache{$url}) : ('0', '0', '0', '0');
local($nmod, $ncsum) = ($mod, $csum);
$TIMESTR = &main'TimeStr('GMT', $time); # for http header
if ( $mod ne '0') { # only check last-mod date
$flag = &Request($host, $port, $path, "GET" );
$FlagOk{$flag} && do {
if ($HEADER{'last-modified'}) {
($nmod = $HEADER{'last-modified'}) =~ tr/ /_/;
$flag = -3005 if ($nmod eq $mod);
}
else { $mod = $nmod = '0'; }
};
}
else {
$REQHEAD{'if-Modified-Since'} = $TIMESTR;
$flag = &Request($host, $port, $path, 'GET', "GetModified");
}
$csum = -1 if $flag == 304; # -1: server obeys "if-mod"
$FlagNotMod{$flag} || !$FlagOk{$flag} ||
($UrlMod{$url} = "modified since " . &main'TimeStr('(local)', $time));
#---- update cache if -reset or 1st time we get something new
$FlagOk{$flag} && do {
$time = $NOW if $ResetCache || $time eq '0';
$csum = $ncsum if $ResetCache || $csum eq '0';
$mod = $nmod if $ResetCache || $mod eq '0';
};
local($temp) = join(" ", $flag, $time, $mod, $csum); # create new entry
#---- update entry in cache if needed
(!$StatCache{$url} || $StatCache{$url} ne $temp) && do {
$StatCache{$url} = $temp;
$TaintCache{$StatType}++;
};
$flag;
}
#--------------------------------------------------------------------------
# GetModified($flag, *S)
#
# Passed to request4(). Only get here if file was modified or
# "If-Modified-Since" was ignored. Check last-mod date 1st.
# then check checksum only if they ask and if the $time was > 0.
# If $csum == -1 then don't bother with checksum.
#--------------------------------------------------------------------------
sub GetModified
{
local($flag, *S) = @_;
$HEADER{'last-modified'} && do { # use this info
($nmod = $HEADER{'last-modified'}) =~ tr/ /_/;
return $flag if $mod ne '0' && ($nmod ne $mod); # modified
return -3005; # not modified
};
$csum == -1 && return $flag; # modified: obeyed "if-mod" before
return -3006 unless $Arg{'checksum'} && $time != 0; # don't checksum
&main'Progress(" computing checksum");
$ncsum = 0;
while () { $ncsum += unpack("%32C*", $_); } # compute csum
return $flag if $csum ne '0' && ($ncsum != $csum); # modified
return -3007; # not modified
}
#--------------------------------------------------------------------------
# UrlsFromCache($ok, $retry, $fail)
#
# Returns @urls with urls from the cache depending on the last
# status of the url in the cache.
#--------------------------------------------------------------------------
sub UrlsFromCache
{
local($ok, $retry, $fail) = @_;
local(@urls);
$OpenedCache{$StatType} || &main'Warn("No url cache to read from.");
local($url, $cache, $flag);
while( ($url, $cache) = each %StatCache ) {
($flag) = split(" ", $cache);
push(@urls, $url) if
($fail && $FlagWarn{$flag} ) ||
($fail && $FlagFail{$flag} ) ||
($ok && $FlagOk{$flag} ) ||
($retry && $FlagRetry{$flag} );
}
@urls;
}
#--------------------------------------------------------------------------
# Recheck(@urls)
#
# Returns only those urls that need to be retried.
#--------------------------------------------------------------------------
sub Recheck
{
local(%retry);
grep( $retry{$_}++, &UrlsFromCache(0, 1, 0));
grep( $retry{$_}, @_);
}
#--------------------------------------------------------------------------
# $flag = Disallowed($url)
#
# Checks robots.txt file for $url. Results are cached for each host.
# Returns:
# -10 if access is excluded by robots.txt
# 0 if access is allowed
# < 0 if < 0 (non-http) error occured
#--------------------------------------------------------------------------
sub Disallowed
{
local($url, $expire) = @_;
local($scheme, $host, $port, $path) = &SplitUrl($url);
local($flag);
$BotExclude{$host} && do {
local($time, $xpath) = split(/\s+/, $BotExclude{$host});
local($secs) = 60 * 60 * 24 * ($expire || 30);
$time + $secs >= $NOW && do {
$xpath eq 'ok' && return 0;
return ($path =~ m/^$xpath/) ? -10 : 0;
};
};
&main'Progress(" checking robots.txt for $host");
$flag = &Request($host, $port, "/robots.txt", "GET", "GetText", 100);
return $flag if $FlagRetry{$flag};
$BotExclude{$host} = time . " ok"; # default value
$TaintCache{$BotType}++; # need to write a new file
return 0 unless $FlagOk{$flag};
$_ = join("", @DATA);
s/\r\n?/\n/g; # end-of-line = \r | \n | \r\n
@DATA = split(/\n/, $_);
local(@agents, @disallow);
push(@DATA, " "); # ensure last group gets proccessed
foreach (@DATA) {
next if /^\s*#/;
s/\s+$//;
if ( /^$/ ) {
if (@disallow && @agents) {
$_ = join(" ", @disallow); # prepare for use as regexp
s#([^\w\s/])#\\$1#g; # literal search (pretty)
s/\s+/\|/g;
$BotExclude{$host} = "$NOW $_";
last if grep(/linklint/i, @agents);
}
@agents = @disallow = ();
next;
}
s/\s*#.*$//; # trailing comments
if ( m/^\s*(User.?Agent|Robot)s?\s*:\s+(\S+.*\S?)\s*$/i) {
push(@agents, $2);
}
elsif ( m/^\s*Disallow\s*:\s+(\S+.*\S?)\s*$/i) {
next unless grep(/(linklint|\*)/i, @agents);
push(@disallow, $1);
}
}
return &Disallowed(@_); # only recurse once. Relies on BotExclude{host}
}
#--------------------------------------------------------------------------
# GetParse($flag, *S, $link, *newlinks, *Anchor, *wantanch);
#
# Parse html via remote http connection.
#--------------------------------------------------------------------------
sub GetParse
{
local($flag) = shift;
local($handle) = shift;
&main'AppendList(*main'FileList, $LINK, $REFERER);
# &main'CacheDir($LINK);
$HEADER{'content-type'} =~ m#^text/html#i || return $flag;
&main'StopRecursion($LINK, $REFERER) && return -2001;
&main'Progress("Checking $LINK");
&main'ParseHtml($handle, $LINK, @_);
return -2000; # parsed the file
}
#--------------------------------------------------------------------------
# GetRedirect($flag, 'S', $url)
#
# Passed to request4() by CheckUrl() to parse for redirects in header.
#--------------------------------------------------------------------------
sub GetRedirect
{
local($flag) = shift;
$HEADER{'content-type'} =~ m#^text/html#i || return $flag;
local($redir) = &main'ParseRedirect(@_);
$redir || return $flag;
$HEADER{'location'} = $redir;
return -3003;
}
#--------------------------------------------------------------------------
# GetText($flag, *S, $lines)
#
# Passed to request4() to read $lines of text into @DATA.
# For now @DATA is a global.
#--------------------------------------------------------------------------
sub GetText
{
local($flag, *S, $lines) = @_;
$HEADER{'content-type'} =~ /^text/ || return $flag;
while ( ) { # read $lines into @DATA
push(@DATA, $_);
$lines && (--$lines || last);
}
$flag;
}
#--------------------------------------------------------------------------
# $flag = Request($host, $port, $path, $method, *getmethod, @params)
#
# Handles host errors. Flags bad hosts. Caches host errors.
# Calls Request2(). Will retry if more than one IP address is given
# by gethostbyname() and we get StatRetry errors.
#
# Use subroutine getmethod($flag, 'S', @params) if given
# to read data after the header. I don't have a great method for
# sending data back at the moment. Use globals for now.
#--------------------------------------------------------------------------
sub Request
{
my ($host, $port, $path, @other) = @_;
my $flag;
$REQHEAD{Host} = $host;
if ($Proxy) {
my $v_url = "http://$host";
$port and $v_url .= ":$port";
$v_url .= $path;
$flag = Request2($Proxy, $Proxy_Port, $v_url, @other);
}
else {
$flag = &Request2(@_);
}
%REQHEAD = ();
return $flag;
}
sub Request2
{
local($_, $flag, $realm, $pw, $auth);
$flag = &Request3(@_);
$flag == 401 || return $flag;
($auth = $HEADER{'www-authenticate'}) || do {
&main'Warn(qq~missing authentication~, $url);
return -4020;
};
$auth =~ m/\s*basic\s+realm\s*=\s*"([^"]*)"/i || do {
&main'Warn(qq~unknown authorization scheme: $auth~, $url);
return -4020;
};
$realm = $1;
if ( $pw = $PassWord{$realm} || $PassWord{'DEFAULT'} ) {
$REQHEAD{'Authorization'} = "Basic $pw";
$flag = &Request3(@_);
$flag != 401 && return $flag;
&main'Warn(qq~invalid password for "$realm"~);
return -4010;
}
else {
&main'Warn(qq~need password for "$realm"~);
return $flag;
}
}
sub Request3
{
local($host) = shift;
local($flag) = &Request4($host, @_);
return $flag unless $FlagRetry{$flag};
$IpAddr2{$host} || return &HostError($host, $flag);
#----- try alternate ip addresses
foreach (split(/\n/, $IpAddr2{$host})) {
&main'Progress("Warning: $host $IpAddr{$host}");
&main'Progress(" Error: $FlagRetry{$flag}");
&main'Progress(" checking server $_");
$flag = &Request4($_, @_);
next if $FlagRetry{$flag};
$IpAddr{$host} = $_; # save good one as the default
return $flag;
}
&HostError($host, $flag); # all servers for this host are down
}
#--------------------------------------------------------------------------
# HostError($host, $flag)
#
# Fills %HostError with $flag, fills %HostFail with error message.
# Returns $flag.
#--------------------------------------------------------------------------
sub HostError
{
local($host, $flag) = @_;
$HostFail{$host} = &ErrorMsg($flag);
$HostError{$host} = $flag;
}
#--------------------------------------------------------------------------
# $flag = Request4($host, $port, $path, $method, 'getmethod', @params)
#
# Fills %HEADER with header info,
# Uses globals set by Init().
# $flag is error (or success) flag see %Httpxxx for details.
# Will use getmethod($flag, 'S', @params) to read data.
#--------------------------------------------------------------------------
sub Request4
{
local($host, $port, $path, $method, $getmethod, @params) = @_;
local($request, $ipaddr, $flag);
$port = $port || 80;
%HEADER = (); # global %HEADER holds http header info.
$DB{9} && do {
# $HEADER{'location'} = 'http://dum/dum';
return $flag = $FlagDebug[ int (rand(@FlagDebug)) ];
};
(($ipaddr,$flag) = &GetIpAddress($host));
$flag && return $flag;
$Delay && sleep($Delay);
$DB{7} && print
"\n$method http://$host$path\n",
"host ip: $IpAddr{$host}\n";
$request = "$method $path HTTP/1.0";
$USER_HEADERS and $request .= $USER_HEADERS;
$REQHEAD{"User-Agent"} = $UserAgent;
for my $name (sort keys %REQHEAD) {
$USER_REQ_HEAD{$name} and next;
$request .= "${CRLF}$name: $REQHEAD{$name}";
}
$ALARMFLAG = -12;
$@ = '';
$TimeOut && alarm($TimeOut);
$SOCKETOPEN = 0;
eval {
$flag = &FragileRequest($ipaddr, $request, $getmethod || \NUL, @params);
};
$TimeOut && alarm(0);
$SOCKETOPEN && close(S);
$SOCKETOPEN = 0;
$@ || return $flag;
$@ =~ /^timeout/ && return $ALARMFLAG;
$@ =~ /^user interrupt/ || return -6000;
print STDERR "\nUser Interrupt.\n",
"Interrupt again to abort or wait 2 seconds for linklint to resume\n";
sleep(2);
return -5000;
}
#--------------------------------------------------------------------------
# FragileRequest($ipaddr, $request, *getmethod, @params)
#
# Actually sends $request, and reads status, header and data from socket.
# Should be called from within an eval() to implement timeout.
#--------------------------------------------------------------------------
sub FragileRequest
{
local($ipaddr, $request, *getmethod, @params) = @_;
my $iaddr = inet_aton($ipaddr);
my $paddr = sockaddr_in($port, $iaddr);
my $proto = getprotobyname('tcp');
socket(S, PF_INET, SOCK_STREAM, $proto) or
return -2;
$SOCKETOPEN = 1;
$ALARMFLAG = -14; # "connecting to host"
$DB{4} && &main'Progress(" Connecting");
connect(S, $paddr) || return -4; # -4: could not connect
$DB{4} && &main'Progress(" Connect successful");
$ALARMFLAG = -15; # "waiting for data";
local($lastsel) = select(S); $| = 1; select($lastsel);
$DB{8} && print "\n$request\n\n";
print S "$request$CRLF$CRLF";
# $TimeOut && do {
# local($rin) = '';
# vec($rin, fileno(S), 1 ) = 1;
# select($rin, undef, undef, $TimeOut ) || return -5;
# $ALARMFLAG = -16; # "reading status"
# };
$_ = ; # read status line
$_ || return -7; # -7: no status (will try GET)
$TimeOut && alarm($TimeOut);
s/\s*$//;
$flag = /^\s*\S+\s+(\d+)/ ? $1 : -8; # -8: Malformed status line
($DB{7} || $DB{8}) && print "$_\n";
$flag == -8 && return $flag;
$ALARMFLAG = -17; # "reading header";
local($name);
while ( ) { # put header info into %HEADER
s/\s*$//;
$DB{8} && print "$_\n";
($DB{7} && $DB{8}) && next;
last unless m/\w/;
next unless m/(\S+):\s+(\S*.*\S*)\s*$/;
($name = $1) =~ tr/A-Z/a-z/;
$HEADER{$name} = $2;
}
$flag == 200 && @_ > 2 && defined &getmethod && do {
$ALARMFLAG = -18; # "reading data"
return &getmethod($flag, *S, @params);
};
return $flag;
}
sub AlarmHandler
{
die "timeout";
}
sub IntHandler
{
die "user interrupt";
}
#--------------------------------------------------------------------------
# GetIpAddress($host)
#
# Returns UNpacked IP address for host. Caches the address in
# $IpAddr{$host}, caches alternate IP addresses in $IpAddr2{$host}.
#--------------------------------------------------------------------------
sub GetIpAddress
{
local($host) = @_;
local($_, @addrlist);
$host =~ m/(\d+)\.(\d+)\.(\d+)\.(\d+)/ &&
($IpAddr{$host} = $host);
$IpAddr{$host} && return ($IpAddr{$host}, 0); # use cached ip address
$TimeOut && alarm($TimeOut);
eval('($_,$_,$_,$_, @addrlist) = gethostbyname($host)');
$TimeOut && alarm(0);
$@ && $@ =~ /^timeout/ && return (0, -19);
@addrlist || return (0, -1); # could not find host
grep($_ = join(".", unpack("C4", $_) ), @addrlist);
$IpAddr{$host} = shift @addrlist; # 1st one is default
$IpAddr2{$host} = join("\n", @addrlist); # save others just in case
return ($IpAddr{$host}, 0);
}
#--------------------------------------------------------------------------
# SplitUrl($url)
#
# Split the given URL into its component parts according to HTTP rules.
# returns ($scheme, $host, $port, $path, $query, $frag)
#--------------------------------------------------------------------------
sub SplitUrl
{
local($_) = $_[0];
local($scheme) = s#^(\w+):## ? $1 : '';
local($host) = s#^//([^/]*)## ? $1 : '';
local($port) = $host =~ s/:(\d*)$// ? $1 : '';
local($query) = s/\?(.*)$// ? $1 : '';
local($frag) = s/#([^#]*)$// ? $1 : '';
$scheme =~ tr/A-Z/a-z/;
$_ = $_ || '/';
return ($scheme, $host, $port, $_, $query, $frag);
}
#--------------------------------------------------------------------------
# SplitUrl($url)
#
# Split the given URL into its component parts according to HTTP rules.
# returns ($scheme, $host, $port, $path, $query, $frag)
#--------------------------------------------------------------------------
sub SplitUrlQ
{
local($scheme, $host, $port, $path, $query) = &SplitUrl(@_);
$query && ( $path .= "?" . $query);
return ($scheme, $host, $port, $path);
}
#--------------------------------------------------------------------------
# StatusMsg(*all, *ok, *fail, *warn)
#
# Fills %ok, %fail, %retry with urls and error MESSAGES from
# urls and error FLAGS in %all.
#--------------------------------------------------------------------------
sub StatusMsg
{
local(*all, *ok, *fail, *warn) = @_;
while ( ($url, $flag) = each %all) {
$msg = &ErrorMsg($flag);
$FlagOk{$flag} && ($ok{$url} = $msg, next);
$FlagWarn{$flag} && ($warn{$url} = $msg, next);
$fail{$url} = $msg;
}
}
sub RetryCount
{
local(*flags) = @_;
scalar grep($FlagRetry{$_}, values %flags);
}
#--------------------------------------------------------------------------
# ErrorMsg($flag)
#
# Returns the error message associated with flag.
#--------------------------------------------------------------------------
sub ErrorMsg
{
local($flag) = @_;
$DB{6} || ($FlagOk{$flag} && return 'ok');
$FlagOk{$flag} ||
$FlagFail{$flag} ||
$FlagWarn{$flag} ||
$FlagRetry{$flag} ||
"unknown error ($flag)";
}
#--------------------------------------------------------------------------
# OtherStatus(*urlmod, *hostfail, *urlmoved, *redirect)
#
# Fills hashes with modified, moved, and host fail messeges
# Fills *redirect with redirected urls and destinations.
#--------------------------------------------------------------------------
sub OtherStatus
{
local(*urlmod, *hostfail, *urlmoved, *redirect) = @_;
%urlmod = %UrlMod;
%urlmoved = %UrlMoved;
%hostfail = %HostFail;
%redirect = %Redirect;
}
#--------------------------------------------------------------------------
# ReadCache($file, $type, *hash)
#
# Reads $file, looking for key val1 on each line.
# Fills hash{key} = val1. Skips entries that have expired.
# Sets $OpenedCache{$type} to $file for writing later.
# Also used to only read the cache file once.
#--------------------------------------------------------------------------
sub ReadCache
{
local($file, $type, *hash) = @_;
$OpenedCache{$type} && return;
$OpenedCache{$type} = $file;
open(CACHE, $file) || return;
($DB{7} || $DB{8}) && &main'Progress(qq~reading $type from "$file"~);
foreach () {
/^#/ && next;
/^(\S+)\s+(\S+)\s+(\S.*\S)\s*$/ || next;
$hash{$1} = "$2 $3";
}
close(CACHE);
}
#--------------------------------------------------------------------------
# WriteCaches()
#--------------------------------------------------------------------------
sub WriteCaches
{
&WriteCache($BotType, *BotExclude);
&WriteCache($StatType, *StatCache);
}
#--------------------------------------------------------------------------
# WriteCache($type, *hash)
#
# Writes key(hash1) value(hash1) to file. Preceded by $header.
# Will only write if cache was opened via ReadCache() and if the
# cache has been tainted via %TaintCache.
#--------------------------------------------------------------------------
sub WriteCache
{
local($type, *hash) = @_;
local($file) = $OpenedCache{$type} || return;
($TaintCache{$type} && %hash) || return;
open(CACHE, ">$file") || do {
&main'Warn(qq~Could not write $type to "$file"\n~, 'sys');
return;
};
local($header) =
"# $type created by linklint\n" .
"# Use -cache flag or set environment variable LINKLINT to\n" .
"# to change this file's directory.\n\n";
print CACHE $header;
foreach ( sort keys %hash ) {
print CACHE "$_ $hash{$_}\n";
}
close CACHE;
&main'Progress(qq~\nWrote $type to "$file"~);
}
sub FlagOk
{
$FlagOk{$_[0]} ? 1 : 0;
}
sub FlagWarn
{
$FlagWarn{$_[0]} ? 1 : 0;
}
sub Base64Encode
{
local($plain) = @_;
local($out, @out);
local(@bits) = split(//, unpack('B*', $plain));
while (@bits > 0) {
$out = join('', splice(@bits, 0, 6));
while (length($out) < 6) { $out .= '0' };
push(@out, $Base64[hex(unpack('H*', pack('B8', "00$out")))]);
}
while ( @out % 4) { push(@out, "="); }
join('', @out);
}
sub d_u_m_m_y { $main'FileList = 0 }
1; # required packages must return true
#==========================================================================
# End of linkhttp.pl
#==========================================================================