#!/usr/local/bin/perl
# link.cgi
# Forward the URL from path_info on to another webmin server

require './servers-lib.pl';
$ENV{'PATH_INFO'} =~ /^\/(\d+)(.*)$/ ||
	&error("Bad PATH_INFO : $ENV{'PATH_INFO'}");
$path = $2 ? $2 : '/';
if ($ENV{'QUERY_STRING'}) {
	$path .= '?'.$ENV{'QUERY_STRING'};
	}
elsif (@ARGV) {
	$path .= '?'.join('+', @ARGV);
	}
$s = &get_server($1);
&can_use_server($s) || &error($text{'link_ecannot'});
$url = "/$module_name/link.cgi/$s->{'id'}";
$| = 1;
$meth = $ENV{'REQUEST_METHOD'};

# Connect to the server
$con = &make_http_connection($s->{'host'}, $s->{'port'}, $s->{'ssl'},
			     $meth, $path);
&error($con) if (!ref($con));

# Send request headers
&write_http_connection($con, "Host: $s->{'host'}\r\n");
&write_http_connection($con, "User-agent: Webmin\r\n");
$auth = &encode_base64("$s->{'user'}:$s->{'pass'}");
$auth =~ s/\n//g;
&write_http_connection($con, "Authorization: basic $auth\r\n");
&write_http_connection($con, sprintf(
			"Webmin-servers: %s://%s:%d/$module_name/\n",
			$ENV{'HTTPS'} eq "ON" ? "https" : "http",
			$ENV{'SERVER_NAME'}, $ENV{'SERVER_PORT'}));
$cl = $ENV{'CONTENT_LENGTH'};
&write_http_connection($con, "Content-length: $cl\r\n") if ($cl);
&write_http_connection($con, "Content-type: $ENV{'CONTENT_TYPE'}\r\n")
	if ($ENV{'CONTENT_TYPE'});
&write_http_connection($con, "\r\n");
if ($cl) {
	read(STDIN, $post, $cl);
	&write_http_connection($con, $post);
	}

# read back the headers
$dummy = &read_http_connection($con);
while(1) {
	($headline = &read_http_connection($con)) =~ s/\r|\n//g;
	last if (!$headline);
	$headline =~ /^(\S+):\s+(.*)$/ || &error("Bad header");
	$header{lc($1)} = $2;
	$headers .= $headline."\n";
	}

$defport = $s->{'ssl'} ? 443 : 80;
if ($header{'location'} =~ /^(http|https):\/\/$s->{'host'}:$s->{'port'}(.*)$/ ||
    $header{'location'} =~ /^(http|https):\/\/$s->{'host'}(.*)/ &&
    $s->{'port'} == $defport) {
	# fix a redirect
	&redirect("$url$2");
	exit;
	}
elsif ($header{'www-authenticate'}) {
	# Invalid login
	&error(&text('link_elogin', $s->{'host'}, $s->{'user'}));
	}
else {
	# just output the headers
	print $headers,"\n";
	}

# read back the rest of the page
if ($header{'content-type'} =~ /text\/html/) {
	while($_ = &read_http_connection($con)) {
		s/src='(\/[^']*)'/src='$url$1'/gi;
		s/src="(\/[^"]*)"/src="$url$1"/gi;
		s/src=(\/[^ "'>]*)/src=$url$1/gi;
		s/href='(\/[^']*)'/href='$url$1'/gi;
		s/href="(\/[^"]*)"/href="$url$1"/gi;
		s/href=(\/[^ >"']*)/href=$url$1/gi;
		s/action='(\/[^']*)'/action='$url$1'/gi;
		s/action="(\/[^"]*)"/action="$url$1"/gi;
		s/action=(\/[^ "'>]*)/action=$url$1/gi;
		s/\.location\s*=\s*'(\/[^']*)'/.location='$url$1'/gi;
		s/\.location\s*=\s*"(\/[^']*)"/.location="$url$1"/gi;
		s/window.open\("(\/[^"]*)"/window.open\("$url$1"/gi;
		s/name=return\s+value="(\/[^"]*)"/name=return value="$url$1"/gi;
		print;
		}
	}
else {
	while($buf = &read_http_connection($con, 1024)) {
		print $buf;
		}
	}
&close_http_connection($con);

