package HTTP;

$banner = "HTTP/1.0 200 Smile!\r\n";
$mime_header = "Content-type: text/html\r\n\r\n";

sub getmimeheaders { # fd, return (len, string)
    my ($MIMEFD) = @_;
    my ($line, $length);
    $line = "";
    # read and echo MIME headers; watch for Content-Length: header
    while (<$MIMEFD>) {
	$line .= $_;
	/^Content-Length:\s*(.*)\r$/i && ($length = $1);
	last if /^\r$/; # blank line ends MIME headers
    }
    return ($length, $line);
}

sub getmimecontent { # fd, return string
    my($MIMEFD,$length) = @_;
    my $line = "";
    if ($length) {
	# read content-length bytes
	$line .= getc($MIMEFD) while ($length--);
    }
    elsif (($reqtype eq "PUT") || ($reqtype eq "POST")) {
	# no content-length, so look for tail line
	while (<$MIMEFD>) {
	    last if /^.\r$/; # line with . only, just like pop
	    $line .= $_;
	}
    }
    return $line;
}

sub getpostfields { # line
    my ($line) = @_;
    my (@fields, %content);
    @fields = split(/&/, $line);
    for $i (@fields) {
	($k, $v) = split(/=/, $i);
	# + are spaces (real + are always encoded as %2B)
	$v =~ s/\+/ /g;
	# %xx are hex. perhaps use /i here?
	$v =~ s/%([0-9A-Fa-f][0-9A-Fa-f])/pack("H2","$1$2")/eg;
	$content{$k} = $v;
	# print "$k set to $v\r\n";
    }
    return %content;
}

1;
