cvsweb.cgi 95.5 KB
Newer Older
1
#!/usr/bin/perl -w
2 3 4 5
#
# cvsweb - a CGI interface to CVS trees.
#
# Written in their spare time by
6 7 8 9 10 11 12 13 14
#             Bill Fenner          <fenner@FreeBSD.org>   (original work)
# extended by Henner Zeller        <zeller@think.de>,
#             Henrik Nordstrom     <hno@hem.passagen.se>
#             Ken Coar             <coar@Apache.Org>
#             Dick Balaska         <dick@buckosoft.com>
#             Akinori MUSHA        <knu@FreeBSD.org>
#             Jens-Uwe Mager       <jum@helios.de>
#             Ville Skytt         <scop@FreeBSD.org>
#             Vassilii Khachaturov <vassilii@tarunz.org>
15 16 17 18 19 20 21
#
# Based on:
# * Bill Fenners cvsweb.cgi revision 1.28 available from:
#   http://www.FreeBSD.org/cgi/cvsweb.cgi/www/en/cgi/cvsweb.cgi
#
# Copyright (c) 1996-1998 Bill Fenner
#           (c) 1998-1999 Henner Zeller
22 23 24
#           (c) 1999      Henrik Nordstrom
#           (c) 2000-2002 Akinori MUSHA
#           (c) 2002      Ville Skytt
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
48
# $FreeBSD: projects/cvsweb/cvsweb.cgi,v 1.119.2.6 2002/09/26 20:56:05 scop Exp $
49
# $Id: cvsweb.cgi,v 1.10 2007-07-20 18:52:07 stoller Exp $
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
# $Idaemons: /home/cvs/cvsweb/cvsweb.cgi,v 1.84 2001/10/07 20:50:10 knu Exp $
#
###

require 5.000;

use strict;

use vars qw (
    $cvsweb_revision
    $mydir $uname $config $allow_version_select $verbose
    @CVSrepositories @CVSROOT %CVSROOT %CVSROOTdescr
    %MIRRORS %DEFAULTVALUE %ICONS %MTYPES
    @DIFFTYPES %DIFFTYPES @LOGSORTKEYS %LOGSORTKEYS
    %alltags @tabcolors %fileinfo %tags @branchnames %nameprinted
    %symrev %revsym @allrevisions %date %author @revdisplayorder
    @revisions %state %difflines %log %branchpoint @revorder
    $prcgi @prcategories $re_prcategories $prkeyword $re_prkeyword $mancgi
    $checkoutMagic $doCheckout $scriptname $scriptwhere
69 70
    $where $pathinfo $Browser $nofilelinks $maycompress
    @stickyvars @unsafevars
71 72 73 74 75 76 77 78
    %funcline_regexp $is_mod_perl
    $is_links $is_lynx $is_w3m $is_msie $is_mozilla3 $is_textbased
    %input $query $barequery $sortby $bydate $byrev $byauthor
    $bylog $byfile $defaultDiffType $logsort $cvstree $cvsroot
    $mimetype $charset $output_filter $defaultTextPlain $defaultViewable
    $command_path %CMD $allow_compress
    $backicon $diricon $fileicon
    $fullname $newname $cvstreedefault
79
    $body_tag $body_tag_for_src $logo $defaulttitle $address
80 81 82 83 84
    $long_intro $short_instruction $shortLogLen
    $show_author $dirtable $tablepadding $columnHeaderColorDefault
    $columnHeaderColorSorted $hr_breakable $showfunc $hr_ignwhite
    $hr_ignkeysubst $diffcolorHeading $diffcolorEmpty $diffcolorRemove
    $diffcolorChange $diffcolorAdd $diffcolorDarkChange $difffontface
85 86 87 88
    $difffontsize $inputTextSize $mime_types
    $allow_annotate $allow_markup
    $allow_log_extra $allow_dir_extra $allow_source_extra
    $use_java_script $open_extern_window
89 90 91 92 93 94 95
    $extern_window_width $extern_window_height $edit_option_form
    $show_subdir_lastmod $show_log_in_markup $preformat_in_markup $v
    $navigationHeaderColor $tableBorderColor $markupLogColor
    $tabstop $state $annTable $sel $curbranch @HideModules @ForbiddenFiles
    $module $use_descriptions %descriptions @mytz $dwhere $moddate
    $use_moddate $has_zlib $gzip_open
    $allow_tar @tar_options @gzip_options @zip_options @cvs_options
96 97
    @annotate_options $LOG_FILESEPARATOR $LOG_REVSEPARATOR
    $tmpdir $HTML_DOCTYPE $HTML_META
98
    $long_tag $license
99 100 101 102 103 104 105 106 107 108 109
);

sub printDiffSelect($);
sub printDiffLinks($$);
sub printLogSortSelect($);
sub findLastModifiedSubdirs(@);
sub htmlify_sub(&$);
sub htmlify($;$);
sub spacedHtmlText($;$);
sub link($$);
sub revcmp($$);
110
sub fatal($$@);
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
sub redirect($);
sub safeglob($);
sub search_path($);
sub getMimeTypeFromSuffix($);
sub head($;$);
sub scan_directives(@);
sub openOutputFilter();
sub doAnnotate($$);
sub doCheckout($$);
sub cvswebMarkup($$$);
sub viewable($);
sub doDiff($$$$$$);
sub getDirLogs($$@);
sub readLog($;$);
sub printLog($;$);
sub doLog($);
sub flush_diff_rows($$$$);
sub human_readable_diff($);
sub navigateHeader($$$$$);
sub plural_write($$);
sub readableTime($$);
sub clickablePath($$);
sub chooseCVSRoot();
sub chooseMirror();
sub fileSortCmp();
sub download_url($$;$);
sub download_link($$$;$);
sub toggleQuery($$);
sub urlencode($);
sub htmlquote($);
sub htmlunquote($);
sub hrefquote($);
sub http_header(;$);
sub html_header($);
sub html_footer();
sub link_tags($);
sub forbidden_file($);
sub forbidden_module($);

##### Start of Configuration Area ########
delete $ENV{PATH};

153
$cvsweb_revision = '2.0.6';
154

155
use File::Basename ();
156

157
($mydir) = (File::Basename::dirname($0) =~ /(.*)/);    # untaint
158 159 160 161 162 163 164 165 166 167 168 169 170 171

# == EDIT this ==
# Locations to search for user configuration, in order:
for ("$mydir/cvsweb.conf", '/usr/local/etc/cvsweb/cvsweb.conf') {
	if (defined($_) && -r $_) {
		$config = $_;
		last;
	}
}

# == Configuration defaults ==
# Defaults for configuration variables that shouldn't need
# to be configured..
$allow_version_select = 1;
172
$allow_log_extra = 1;
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190

##### End of Configuration Area   ########

######## Configuration variables #########
# These are defined to allow checking with perl -cw
@CVSrepositories = @CVSROOT = %CVSROOT = %MIRRORS = %DEFAULTVALUE = %ICONS =
    %MTYPES = %tags = %alltags = @tabcolors = %fileinfo = ();
$cvstreedefault = $body_tag = $body_tag_for_src = $logo = $defaulttitle =
    $address = $long_intro = $short_instruction = $shortLogLen = $show_author =
    $dirtable = $tablepadding = $columnHeaderColorDefault =
    $columnHeaderColorSorted = $hr_breakable = $showfunc = $hr_ignwhite =
    $hr_ignkeysubst = $diffcolorHeading = $diffcolorEmpty = $diffcolorRemove =
    $diffcolorChange = $diffcolorAdd  = $diffcolorDarkChange = $difffontface   =
    $difffontsize    = $inputTextSize = $mime_types          = $allow_annotate =
    $allow_markup        = $use_java_script      = $open_extern_window =
    $extern_window_width = $extern_window_height = $edit_option_form   =
    $show_subdir_lastmod = $show_log_in_markup = $v = $navigationHeaderColor =
    $tableBorderColor = $markupLogColor = $tabstop = $use_moddate = $moddate =
191
    $gzip_open = $HTML_DOCTYPE = $HTML_META = $long_tag = $license = undef;
192 193 194 195 196
$tmpdir = defined($ENV{TMPDIR}) ? $ENV{TMPDIR} : "/var/tmp";

$LOG_FILESEPARATOR = q/^={77}$/;
$LOG_REVSEPARATOR  = q/^-{28}$/;

197
@DIFFTYPES = qw(h H u c s);
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
@DIFFTYPES{@DIFFTYPES} = (
	{
		'descr'   => 'colored',
		'opts'    => ['-u'],
		'colored' => 1,
	},
	{
		'descr'   => 'long colored',
		'opts'    => ['--unified=15'],
		'colored' => 1,
	},
	{
		'descr'   => 'unified',
		'opts'    => ['-u'],
		'colored' => 0,
	},
	{
		'descr'   => 'context',
		'opts'    => ['-c'],
		'colored' => 0,
	},
	{
		'descr'   => 'side by side',
		'opts'    => ['--side-by-side', '--width=164'],
		'colored' => 0,
	},
);

@LOGSORTKEYS = qw(cvs date rev);
@LOGSORTKEYS{@LOGSORTKEYS} = (
	{
		'descr' => 'Not sorted',
	},
	{
		'descr' => 'Commit date',
	},
	{
		'descr' => 'Revision',
	},
);

239 240 241 242 243 244 245 246 247 248
$HTML_DOCTYPE =
  '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">';

$HTML_META = <<EOM;
<meta name="robots" content="nofollow">
<meta name="generator" content="FreeBSD-CVSweb $cvsweb_revision">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<meta http-equiv="Content-Style-Type" content="text/css">
EOM

249 250
##### End of configuration variables #####

251 252
use Time::Local ();
use IPC::Open2 qw(open2);
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313

# Check if the zlib C library interface is installed, and if yes
# we can avoid using the extra gzip process.
eval { require Compress::Zlib; };
$has_zlib = !$@;

$verbose       = $v;
$checkoutMagic = "~checkout~";
$pathinfo      = defined($ENV{PATH_INFO}) ? $ENV{PATH_INFO} : '';
$where         = $pathinfo;
$doCheckout = ($where =~ m|^/$checkoutMagic/|);
$where =~ s|^/$checkoutMagic/|/|;
$where =~ s|^/||;
$scriptname = defined($ENV{SCRIPT_NAME}) ? $ENV{SCRIPT_NAME} : '';
$scriptname =~ s|^/*|/|;

# Let's workaround thttpd's stupidity..
if ($scriptname =~ m|/$|) {
	$pathinfo .= '/';
	my $re = quotemeta $pathinfo;
	$scriptname =~ s/$re$//;
}

$scriptwhere = $scriptname;
$scriptwhere .= '/' . urlencode($where);
$where = '/' if ($where eq '');

$is_mod_perl = defined($ENV{MOD_PERL});

# in lynx, it it very annoying to have two links
# per file, so disable the link at the icon
# in this case:
$Browser = $ENV{HTTP_USER_AGENT} || '';
$is_links    = ($Browser =~ m`^Links `);
$is_lynx     = ($Browser =~ m`^Lynx/`i);
$is_w3m      = ($Browser =~ m`^w3m/`i);
$is_msie     = ($Browser =~ m`MSIE`);
$is_mozilla3 = ($Browser =~ m`^Mozilla/[3-9]`);

$is_textbased = ($is_links || $is_lynx || $is_w3m);

$nofilelinks = $is_textbased;

# newer browsers accept gzip content encoding
# and state this in a header
# (netscape did always but didn't state it)
# It has been reported that these
#  braindamaged MS-Internet Exploders claim that they
# accept gzip .. but don't in fact and
# display garbage then :-/
# Turn off gzip if running under mod_perl and no zlib is available,
# piping does not work as expected inside the server.
$maycompress =
    (((defined($ENV{HTTP_ACCEPT_ENCODING})
    && $ENV{HTTP_ACCEPT_ENCODING} =~ m`gzip`) || $is_mozilla3) && !$is_msie
    && !($is_mod_perl && !$has_zlib));

# put here the variables we need in order
# to hold our state - they will be added (with
# their current value) to any link/query string
# you construct
314
@stickyvars = qw(cvsroot hideattic sortby logsort f only_with_tag
315
		 pid eid exptidx guid version);
316
@unsafevars = qw(logsort only_with_tag r1 r2 rev sortby tr1 tr2);
317 318

if (-f $config) {
319 320 321
	do "$config" or fatal("500 Internal Error",
			      'Error in loading configuration file: %s<br><br>%s<br>',
			      $config, $@);
322
} else {
323 324 325
	fatal("500 Internal Error",
	      'Configuration not found.  Set the variable <code>$config</code> in cvsweb.cgi to your <b>cvsweb.conf</b> configuration file first.'
	     );
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
}

undef %input;
$query = $ENV{QUERY_STRING};

if (defined($query) && $query ne '') {
	foreach (split (/&/, $query)) {
		y/+/ /;
		s/%(..)/sprintf("%c", hex($1))/ge;    # unquote %-quoted
		if (/(\S+)=(.*)/) {
			$input{$1} = $2 if ($2 ne "");
		} else {
			$input{$_}++;
		}
	}
}

# For backwards compability, set only_with_tag to only_on_branch if set.
$input{only_with_tag} = $input{only_on_branch}
    if (defined($input{only_on_branch}));

347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
# Prevent cross-site scripting
foreach (@unsafevars) {
	# Colons are needed in diffs between tags.
	if (defined($input{$_}) && $input{$_} =~ /[^\w\-.:]/) {
		fatal("500 Internal Error",
		      'Malformed query (%s=%s)',
		      $_, $input{$_});
	}
}

if (defined($input{"content-type"})) {
	fatal("500 Internal Error", "Unsupported content-type")
	    if ($input{"content-type"} !~ /^[-0-9A-Za-z]+\/[-0-9A-Za-z]+$/);
}

362
# Emulab Hacks!
363
if (@ARGV && $ARGV[0] eq "--repo") {
364
    $license = undef;
365 366 367
    @CVSrepositories = (
	'top'   => [$ARGV[1], $ARGV[1]],
    );
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
    $cvstreedefault = $CVSrepositories[2 * 0];    # The first one
}
elsif (! -e @{$CVSrepositories[1]}[1] . "/CVSROOT") {
    my $dh = do { local (*DH); };
    my $topdir = @{$CVSrepositories[1]}[1];
    
    opendir($dh, $topdir) or
	fatal("404 Not Found", '%s: %s', $topdir, $!);
    my @dirfiles = readdir($dh);
    closedir($dh);
    
    @CVSrepositories = ();

    foreach my $dir (@dirfiles) {
	my $rdir = "$topdir/$dir";

	next
	    if ($dir eq "." || $dir eq "..");

	if (-r $rdir && -e "$rdir/CVSROOT") {
	    push(@CVSrepositories, $dir => [$dir, $rdir]);
	}
    }
    if (! @CVSrepositories) {
	fatal("404 Not Found", '%s: %s', $topdir, $!);
    }
    $cvstreedefault = $CVSrepositories[2 * 0];    # The first one
395
}
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
$DEFAULTVALUE{'cvsroot'} = $cvstreedefault;

foreach (keys %DEFAULTVALUE) {

	# replace not given parameters with the default parameters
	if (!defined($input{$_}) || $input{$_} eq "") {

		# Empty Checkboxes in forms return -- nothing. So we define a helper
		# variable in these forms (copt) which indicates that we just set
		# parameters with a checkbox
		if (!defined($input{"copt"})) {

			# 'copt' isn't defined --> empty input is not the result
			# of empty input checkbox --> set default
			$input{$_} = $DEFAULTVALUE{$_}
			    if (defined($DEFAULTVALUE{$_}));
		} else {

			# 'copt' is defined -> the result of empty input checkbox
			# -> set to zero (disable) if default is a boolean (0|1).
			$input{$_} = 0
			    if (defined($DEFAULTVALUE{$_})
			    && ($DEFAULTVALUE{$_} eq "0"
			    || $DEFAULTVALUE{$_} eq "1"));
		}
	}
}

$barequery = "";
my @barequery;
foreach (@stickyvars) {

	# construct a query string with the sticky non default parameters set
	if (defined($input{$_}) && $input{$_} ne ''
	    && !(defined($DEFAULTVALUE{$_}) && $input{$_} eq $DEFAULTVALUE{$_}))
	{
		push @barequery,
		    join ('=', urlencode($_), urlencode($input{$_}));
	}
}

# is there any query ?
if (@barequery) {
	$barequery = join ('&', @barequery);
	$query     = "?$barequery";
	$barequery = "&$barequery";
} else {
	$query = "";
}
undef @barequery;

if (defined($input{path})) {
	redirect("$scriptname/$input{path}$query");
}

# get actual parameters
$sortby   = $input{"sortby"};
$bydate   = 0;
$byrev    = 0;
$byauthor = 0;
$bylog    = 0;
$byfile   = 0;
if ($sortby eq "date") {
	$bydate = 1;
} elsif ($sortby eq "rev") {
	$byrev = 1;
} elsif ($sortby eq "author") {
	$byauthor = 1;
} elsif ($sortby eq "log") {
	$bylog = 1;
} else {
	$byfile = 1;
}

$defaultDiffType = $input{'f'};

$logsort = $input{'logsort'};

474 475 476
{
	my @tmp = @CVSrepositories;
	my @pair;
477

478 479 480
	while (@pair = splice(@tmp, 0, 2)) {
		my ($key,   $val)     = @pair;
		my ($descr, $cvsroot) = @$val;
481

482
		next if !-d $cvsroot;
483

484 485 486 487
		$CVSROOTdescr{$key} = $descr;
		$CVSROOT{$key}      = $cvsroot;
		push @CVSROOT, $key;
	}
488 489 490 491
}

## Default CVS-Tree
if (!defined($CVSROOT{$cvstreedefault})) {
492 493 494
	fatal("500 Internal Error",
	      '<code>$cvstreedefault</code> points to a repository (%s) not defined in <code>%%CVSROOT</code> (edit your configuration file %s)',
	      $cvstreedefault, $config);
495 496 497 498 499 500 501 502 503 504 505 506
}

# alternate CVS-Tree, configured in cvsweb.conf
if ($input{'cvsroot'} && $CVSROOT{$input{'cvsroot'}}) {
	$cvstree = $input{'cvsroot'};
} else {
	$cvstree = $cvstreedefault;
}

$cvsroot = $CVSROOT{$cvstree};

# create icons out of description
507
foreach my $k (keys %ICONS) {
508 509 510 511 512
	no strict 'refs';
	my ($itxt, $ipath, $iwidth, $iheight) = @{$ICONS{$k}};
	if ($ipath) {
		${"${k}icon"} =
		    sprintf(
513
			'<img src="%s" alt="%s" border="0" width="%d" height="%d">',
514 515 516 517 518 519 520 521 522 523
			hrefquote($ipath), htmlquote($itxt), $iwidth, $iheight)
	} else {
		${"${k}icon"} = $itxt;
	}
}

my $config_cvstree = "$config-$cvstree";

# Do some special configuration for cvstrees
if (-f $config_cvstree) {
524 525 526 527
	do "$config_cvstree" or
	    fatal("500 Internal Error",
		  'Error in loading configuration file: %s<br><br>%s<br>',
		  $config_cvstree, $@);
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
}
undef $config_cvstree;

$re_prcategories = '(?:' . join ('|', @prcategories) . ')' if @prcategories;
$re_prkeyword = quotemeta($prkeyword) if defined($prkeyword);
$prcgi .= '%s' if defined($prcgi) && $prcgi !~ /%s/;

$fullname         = "$cvsroot/$where";
$mimetype         = &getMimeTypeFromSuffix($fullname);
$defaultTextPlain = ($mimetype eq "text/plain");
$defaultViewable  = $allow_markup && viewable($mimetype);

my $rewrite = 0;

if ($pathinfo =~ m|//|) {
	$pathinfo =~ y|/|/|s;
	$rewrite = 1;
}

if (-d $fullname && $pathinfo !~ m|/$|) {
	$pathinfo .= '/';
	$rewrite = 1;
}

if (!-d $fullname && $pathinfo =~ m|/$|) {
	chop $pathinfo;
	$rewrite = 1;
}

if ($rewrite) {
	redirect($scriptname . urlencode($pathinfo) . $query);
}

undef $rewrite;

if (!-d $cvsroot) {
564 565
	fatal("500 Internal Error",
	      '$CVSROOT not found!<p>The server on which the CVS tree lives is probably down.  Please try again in a few minutes.');
566 567 568 569 570 571 572 573
}

#
# See if the module is in our forbidden list.
#
$where =~ m:([^/]*):;
$module = $1;
if ($module && &forbidden_module($module)) {
574 575 576
	fatal("403 Forbidden",
	      'Access to %s forbidden.',
	      $where);
577 578 579 580 581 582
}

#
# Handle tarball downloads before any headers are output.
#
if ($input{tarball}) {
583 584
	fatal("403 Forbidden",
	      'Downloading tarballs is prohibited.')
585 586 587 588 589 590 591
	    unless $allow_tar;
	my ($module) = ($where =~ m,^/?(.*),);    # untaint
	$module =~ s,/([^/]*)$,,;
	my ($ext)     = ($1      =~ /(\.tar\.gz|\.zip)$/);
	my ($basedir) = ($module =~ m,([^/]+)$,);

	if ($basedir eq '' || $module eq '') {
592 593
		fatal("500 Internal Error",
		      'You cannot download the top level directory.');
594 595
	}

596
	my $tmpexportdir = "$tmpdir/.cvsweb.$$." . int(time);
597

598 599 600 601
	mkdir($tmpexportdir, 0700)
	    or fatal("500 Internal Error",
		     'Unable to make temporary directory: %s',
		     $!);
602 603 604 605 606 607 608

	my @fatal;

	my $tag =
	    (exists $input{only_with_tag} && length $input{only_with_tag}) ?
	    $input{only_with_tag} : "HEAD";

609 610 611 612
	if ($tag eq 'MAIN') {
	    $tag = 'HEAD';
	}

613
	if (system $CMD{cvs}, @cvs_options, '-Qd', $cvsroot, 'export', '-r',
614
	    $tag, '-d', "$tmpexportdir/$basedir", $module)
615
	{
616 617 618
		@fatal = ("500 Internal Error",
			  'cvs co failure: %s: %s',
			  $!, $module);
619 620 621 622
	} else {
		$| = 1;    # Essential to get the buffering right.

		if ($ext eq '.tar.gz') {
623
			print "Content-Type: application/x-gzip\r\n\r\n";
624 625

			system
626
			    "$CMD{gtar} @tar_options -cf - -C $tmpexportdir $basedir | $CMD{gzip} @gzip_options -c"
627
			    and @fatal =
628 629 630
				("500 Internal Error",
				 'tar zc failure: %s: %s',
			     $!, $basedir);
631
		} elsif ($ext eq '.zip' && $CMD{zip}) {
632
			print "Content-Type: application/zip\r\n\r\n";
633 634

			system
635
			    "cd $tmpexportdir && $CMD{zip} @zip_options -r - $basedir"
636
			    and @fatal =
637 638 639
				("500 Internal Error",
				 'zip failure: %s: %s',
				 $!, $basedir);
640 641
		} else {
			@fatal =
642 643
			    ("500 Internal Error",
			     'unsupported file type');
644 645 646
		}
	}

647
	system $CMD{rm}, '-rf', $tmpexportdir if -d $tmpexportdir;
648 649 650 651 652 653 654 655 656 657

	&fatal(@fatal) if @fatal;

	exit;
}

##############################
# View a directory
###############################
if (-d $fullname) {
658
    	my $dh = do { local (*DH); };
659 660 661
	opendir($dh, $fullname) or fatal("404 Not Found",
					 '%s: %s',
					 $where, $!);
662 663 664 665 666 667 668 669 670 671 672
	my @dir = readdir($dh);
	closedir($dh);
	my @subLevelFiles = findLastModifiedSubdirs(@dir)
	    if ($show_subdir_lastmod);
	getDirLogs($cvsroot, $where, @subLevelFiles);

	if ($where eq '/') {
		html_header($defaulttitle);
		$long_intro =~ s/!!CVSROOTdescr!!/$CVSROOTdescr{$cvstree}/g;
		print $long_intro;
	} else {
673
    		html_header($where);
674
		print $short_instruction;
675 676
                print $license
                   if (defined($license));
677 678
	}

679
	if ($use_descriptions && open(DESC, "<$cvsroot/CVSROOT/descriptions"))
680 681 682 683 684 685
	{
		while (<DESC>) {
			chomp;
			my ($dir, $description) = /(\S+)\s+(.*)/;
			$descriptions{$dir} = $description;
		}
686
		close(DESC);
687 688
	}

689
	print "<p><a name=\"dirlist\"></a></p>\n";
690 691 692 693

	# give direct access to dirs
	if ($where eq '/') {
		chooseMirror ();
694
                #chooseCVSRoot ();
695 696
	} else {
		print "<p>Current directory: <b>", &clickablePath($where, 0),
697
		    "</b></p>\n";
698

699
		print "<p>Current tag: <b>", $input{only_with_tag},"</b></p>\n"
700 701 702 703
		    if $input{only_with_tag};

	}

704
	print "<hr noshade>\n";
705

706
	# Using <menu> in this manner violates the HTML2.0 spec but
707 708 709 710 711
	# provides the results that I want in most browsers.  Another
	# case of layout spooging up HTML.

	my $infocols = 0;
	if ($dirtable) {
712 713 714 715
		print "<table style=\"border-width: 0";
		print "; background-color: $tableBorderColor"
		    if (defined $tableBorderColor);
		print "\" width=\"100%\" cellspacing=\"1\" cellpadding=\"$tablepadding\">\n";
716
		$infocols++;
717
		printf "<tr>\n<th style=\"text-align: left; background-color: %s\">",
718 719 720 721 722 723 724 725 726 727 728 729 730 731
		    $byfile ? $columnHeaderColorSorted :
		    $columnHeaderColorDefault;

		if ($byfile) {
			print 'File';
		} else {
			print &link(
				'File',
				sprintf(
					'./%s#dirlist',
					&toggleQuery("sortby", "file")
				)
			);
		}
732
		print "</th>\n";
733 734 735 736 737

		# do not display the other column-headers, if we do not have any files
		# with revision information:
		if (scalar(%fileinfo)) {
			$infocols++;
738
			printf '<th style="text-align: left; background-color: %s">',
739 740 741 742 743 744 745 746 747 748 749 750 751 752
			    $byrev ? $columnHeaderColorSorted :
			    $columnHeaderColorDefault;

			if ($byrev) {
				print 'Rev.';
			} else {
				print &link(
					'Rev.',
					sprintf(
						'./%s#dirlist',
						&toggleQuery("sortby", "rev")
					)
				);
			}
753
			print "</th>\n";
754
			$infocols++;
755
			printf '<th style="text-align: left; background-color: %s">',
756 757 758 759 760 761 762 763 764 765 766 767 768 769
			    $bydate ? $columnHeaderColorSorted :
			    $columnHeaderColorDefault;

			if ($bydate) {
				print 'Age';
			} else {
				print &link(
					'Age',
					sprintf(
						'./%s#dirlist',
						&toggleQuery("sortby", "date")
					)
				);
			}
770
			print "</th>\n";
771 772 773

			if ($show_author) {
				$infocols++;
774
				printf '<th style="text-align: left; background-color: %s">',
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
				    $byauthor ? $columnHeaderColorSorted :
				    $columnHeaderColorDefault;

				if ($byauthor) {
					print 'Author';
				} else {
					print &link(
						'Author',
						sprintf(
							'./%s#dirlist',
							&toggleQuery(
								"sortby",
								"author"
							)
						)
					);
				}
792
				print "</th>\n";
793 794
			}
			$infocols++;
795
			printf '<th style="text-align: left; background-color: %s">',
796 797 798 799 800 801 802 803 804 805 806 807 808 809
			    $bylog ? $columnHeaderColorSorted :
			    $columnHeaderColorDefault;

			if ($bylog) {
				print 'Last log entry';
			} else {
				print &link(
					'Last log entry',
					sprintf(
						'./%s#dirlist',
						&toggleQuery("sortby", "log")
					)
				);
			}
810
			print "</th>\n";
811
		} elsif ($use_descriptions) {
812
			printf '<th style="text-align: left; background-color: s">',
813
			    $columnHeaderColorDefault;
814
			print "Description</th>\n";
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
			$infocols++;
		}
		print "</tr>\n";
	} else {
		print "<menu>\n";
	}
	my $dirrow = 0;

	my $i;
	lookingforattic:
	for ($i = 0 ; $i <= $#dir ; $i++) {
		if ($dir[$i] eq "Attic") {
			last lookingforattic;
		}
	}

	if (!$input{'hideattic'} && ($i <= $#dir)
	    && opendir($dh, $fullname . "/Attic"))
	{
		splice(@dir, $i, 1, grep((s|^|Attic/|, !m|/\.|), readdir($dh)));
		closedir($dh);
	}

	my $hideAtticToggleLink =
	    $input{'hideattic'} ? '' :
	    &link('[Hide]', sprintf('./%s#dirlist', &toggleQuery("hideattic")));

	# Sort without the Attic/ pathname.
	# place directories first

	my $attic;
	my $url;
	my $fileurl;
	my $filesexists;
	my $filesfound;

851 852 853
	foreach my $file (sort { &fileSortCmp } @dir) {

		next if ($file eq '.');
854 855

		# ignore CVS lock and stale NFS files
856
		next if ($file =~ /^#cvs\.|^,|^\.nfs/);
857 858

		# Check whether to show the CVSROOT path
859
		next if ($input{'hidecvsroot'} && $file eq 'CVSROOT');
860 861

		# Check whether the module is in the restricted list
862
		next if ($file && &forbidden_module($file));
863 864

		# Ignore non-readable files
865
		next if ($input{'hidenonreadable'} && !(-r "$fullname/$file"));
866

867
		if ($file =~ s|^Attic/||) {
868 869 870 871 872
			$attic = " (in the Attic)&nbsp;" . $hideAtticToggleLink;
		} else {
			$attic = "";
		}

873 874 875 876 877 878 879
		if ($file eq '..' || -d "$fullname/$file") {
			next if ($file eq '..' && $where eq '/');
			my ($rev, $date, $log, $author, $filename) =
			    @{$fileinfo{$file}}
			    if (defined($fileinfo{$file}));
			printf "<tr style=\"background-color: %s\">\n<td>",
			     $tabcolors[$dirrow % 2] if $dirtable;
880

881
			if ($file eq '..') {
882 883 884 885 886 887
				$url = "../$query";
				if ($nofilelinks) {
					print $backicon;
				} else {
					print &link($backicon, $url);
				}
888
				print '&nbsp;', &link("Parent Directory", $url);
889
			} else {
890 891
				$url = './' . urlencode($file) . "/$query";
				print "<a name=\"$file\"></a>";
892 893 894 895 896 897

				if ($nofilelinks) {
					print $diricon;
				} else {
					print &link($diricon, $url);
				}
898
				print '&nbsp;', &link("$file/", $url), $attic;
899

900
				if ($file eq "Attic") {
901 902 903 904 905 906 907 908 909 910 911 912 913 914
					print "&nbsp; ";
					print &link(
						"[Don't hide]",
						sprintf(
							'./%s#dirlist',
							&toggleQuery(
								"hideattic")
						)
					);
				}
			}

			# Show last change in dir
			if ($filename) {
915
				print "</td>\n<td>&nbsp;</td>\n<td>&nbsp;"
916 917 918 919 920 921 922 923
				    if ($dirtable);
				if ($date) {
					print " <i>",
					    readableTime(time() - $date, 0),
					    "</i>";
				}

				if ($show_author) {
924
					print "</td>\n<td>&nbsp;" if ($dirtable);
925 926
					print $author;
				}
927
				print "</td>\n<td>&nbsp;" if ($dirtable);
928 929
				$filename =~ s%^[^/]+/%%;
				print "$filename/$rev";
930
				print "<br>" if ($dirtable);
931 932

				if ($log) {
933 934 935
					print "&nbsp;<span style=\"font-size: smaller\">",
					  &htmlify(
						substr($log, 0, $shortLogLen), $allow_dir_extra);
936 937 938
					if (length $log > 80) {
						print "...";
					}
939
					print "</span>";
940 941 942
				}
			} else {
				my ($dwhere) =
943
				    ($where ne "/" ? $where : "") . $file;
944 945 946 947

				if ($use_descriptions
				    && defined $descriptions{$dwhere})
				{
948 949
					print "<td colspan=\"",($infocols - 1),
					    "\">&nbsp;"
950 951 952 953 954 955 956 957
					    if $dirtable;
					print $descriptions{$dwhere};
				} elsif ($dirtable && $infocols > 1) {

					# close the row with the appropriate number of
					# columns, so that the vertical seperators are visible
					my ($cols) = $infocols;
					while ($cols > 1) {
958
						print "</td>\n<td>&nbsp;";
959 960 961 962 963 964
						$cols--;
					}
				}
			}

			if ($dirtable) {
965
				print "</td>\n</tr>\n";
966 967 968 969
			} else {
				print "<br>\n";
			}
			$dirrow++;
970 971 972 973 974 975 976 977
		} elsif ($file =~ s/,v$//) {

			# Skip forbidden files now so we'll give no hint
			# about their existence.  This should probably have
			# been done earlier, but it's straightforward here.
			next if forbidden_file("$fullname/$file");

			$fileurl = ($attic ? "Attic/" : "") . urlencode($file);
978 979
			$url = './' . $fileurl . $query;
			$filesexists++;
980 981
			next if (!defined($fileinfo{$file}));
			my ($rev, $date, $log, $author) = @{$fileinfo{$file}};
982
			$filesfound++;
983 984 985
			printf "<tr style=\"background-color: %s\">\n<td>",
			    $tabcolors[$dirrow % 2] if $dirtable;
			print "<a name=\"$file\"></a>";
986 987 988 989 990 991

			if ($nofilelinks) {
				print $fileicon;
			} else {
				print &link($fileicon, $url);
			}
992 993
			print '&nbsp;', &link(htmlquote($file), $url), $attic;
			print "</td>\n<td>&nbsp;" if ($dirtable);
994 995 996
			download_link($fileurl, $rev, $rev,
				$defaultViewable ? "text/x-cvsweb-markup" :
				undef);
997
			print "</td>\n<td>&nbsp;" if ($dirtable);
998 999 1000 1001 1002 1003

			if ($date) {
				print " <i>", readableTime(time() - $date, 0),
				    "</i>";
			}
			if ($show_author) {
1004
				print "</td>\n<td>&nbsp;" if ($dirtable);
1005 1006
				print $author;
			}
1007
			print "</td>\n<td>&nbsp;" if ($dirtable);
1008 1009

			if ($log) {
1010 1011
				print " <span style=\"font-size: smaller\">",
				    &htmlify(substr($log, 0, $shortLogLen), $allow_dir_extra);
1012 1013 1014
				if (length $log > 80) {
					print "...";
				}
1015
				print "</span>";
1016
			}
1017
			print "</td>\n" if ($dirtable);
1018 1019 1020 1021 1022 1023
			print(($dirtable) ? "</tr>" : "<br>");
			$dirrow++;
		}
		print "\n";
	}

1024
	print($dirtable ? "</table>\n" : "</menu>\n");
1025 1026 1027

	if ($filesexists && !$filesfound) {
		print
1028
		    "<p><b>NOTE:</b> There are $filesexists files, but none matches the current tag ($input{only_with_tag}).</p>\n";
1029 1030 1031 1032 1033 1034 1035 1036 1037
	}
	if ($input{only_with_tag} && (!%tags || !$tags{$input{only_with_tag}}))
	{
		%tags = %alltags
	}

	if (scalar %tags || $input{only_with_tag} || $edit_option_form
	    || defined($input{"options"}))
	{
1038
		print "<hr size=\"1\" noshade>\n";
1039 1040 1041
	}

	if (scalar %tags || $input{only_with_tag}) {
1042
		print "<form method=\"get\" action=\"./\">\n";
1043 1044
		foreach my $var (@stickyvars) {
			print
1045
			    "<input type=\"hidden\" name=\"$var\" value=\"$input{$var}\">\n"
1046 1047 1048 1049 1050
			    if (defined($input{$var})
			    && (!defined($DEFAULTVALUE{$var})
			    || $input{$var} ne $DEFAULTVALUE{$var})
			    && $input{$var} ne "" && $var ne "only_with_tag");
		}
1051 1052 1053 1054
		print "<p><label for=\"only_with_tag\" accesskey=\"T\">";
		print "Show only files with tag:</label>\n";
		print "<select id=\"only_with_tag\" name=\"only_with_tag\"";
		print " onchange=\"this.form.submit()\"" if $use_java_script;
1055
		print ">";
1056
		print "<option value=\"\">All tags / default branch</option>\n";
1057 1058

		foreach my $tag (reverse sort { lc $a cmp lc $b } keys %tags) {
1059
			print "<option",
1060
			    defined($input{only_with_tag})
1061 1062
			    && $input{only_with_tag} eq $tag ? " selected" : "",
			    ">$tag</option>\n";
1063
		}
1064 1065 1066 1067
		print "</select>\n";
		print " <label for=\"path\" accesskey=\"P\">";
		print "Module path or alias:</label>\n";
		printf "<input type=\"text\" id=\"path\" name=\"path\" value=\"%s\" size=\"15\">\n",
1068
		    htmlquote($where);
1069 1070
		print "<input type=\"submit\" value=\"Go\" accesskey=\"G\"></p>\n";
		print "</form>\n";
1071 1072 1073 1074 1075 1076
	}

	if ($allow_tar) {
		my ($basefile) = ($where =~ m,(?:.*/)?([^/]+),);

		if (defined($basefile) && $basefile ne '') {
1077 1078
			print "<hr noshade>\n",
			    "<div align=\"center\">Download this directory in ";
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088

			# Mangle the filename so browsers show a reasonable
			# filename to download.
			print &link("tarball", "./$basefile.tar.gz$query"
				. ($query ? "&" : "?") . "tarball=1");
			if ($CMD{zip}) {
				print " or ",
				    &link("zip archive", "./$basefile.zip$query"
					. ($query ? "&" : "?") . "tarball=1");
			}
1089
			print "</div>\n";
1090 1091 1092 1093
		}
	}

	if ($edit_option_form || defined($input{"options"})) {
1094 1095 1096 1097 1098 1099

		my $formwhere = $scriptwhere;
		$formwhere =~ s|Attic/?$|| if ($input{'hideattic'});

		print "<form method=\"get\" action=\"${formwhere}\">\n";
		print "<input type=\"hidden\" name=\"copt\" value=\"1\">\n";
1100 1101
		if ($cvstree ne $cvstreedefault) {
			print
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
			    "<input type=\"hidden\" name=\"cvsroot\" value=\"$cvstree\">\n";
		}
		print "<center>\n<table cellpadding=\"0\" cellspacing=\"0\">";
		print "\n<tr style=\"background-color: $columnHeaderColorDefault\">\n";
		print "<th colspan=\"2\">Preferences</th>\n</tr>\n";
		print "<tr>\n<td>";
		print "<label for=\"sortby\" accesskey=\"F\">Sort files by ";
		print "</label><select id=\"sortby\" name=\"sortby\">\n";
		print "<option value=\"\">File</option>\n";
		print "<option", $bydate ? " selected" : "",
		    " value=\"date\">Age</option>\n";
		print "<option", $byauthor ? " selected" : "",
		    " value=\"author\">Author</option>\n"
1115
		    if ($show_author);
1116 1117 1118 1119 1120 1121 1122
		print "<option", $byrev ? " selected" : "",
		    " value=\"rev\">Revision</option>\n";
		print "<option", $bylog ? " selected" : "",
		    " value=\"log\">Log message</option>\n";
		print "</select>\n</td>\n";
		print "<td><label for=\"logsort\" accesskey=\"L\">";
		print "Sort log by: </label>";
1123
		printLogSortSelect(0);
1124 1125 1126
		print "</td>\n</tr>\n";
		print "<tr>\n<td><label for=\"f\" accesskey=\"D\">";
		print "Diff format: </label>";
1127
		printDiffSelect(0);
1128 1129 1130 1131 1132 1133 1134 1135 1136
		print "</td>\n";
		print "<td><label for=\"hideattic\" accesskey=\"A\">";
		print "Show Attic files: </label>";
		print "<input id=\"hideattic\" name=\"hideattic\" type=\"checkbox\"",
		    $input{'hideattic'} ? " checked" : "",
		     "></td>\n</tr>\n";
		print "<tr>\n<td align=\"center\" colspan=\"2\">";
		print "<input type=\"submit\" value=\"Change Options\" accesskey=\"C\">";
		print "</td>\n</tr>\n</table>\n</center>\n</form>\n";
1137
	}
1138 1139 1140 1141
	if ($where eq '/') {
		$long_tag =~ s/!!CVSROOTdescr!!/$CVSROOTdescr{$cvstree}/g;
		print $long_tag;
	}
1142
	html_footer();
1143 1144 1145 1146 1147 1148
}

###############################
# View Files
###############################
elsif (-f $fullname . ',v') {
1149 1150 1151 1152 1153 1154 1155

	if (forbidden_file($fullname)) {
		fatal('403 Forbidden',
		      'Access forbidden.  This file is mentioned in @ForbiddenFiles');
		return;
	}

1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
	if (defined($input{'rev'}) || $doCheckout) {
		&doCheckout($fullname, $input{'rev'});
		gzipclose();
		exit;
	}

	if (defined($input{'annotate'}) && $allow_annotate) {
		&doAnnotate($input{'annotate'});
		gzipclose();
		exit;
	}

	if (defined($input{'r1'}) && defined($input{'r2'})) {
		&doDiff(
			$fullname,     $input{'r1'},
			$input{'tr1'}, $input{'r2'},
			$input{'tr2'}, $input{'f'}
		);
		gzipclose();
		exit;
	}
	print("going to dolog($fullname)\n") if ($verbose);
	&doLog($fullname);

	##############################
	# View Diff
	##############################
} elsif ($fullname =~ s/\.diff$// && -f $fullname . ",v" && $input{'r1'}
    && $input{'r2'})
{

	# $where-diff-removal if 'cvs rdiff' is used
	# .. but 'cvs rdiff'doesn't support some options
	# rcsdiff does (-w and -p), so it is disabled
	# $where =~ s/\.diff$//;

	# Allow diffs using the ".diff" extension
	# so that browsers that default to the URL
	# for a save filename don't save diff's as
	# e.g. foo.c
	&doDiff(
		$fullname,     $input{'r1'}, $input{'tr1'}, $input{'r2'},
		$input{'tr2'}, $input{'f'}
	);
	gzipclose();
	exit;
} elsif (($newname = $fullname) =~ s|/([^/]+)$|/Attic/$1| && -f $newname . ",v")
{

	# The file has been removed and is in the Attic.
	# Send a redirect pointing to the file in the Attic.
	(my $newplace = $scriptwhere) =~ s|/([^/]+)$|/Attic/$1|;
	if ($ENV{QUERY_STRING} ne "") {
		redirect("${newplace}?$ENV{QUERY_STRING}");
	} else {
		redirect($newplace);
	}
	exit;
} elsif (0 && (my @files = &safeglob($fullname . ",v"))) {
	http_header("text/plain");
	print "You matched the following files:\n";
	print join ("\n", @files);

	# Find the tags from each file
	# Display a form offering diffs between said tags
} else {
	my $fh = do { local (*FH); };
	my ($xtra, $module);

	# Assume it's a module name with a potential path following it.
	$xtra = (($module = $where) =~ s|/.*||) ? $& : '';

	# Is there an indexed version of modules?
	if (open($fh, "< $cvsroot/CVSROOT/modules")) {
		while (<$fh>) {
			if (/^(\S+)\s+(\S+)/o && $module eq $1
			    && -d "$cvsroot/$2" && $module ne $2)
			{
				redirect("$scriptname/$2$xtra$query");
			}
		}
	}
1238 1239 1240
	fatal("404 Not Found",
	      '%s: no such file or directory',
	      $where);
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
}

gzipclose();

## End MAIN

sub printDiffSelect($) {
	my ($use_java_script) = @_;
	my $f = $input{'f'};

1251 1252 1253
	print '<select id="f" name="f"';
	print ' onchange="this.form.submit()"' if $use_java_script;
	print ">\n";
1254 1255 1256

	local $_;
	for (@DIFFTYPES) {
1257 1258
		printf("<option value=\"%s\"%s>%s</option>\n", $_,
		    $f eq $_ ? ' selected' : '', "\u$DIFFTYPES{$_}{'descr'}");
1259 1260
	}

1261
	print "</select>";
1262 1263 1264 1265 1266
}

sub printLogSortSelect($) {
	my ($use_java_script) = @_;

1267 1268 1269
	print '<select id="logsort" name="logsort"';
	print ' onchange="this.form.submit()"' if $use_java_script;
	print ">\n";
1270 1271 1272

	local $_;
	for (@LOGSORTKEYS) {
1273 1274
		printf("<option value=\"%s\"%s>%s</option>\n", $_,
		    $logsort eq $_ ? ' selected' : '',
1275 1276 1277
		    "\u$LOGSORTKEYS{$_}{'descr'}");
	}

1278
	print "</select>";
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
}

sub findLastModifiedSubdirs(@) {
	my (@dirs) = @_;
	my ($dirname, @files);

	foreach $dirname (@dirs) {
		next if ($dirname eq ".");
		next if ($dirname eq "..");
		my ($dir) = "$fullname/$dirname";
		next if (!-d $dir);

		my ($lastmod)     = undef;
		my ($lastmodtime) = undef;
		my $dh = do { local (*DH); };

1295
		opendir($dh, $dir) or next;
1296 1297 1298 1299 1300 1301 1302
		my (@filenames) = readdir($dh);
		closedir($dh);

		foreach my $filename (@filenames) {
			$filename = "$dirname/$filename";
			my ($file) = "$fullname/$filename";
			next if ($filename !~ /,v$/ || !-f $file);
1303 1304 1305 1306 1307

			# Skip forbidden files.
			(my $f = $file) =~ s/,v$//;
			next if forbidden_file($f);

1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
			$filename =~ s/,v$//;
			my $modtime = -M $file;

			if (!defined($lastmod) || $modtime < $lastmodtime) {
				$lastmod     = $filename;
				$lastmodtime = $modtime;
			}
		}
		push (@files, $lastmod) if (defined($lastmod));
	}
	return @files;
}

sub htmlify_sub(&$) {
	(my $proc, local $_) = @_;
	my @a = split (m`(<a [^>]+>[^<]*</a>)`i);
	my $linked;
	my $result = '';

	while (($_, $linked) = splice(@a, 0, 2)) {
		&$proc();
		$result .= $_      if defined($_);
		$result .= $linked if defined($linked);
	}

	$result;
}

sub htmlify($;$) {
	(local $_, my $extra) = @_;

	$_ = htmlquote($_);

	# get URL's as link
	s{
      (http|ftp|https)://\S+
     }{
	 &link($&, htmlunquote($&))
     }egx;

	# get e-mails as link
	$_ = htmlify_sub {
		s<
	  [\w+=\-.!]+@[\w\-]+(\.[\w\-]+)+
	    ><
	      &link($&, "mailto:$&")
		>egix;
	    }
	    $_;

	if ($extra) {

		# get PR #'s as link: "PR#nnnn" "PR: nnnn, ..." "PR nnnn, ..." "bin/nnnn"
1361
		if (defined($prcgi) && defined($re_prkeyword))
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
		{
			my $prev;

			do {
				$prev = $_;

				$_ = htmlify_sub {
					s{
		      (\b$re_prkeyword[:\#]?\s*
		       (?:
			\#?
			\d+[,\s]\s*
		       )*
		       \#?)
		      (\d+)\b
		     }{
			 $1 . &link($2, sprintf($prcgi, $2))
		     }egix;
				    }
				    $_;
			} while ($_ ne $prev);

1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
			if (defined($re_prcategories)) {
				$_ = htmlify_sub {
					s{
			  (\b$re_prcategories/(\d+)\b)
			}{
				&link($1, sprintf($prcgi, $2))
			}egox;
				    }
				    $_;
			}
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
		}

		# get manpage specs as link: "foo.1" "foo(1)"
		if (defined($mancgi)) {
			$_ = htmlify_sub {
				s{
		  (\b([a-zA-Z][\w.]+)
		   (?:
		    \( ([0-9n]) \)\B
		    |
		    \.([0-9n])\b
		   )
		  )
		 }{
		     &link($1, sprintf($mancgi, defined($3) ? $3 : $4, $2))
		 }egx;
			    }
			    $_;
		}
	}

	$_;
}

sub spacedHtmlText($;$) {
	local $_ = $_[0];
	my $ts = $_[1] || $tabstop;

	# Cut trailing spaces and tabs
	s/[ \t]+$//;

	if (defined($ts)) {

		# Expand tabs
		1 while s/\t+/' ' x (length($&) * $ts - length($`) % $ts)/e
	}

	# replace <tab> and <space> (\001 is to protect us from htmlify)
	# gzip can make excellent use of this repeating pattern :-)
	if ($hr_breakable) {

		# make every other space 'breakable'
		s/  / \001nbsp;/g;    # 2 * <space>
		                      # leave single space as it is
	} else {
		s/ /\001nbsp;/g;
	}

1442
	$_ = htmlify($_, $allow_source_extra);
1443 1444 1445 1446 1447 1448 1449

	# unescape
	y/\001/&/;

	return $_;
}

1450
# Note that this doesn't htmlquote the first argument...
1451 1452 1453 1454 1455 1456
sub link($$) {
	my ($name, $url) = @_;

	$url =~ s/:/sprintf("%%%02x", ord($&))/eg
	    if $url =~ /^[^a-z]/;    # relative

1457
	sprintf '<a href="%s">%s</a>', hrefquote($url), $name;
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
}

sub revcmp($$) {
	my ($rev1, $rev2) = @_;

	# make no comparison for a tag or a branch
	return 0 if $rev1 =~ /[^\d.]/ || $rev2 =~ /[^\d.]/;

	my (@r1) = split (/\./, $rev1);
	my (@r2) = split (/\./, $rev2);
	my ($a, $b);

	while (($a = shift (@r1)) && ($b = shift (@r2))) {
		if ($a != $b) {
			return $a <=> $b;
		}
	}
	if (@r1) { return 1; }
	if (@r2) { return -1; }
	return 0;
}

1480 1481
sub fatal($$@) {
	my ($errcode, $format, @args) = @_;
1482 1483 1484 1485 1486 1487
	if ($is_mod_perl) {
		Apache->request->status((split (/ /, $errcode))[0]);
	} else {
		print "Status: $errcode\r\n";
	}
	html_header("Error");
1488 1489 1490 1491
	print "<p>Error: ",
	  sprintf($format, map(htmlquote($_), @args)),
	  "</p>\n";
	html_footer();
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
	exit(1);
}

sub redirect($) {
	my ($url) = @_;
	if ($is_mod_perl) {
		Apache->request->status(301);
		Apache->request->header_out(Location => $url);
	} else {
		print "Status: 301 Moved\r\n";
		print "Location: $url\r\n";
	}
	html_header("Moved");
1505 1506
	print "<p>This document is located ", &link('here', $url), "</p>\n";
	html_footer();
1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
	exit(1);
}

sub safeglob($) {
	my ($filename) = @_;
	my ($dirname);
	my (@results);
	my $dh = do { local (*DH); };

	($dirname = $filename) =~ s|/[^/]+$||;
	$filename =~ s|.*/||;

	if (opendir($dh, $dirname)) {
		my $glob = $filename;
		my $t;

		#	transform filename from glob to regex.  Deal with:
		#	[, {, ?, * as glob chars
		#	make sure to escape all other regex chars
		$glob =~ s/([\.\(\)\|\+])/\\$1/g;
		$glob =~ s/\*/.*/g;
		$glob =~ s/\?/./g;
		$glob =~ s/{([^}]+)}/($t = $1) =~ s-,-|-g; "($t)"/eg;
		foreach (readdir($dh)) {

			if (/^${glob}$/) {
				push (@results, "$dirname/" . $_);
			}
		}
		closedir($dh);
	}

	@results;
}

sub search_path($) {
	my ($command) = @_;
	my $d;

	for $d (split (/:/, $command_path)) {
		return "$d/$command" if -x "$d/$command";
	}

	'';
}

sub getMimeTypeFromSuffix($) {
	my ($fullname) = @_;
	my ($mimetype, $suffix);
	my $fh = do { local (*FH); };

	($suffix = $fullname) =~ s/^.*\.([^.]*)$/$1/;
	$mimetype = $MTYPES{$suffix};
	$mimetype = $MTYPES{'*'} if (!$mimetype);

	if (!$mimetype && -f $mime_types) {

		# okey, this is something special - search the
		# mime.types database
		open($fh, "<$mime_types");
		while (<$fh>) {
			if ($_ =~ /^\s*(\S+\/\S+).*\b$suffix\b/) {
				$mimetype = $1;
				last;
			}
		}
		close($fh);
	}

	# okey, didn't find anything useful ..
	if (!($mimetype =~ /\S\/\S/)) {
		$mimetype = "text/plain";
	}
	return $mimetype;
}

###############################
# read first lines like head(1)
###############################
sub head($;$) {
	my $fh        = $_[0];
	my $linecount = $_[1] || 10;

	my @buf;

	if ($linecount > 0) {
		my $i;
		for ($i = 0 ; !eof($fh) && $i < $linecount ; $i++) {
			push @buf, scalar <$fh>;
		}
	} else {
		@buf = <$fh>;
	}

	@buf;
}

###############################
# scan vim and Emacs directives
###############################
sub scan_directives(@) {
	my $ts = undef;

	for (@_) {
		$ts = $1 if /\b(?:ts|tabstop|tab-width)[:=]\s*([1-9]\d*)\b/;
	}

	('tabstop' => $ts);
}

sub openOutputFilter() {
	return if !defined($output_filter) || $output_filter eq '';

1620
	open(STDOUT, "|-") and return;
1621 1622 1623

	# child of child
	open(STDERR, '>/dev/null');
1624
	exec($output_filter) or exit -1;
1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
}

###############################
# show Annotation
###############################
sub doAnnotate($$) {
	my ($rev) = @_;
	my ($pid);
	my ($pathname, $filename);
	my $reader = do { local (*FH); };
	my $writer = do { local (*FH); };

	# make sure the revisions are wellformed, for security
	# reasons ..
	if ($rev =~ /[^\w.]/) {
1640 1641 1642
		fatal("404 Not Found",
		      'Malformed query "%s"',
		      $ENV{QUERY_STRING});
1643 1644 1645 1646 1647 1648 1649 1650 1651
	}

	($pathname = $where) =~ s/(Attic\/)?[^\/]*$//;
	($filename = $where) =~ s/^.*\///;

	# this seems to be necessary
	$| = 1;
	$| = 0;    # Flush

1652 1653 1654 1655 1656 1657 1658 1659
	# Work around a mod_perl bug (?) in order to make open2() work.
	# Search for "untie STDIN" in mod_perl mailing list archives.
	my $old_stdin;
	if ($is_mod_perl && ($old_stdin = tied *STDIN)) {
	  local $^W = undef;
	  untie *STDIN;
	}

1660 1661 1662 1663 1664 1665
	# this annotate version is based on the
	# cvs annotate-demo Perl script by Cyclic Software
	# It was written by Cyclic Software, http://www.cyclic.com/, and is in
	# the public domain.
	# we could abandon the use of rlog, rcsdiff and co using
	# the cvsserver in a similiar way one day (..after rewrite)
1666 1667 1668 1669 1670 1671
	$pid = open2($reader, $writer, $CMD{cvs}, @annotate_options, 'server')
	    or fatal("500 Internal Error",
		     'Fatal Error - unable to open cvs for annotation');

	# Re-tie STDIN if we fiddled around with it earlier, just to be sure.
	tie(*STDIN, ref($old_stdin), $old_stdin) if ($old_stdin && !tied(*STDIN));
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725

	# OK, first send the request to the server.  A simplified example is:
	#     Root /home/kingdon/zwork/cvsroot
	#     Argument foo/xx
	#     Directory foo
	#     /home/kingdon/zwork/cvsroot/foo
	#     Directory .
	#     /home/kingdon/zwork/cvsroot
	#     annotate
	# although as you can see there are a few more details.

	print $writer "Root $cvsroot\n";
	print $writer
	    "Valid-responses ok error Valid-requests Checked-in Updated Merged Removed M E\n";

	# Don't worry about sending valid-requests, the server just needs to
	# support "annotate" and if it doesn't, there isn't anything to be done.
	print $writer "UseUnchanged\n";
	print $writer "Argument -r\n";
	print $writer "Argument $rev\n";
	print $writer "Argument $where\n";

	# The protocol requires us to fully fake a working directory (at
	# least to the point of including the directories down to the one
	# containing the file in question).
	# So if $where is "dir/sdir/file", then @dirs will be ("dir","sdir","file")
	my @dirs = split ('/', $where);
	my $path = "";
	foreach (@dirs) {

		if ($path eq "") {

			# In our example, $_ is "dir".
			$path = $_;
		} else {
			print $writer "Directory $path\n";
			print $writer "$cvsroot/$path\n";

			# In our example, $_ is "sdir" and $path becomes "dir/sdir"
			# And the next time, "file" and "dir/sdir/file" (which then gets
			# ignored, because we don't need to send Directory for the file).
			$path .= "/$_";
		}
	}

	# And the last "Directory" before "annotate" is the top level.
	print $writer "Directory .\n";
	print $writer "$cvsroot\n";

	print $writer "annotate\n";

	# OK, we've sent our command to the server.  Thing to do is to
	# close the writer side and get all the responses.  If "cvs server"
	# were nicer about buffering, then we could just leave it open, I think.
1726
	close($writer) or die "cannot close: $!";
1727 1728 1729 1730 1731

	http_header();

	navigateHeader($scriptwhere, $pathname, $filename, $rev, "annotate");
	print
1732
	    "<h3 style=\"text-align: center\">Annotation of $pathname$filename, Revision $rev</h3>\n";
1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744

	# Ready to get the responses from the server.
	# For example:
	#     E Annotations for foo/xx
	#     E ***************
	#     M 1.3          (kingdon  06-Sep-97): hello
	#     ok
	my ($lineNr) = 0;
	my ($oldLrev, $oldLusr) = ("", "");
	my ($revprint, $usrprint);

	if ($annTable) {
1745
		print "<table style=\"border: none\" cellspacing=\"0\" cellpadding=\"0\">\n";
1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805
	} else {
		print "<pre>";
	}

	# prefetch several lines
	my @buf = head($reader);

	my %d = scan_directives(@buf);

	while (@buf || !eof($reader)) {
		$_ = @buf ? shift @buf : <$reader>;

		my @words = split;

		# Adding one is for the (single) space which follows $words[0].
		my $rest = substr($_, length($words[0]) + 1);
		if ($words[0] eq "E") {
			next;
		} elsif ($words[0] eq "M") {
			$lineNr++;
			(my $lrev = substr($_, 2,  13)) =~ y/ //d;
			(my $lusr = substr($_, 16, 9))  =~ y/ //d;
			my $line = substr($_, 36);
			my $isCurrentRev = ($rev eq $lrev);

			# we should parse the date here ..
			if ($lrev eq $oldLrev) {
				$revprint = sprintf('%-8s', '');
			} else {
				$revprint = sprintf('%-8s', $lrev);
				$revprint =~
				    s`\S+`&link($&, "$scriptwhere$query#rev$&")`e
				    ;    # `
				$oldLusr = '';
			}

			if ($lusr eq $oldLusr) {
				$usrprint = '';
			} else {
				$usrprint = $lusr;
			}
			$oldLrev = $lrev;
			$oldLusr = $lusr;

			# Set bold for text-based browsers only - graphical
			# browsers show bold fonts a bit wider than regular fonts,
			# so it looks irregular.
			print "<b>" if ($isCurrentRev && $is_textbased);

			printf "%s%s %-8s %4d:", $revprint,
			    $isCurrentRev ? '!' : ' ', $usrprint, $lineNr;
			print spacedHtmlText($line, $d{'tabstop'});

			print "</b>" if ($isCurrentRev && $is_textbased);
		} elsif ($words[0] eq "ok") {

			# We could complain about any text received after this, like the
			# CVS command line client.  But for simplicity, we don't.
		} elsif ($words[0] eq "error") {
			fatal("500 Internal Error",
1806 1807
			      'Error occured during annotate: <b>%s</b>',
			      $_);
1808 1809 1810 1811 1812 1813 1814 1815
		}
	}

	if ($annTable) {
		print "</table>";
	} else {
		print "</pre>";
	}
1816 1817 1818
	html_footer();

	close($reader) or warn "cannot close: $!";
1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836
	wait;
}

###############################
# make Checkout
###############################
sub doCheckout($$) {
	my ($fullname, $rev) = @_;
	my ($mimetype, $revopt);
	my $fh = do { local (*FH); };

	if ($rev eq 'HEAD' || $rev eq '.') {
		$rev = undef;
	}

	# make sure the revisions a wellformed, for security
	# reasons ..
	if (defined($rev) && $rev =~ /[^\w.]/) {
1837 1838 1839
		fatal("404 Not Found",
		      'Malformed query "%s"',
		      $ENV{QUERY_STRING});
1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
	}

	# get mimetype
	if (defined($input{"content-type"})
	    && ($input{"content-type"} =~ /\S\/\S/))
	{
		$mimetype = $input{"content-type"}
	} else {
		$mimetype = &getMimeTypeFromSuffix($fullname);
	}

	if (defined($rev)) {
		$revopt = "-r$rev";
		if ($use_moddate) {
			readLog($fullname, $rev);
			$moddate = $date{$rev};
		}
	} else {
		$revopt = "-rHEAD";

		if ($use_moddate) {
			readLog($fullname);
			$moddate = $date{$symrev{HEAD}};
		}
	}

	### just for the record:
	### 'cvs co' seems to have a bug regarding single checkout of
	### directories/files having spaces in it;
	### this is an issue that should be resolved on cvs's side
	#
	# Safely for a child process to read from.
	if (!open($fh, "-|")) {    # child
		 # chdir to $tmpdir before to avoid non-readable cgi-bin directories
		chdir($tmpdir);
		open(STDERR, ">&STDOUT");    # Redirect stderr to stdout
1876 1877 1878 1879 1880 1881 1882

		# work around a bug of cvs -p; expand symlinks
		use Cwd 'abs_path';
		exec($CMD{cvs}, @cvs_options,
		     '-d', abs_path($cvsroot),
		     'co', '-p',
		     $revopt, $where) or exit -1;
1883 1884 1885
	}

	if (eof($fh)) {
1886 1887 1888
		fatal("404 Not Found",
		      '%s is not (any longer) pertinent',
		      $where);
1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911
	}

	#===================================================================
	#Checking out squid/src/ftp.c
	#RCS:  /usr/src/CVS/squid/src/ftp.c,v
	#VERS: 1.1.1.28.6.2
	#***************

	# Parse CVS header
	my ($revision, $filename, $cvsheader);
	$filename = "";
	while (<$fh>) {
		last if (/^\*\*\*\*/);
		$revision = $1 if (/^VERS: (.*)$/);

		if (/^Checking out (.*)$/) {
			$filename = $1;
			$filename =~ s/^\.\/*//;
		}
		$cvsheader .= $_;
	}

	if ($filename ne $where) {
1912 1913 1914
		fatal("500 Internal Error",
		      'Unexpected output from cvs co: %s',
		      $cvsheader);
1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937
	}
	$| = 1;

	if ($mimetype eq "text/x-cvsweb-markup") {
		&cvswebMarkup($fh, $fullname, $revision);
	} else {
		http_header($mimetype);
		print <$fh>;
	}
	close($fh);
}

sub cvswebMarkup($$$) {
	my ($filehandle, $fullname, $revision) = @_;
	my ($pathname,   $filename);

	($pathname = $where) =~ s/(Attic\/)?[^\/]*$//;
	($filename = $where) =~ s/^.*\///;
	my ($fileurl) = urlencode($filename);

	http_header();

	navigateHeader($scriptwhere, $pathname, $filename, $revision, "view");
1938 1939
	print "<hr noshade>";
	print "<table width=\"100%\">\n<tr>\n<td style=\"background-color: $markupLogColor\">";
1940 1941 1942 1943 1944 1945 1946 1947 1948 1949
	print "File: ", &clickablePath($where, 1);
	print "&nbsp;(";
	&download_link($fileurl, $revision, "download");
	print ")";

	if (!$defaultTextPlain) {
		print "&nbsp;(";
		&download_link($fileurl, $revision, "as text", "text/plain");
		print ")";
	}
1950
	print "<br>\n";
1951 1952 1953 1954 1955

	if ($show_log_in_markup) {
		readLog($fullname);    #,$revision);
		printLog($revision, 0);
	} else {
1956 1957
		print "Version: <b>$revision</b><br>\n";
		print "Tag: <b>", $input{only_with_tag}, "</b><br>\n"
1958 1959
		    if $input{only_with_tag};
	}
1960
	print "</td>\n</tr>\n</table>";
1961
	my $url = download_url($fileurl, $revision, $mimetype);
1962
	print "<hr noshade>";
1963 1964

	if ($mimetype =~ /^image/) {
1965
		printf '<img src="%s" alt=""><br>', hrefquote("$url$barequery");
1966
	} elsif ($mimetype =~ m%^application/pdf%) {
1967
		printf '<embed src="%s" width="100%"><br>',
1968 1969
		    hrefquote("$url$barequery");
	} elsif ($preformat_in_markup) {
1970
		print "<pre>";
1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981

		# prefetch several lines
		my @buf = head($filehandle);

		my %d = scan_directives(@buf);

		while (@buf || !eof($filehandle)) {
			$_ = @buf ? shift @buf : <$filehandle>;

			print spacedHtmlText($_, $d{'tabstop'});
		}
1982
		print "</pre>";
1983
	} else {
1984
		print "<pre>";
1985 1986 1987 1988

		while (<$filehandle>) {
			print htmlquote($_);
		}
1989
		print "</pre>";
1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007
	}
}

sub viewable($) {
	my ($mimetype) = @_;

	$mimetype =~ m%^((text|image)/|application/pdf)%;
}

###############################
# Show Colored Diff
###############################
sub doDiff($$$$$$) {
	my ($fullname, $r1, $tr1, $r2, $tr2, $f) = @_;
	my $fh = do { local (*FH); };
	my ($rev1, $rev2, $sym1, $sym2, $f1, $f2);

	if (&forbidden_file($fullname)) {
2008 2009
		fatal("403 Forbidden",
		      'Access forbidden.  This file is mentioned in @ForbiddenFiles');
2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033
		return;
	}

	if ($r1 =~ /([^:]+)(:(.+))?/) {
		$rev1 = $1;
		$sym1 = $3;
	}
	if ($r1 eq 'text') {
		$rev1 = $tr1;
		$sym1 = "";
	}

	if ($r2 =~ /([^:]+)(:(.+))?/) {
		$rev2 = $1;
		$sym2 = $3;
	}
	if ($r2 eq 'text') {
		$rev2 = $tr2;
		$sym2 = "";
	}

	# make sure the revisions a wellformed, for security
	# reasons ..
	if ($rev1 =~ /[^\w.]/ || $rev2 =~ /[^\w.]/) {
2034 2035 2036
		fatal("404 Not Found",
		      'Malformed query "%s"',
		      $ENV{QUERY_STRING});
2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050
	}

	#
	# rev1 and rev2 are now both numeric revisions.
	# Thus we do a DWIM here and swap them if rev1 is after rev2.
	# XXX should we warn about the fact that we do this?
	if (&revcmp($rev1, $rev2) > 0) {
		my ($tmp1, $tmp2) = ($rev1, $sym1);
		($rev1, $sym1) = ($rev2, $sym2);
		($rev2, $sym2) = ($tmp1, $tmp2);
	}
	my $difftype = $DIFFTYPES{$f};

	if (!$difftype) {
2051 2052 2053
		fatal("400 Bad arguments",
		      'Diff format %s not understood',
		      $f);
2054 2055 2056 2057 2058 2059 2060
	}

	my @difftype       = @{$difftype->{'opts'}};
	my $human_readable = $difftype->{'colored'};

	# apply special options
	if ($showfunc) {
2061
		push @difftype, '-p' if $f ne 's';
2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084

		my ($re1, $re2);

		while (($re1, $re2) = each %funcline_regexp) {
			if ($fullname =~ /$re1/) {
				push @difftype, '-F', $re2;
				last;
			}
		}
	}

	if ($human_readable) {
		if ($hr_ignwhite) {
			push @difftype, '-w';
		}
		if ($hr_ignkeysubst) {
			push @difftype, '-kk';
		}
	}

	if (!open($fh, "-|")) {    # child
		open(STDERR, ">&STDOUT");    # Redirect stderr to stdout
		openOutputFilter();
2085
		exec($CMD{rcsdiff}, @difftype, "-r$rev1", "-r$rev2", $fullname) or exit -1;
2086 2087 2088 2089
	}
	if ($human_readable) {
		http_header();
		&human_readable_diff($fh, $rev2);
2090
		html_footer();
2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159
		gzipclose();
		exit;
	} else {
		http_header("text/plain");
	}

	#
	#===================================================================
	#RCS file: /home/ncvs/src/sys/netinet/tcp_output.c,v
	#retrieving revision 1.16
	#retrieving revision 1.17
	#diff -c -r1.16 -r1.17
	#*** /home/ncvs/src/sys/netinet/tcp_output.c     1995/11/03 22:08:08     1.16
	#--- /home/ncvs/src/sys/netinet/tcp_output.c     1995/12/05 17:46:35     1.17
	#
	# Ideas:
	# - nuke the stderr output if it's what we expect it to be
	# - Add "no differences found" if the diff command supplied no output.
	#
	#*** src/sys/netinet/tcp_output.c     1995/11/03 22:08:08     1.16
	#--- src/sys/netinet/tcp_output.c     1995/12/05 17:46:35     1.17 RELENG_2_1_0
	# (bogus example, but...)
	#
	if (grep { $_ eq '-u' } @difftype) {
		$f1 = '---';
		$f2 = '\+\+\+';
	} else {
		$f1 = '\*\*\*';
		$f2 = '---';
	}

	while (<$fh>) {
		if (m|^$f1 $cvsroot|o) {
			s|$cvsroot/||o;
			if ($sym1) {
				chop;
				$_ .= " $sym1\n";
			}
		} elsif (m|^$f2 $cvsroot|o) {
			s|$cvsroot/||o;

			if ($sym2) {
				chop;
				$_ .= " $sym2\n";
			}
		}
		print $_;
	}
	close($fh);
}

###############################
# Show Logs ..
###############################
sub getDirLogs($$@) {
	my ($cvsroot, $dirname, @otherFiles) = @_;
	my ($state, $otherFiles, $tag, $file, $date, $branchpoint, $branch,
	    $log);
	my ($rev, $revision, $revwanted, $filename, $head, $author);

	$tag = $input{only_with_tag};

	my ($DirName) = "$cvsroot/$where";
	my (@files, @filetags);
	my $fh = do { local (*FH); };

	push (@files, &safeglob("$DirName/*,v"));
	push (@files, &safeglob("$DirName/Attic/*,v"))
	    if (!$input{'hideattic'});
2160
	foreach my $file (@otherFiles) {
2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
		push (@files, "$DirName/$file");
	}

	# just execute rlog if there are any files
	if ($#files < 0) {
		return;
	}

	if (defined($tag)) {

		#can't use -r<tag> as - is allowed in tagnames, but misinterpreated by rlog..
		if (!open($fh, "-|")) {    # child
			open(STDERR, '>/dev/null'); # rlog may complain; ignore.
			openOutputFilter();
2175
			exec($CMD{rlog}, @files) or exit -1;
2176 2177 2178 2179 2180 2181
		}
	} else {

		if (!open($fh, "-|")) {    # child
			open(STDERR, '>/dev/null'); # rlog may complain; ignore.
			openOutputFilter();
2182
			exec($CMD{rlog}, '-r', @files) or exit -1;
2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239
		}
	}
	$state = "start";

	while (<$fh>) {
		if ($state eq "start") {

			#Next file. Initialize file variables
			$rev         = '';
			$revwanted   = '';
			$branch      = '';
			$branchpoint = '';
			$filename    = '';
			$log         = '';
			$revision    = '';
			%symrev      = ();
			@filetags    = ();

			#jump to head state
			$state = "head";
		}
		print "$state:$_" if ($verbose);
		again:

		if ($state eq "head") {

			#$rcsfile = $1 if (/^RCS file: (.+)$/); #not used (yet)

			if (/^Working file: (.+)$/) {
				$filename = $1;
			} elsif (/^head: (.+)$/) {
				$head = $1;
			} elsif (/^branch: (.+)$/) {
				$branch = $1
			} elsif (/^symbolic names:/) {
				$state = "tags";
				($branch = $head) =~ s/\.\d+$//
				    if $branch eq '';
				$branch =~ s/(\d+)$/0.$1/;
				$symrev{MAIN}  = $branch;
				$symrev{HEAD}  = $branch;
				$alltags{MAIN} = 1;
				$alltags{HEAD} = 1;
				push (@filetags, "MAIN", "HEAD");
			} elsif (/$LOG_REVSEPARATOR/o) {
				$state = "log";
				$rev   = '';
				$date  = '';
				$log   = '';

				# Try to reconstruct the relative filename if RCS spits out a full path
				$filename =~ s%^\Q$DirName\E/%%;
			}
			next;
		}

		if ($state eq "tags") {
2240
			if (/^\s+([^:]+):\s+([\d\.]+)\s*$/) {
2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331
				push (@filetags, $1);
				$symrev{$1}  = $2;
				$alltags{$1} = 1;
				next;
			} elsif (/^\S/) {

				if (defined($tag)) {
					if (defined($symrev{$tag})
					    || $tag eq "HEAD")
					{
						$revwanted =
						    $symrev{$tag eq "HEAD" ?
						    "MAIN" : $tag};
						($branch = $revwanted) =~
						    s/\b0\.//;
						($branchpoint = $branch) =~
						    s/\.?\d+$//;
						$revwanted = ''
						    if ($revwanted ne $branch);
					} elsif ($tag ne "HEAD") {
						print
						    "Tag not found, skip this file"
						    if ($verbose);
						$state = "skip";
						next;
					}
				}

				foreach my $tagfound (@filetags) {
					$tags{$tagfound} = 1;
				}
				$state = "head";
				goto again;
			}
		}

		if ($state eq "log") {
			if (/$LOG_REVSEPARATOR/o || /$LOG_FILESEPARATOR/o) {

				# End of a log entry.
				my $revbranch = $rev;
				$revbranch =~ s/\.\d+$//;
				print "$filename $rev Wanted: $revwanted ",
				    "Revbranch: $revbranch Branch: $branch ",
				    "Branchpoint: $branchpoint\n"
				    if ($verbose);

				if ($revwanted eq '' && $branch ne ''
				    && $branch eq $revbranch || !defined($tag))
				{
					print
					    "File revision $rev found for branch $branch\n"
					    if ($verbose);
					$revwanted = $rev;
				}

				if ($revwanted ne '' ? $rev eq $revwanted :
				    $branchpoint ne '' ? $rev eq $branchpoint :
				    0 && ($rev eq $head))
				{    # Don't think head is needed here..
					print
					    "File info $rev found for $filename\n"
					    if ($verbose);
					my @finfo =
					    ($rev, $date, $log, $author,
						$filename);
					my ($name);
					($name = $filename) =~ s%/.*%%;
					$fileinfo{$name} = [@finfo];
					$state = "done" if ($rev eq $revwanted);
				}
				$rev  = '';
				$date = '';
				$log  = '';
			} elsif ($date eq ''
			    && m|^date:\s+(\d+)/(\d+)/(\d+)\s+(\d+):(\d+):(\d+);|
			    )
			{
				my $yr = $1;

				# damn 2-digit year routines :-)
				if ($yr > 100) {
					$yr -= 1900;
				}
				$date =
				    &Time::Local::timegm($6, $5, $4, $3, $2 - 1,
					$yr);
				($author) = /author: ([^;]+)/;
				$state = "log";
				$log   = '';
				next;
2332 2333
			} elsif ($rev eq '' && /^revision (\d+(?:\.\d+)+).*$/) {
				$rev = $1; # .*$ eats up the locker(lockers?) info, if any
2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346
				next;
			} else {
				$log .= $_;
			}
		}

		if (/$LOG_FILESEPARATOR/o) {
			$state = "start";
			next;
		}
	}

	if ($. == 0) {
2347 2348 2349
		fatal("500 Internal Error",
		      'Failed to spawn GNU rlog on <em>"%s"</em>.  <p>Did you set the <b>$command_path</b> in your configuration file correctly ? (Currently "%s"',
		      join (", ", @files), $command_path);
2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377
	}
	close($fh);
}

sub readLog($;$) {
	my ($fullname, $revision) = @_;
	my ($symnames, $head, $rev, $br, $brp, $branch, $branchrev);
	my $fh = do { local (*FH); };

	if (defined($revision)) {
		$revision = "-r$revision";
	} else {
		$revision = "";
	}

	undef %symrev;
	undef %revsym;
	undef @allrevisions;
	undef %date;
	undef %author;
	undef %state;
	undef %difflines;
	undef %log;

	print("Going to rlog '$fullname'\n") if ($verbose);
	if (!open($fh, "-|")) {    # child
		if ($revision ne '') {
			openOutputFilter();
2378
			exec($CMD{rlog}, $revision, $fullname) or exit -1;
2379 2380
		} else {
			openOutputFilter();
2381
			exec($CMD{rlog}, $fullname) or exit -1;
2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410
		}
	}

	while (<$fh>) {
		print if ($verbose);
		if ($symnames) {
			if (/^\s+([^:]+):\s+([\d\.]+)/) {
				$symrev{$1} = $2;
			} else {
				$symnames = 0;
			}
		} elsif (/^head:\s+([\d\.]+)/) {
			$head = $1;
		} elsif (/^branch:\s+([\d\.]+)/) {
			$curbranch = $1;
		} elsif (/^symbolic names/) {
			$symnames = 1;
		} elsif (/^-----/) {
			last;
		}
	}
	($curbranch = $head) =~ s/\.\d+$// if (!defined($curbranch));

	# each log entry is of the form:
	# ----------------------------
	# revision 3.7.1.1
	# date: 1995/11/29 22:15:52;  author: fenner;  state: Exp;  lines: +5 -3
	# log info
	# ----------------------------
2411 2412 2413 2414 2415

	# For a locked revision, the first line after the separator 
	# becomes smth like
	# revision 9.19	locked by: vassilii;

2416 2417 2418 2419