#!/bin/perl
#Web server.

use Socket;
use FileHandle;   #for autoflush
use POSIX;        #for WIFEXITED, WEEXITSTATUS, etc.

socket(S, PF_INET, SOCK_STREAM, 0)      or die "$0: $!";
bind(S, sockaddr_in(10567, INADDR_ANY)) or die "$0: $!";
listen(S, SOMAXCONN)                    or die "$0: $!";

for (;;) {
	$clientaddress = accept(CLIENT, S);
	defined $clientaddress or die "$0: $!";
	CLIENT->autoflush();

	$pid = fork();
	defined $pid or die "$0: $!";

	if ($pid == 0) {
		#Arrive here if I am the child.
		$first = 1;
		while (($_ = <CLIENT>) ne "\r\n") {   #ne for strings, != for numbers
			print $_;
			s/\r\n$//;   #Remove the trailing carriage return newline.
			if ($first) {
				$first = 0;
				@field = split(/\s+/, $_);  #Don't need the (/\s+/, $_)
				if ($field[0] ne 'GET') {
					die "$0: The first word must be GET";
				}
				$url = $field[1];
			}
		}

		if ($first) {
			die "$0: found EOF before GET";
		}

		print CLIENT "HTTP/1.1 200 OK\n";
		print CLIENT "Content-type: text/html\n";
		print CLIENT "\n";
		#print CLIENT `cat /usr/local/apache-1.3.14/htdocs$url`; #back quotes
		$url =~ s:^/~([a-z]+[0-9]+):/home1/m/\1/public_html:;
		print CLIENT `cat $url`; #back quotes

		shutdown(CLIENT, SHUT_RDWR) or die "$0: $!";
		exit 0;
	}

	#Arrive here if I am the parent.
	close(CLIENT) or die "$0: $1";

	while (($pid = waitpid(-1, WNOHANG)) > 0) {
		print "child pid $pid:";
		if (WIFEXITED($?)) {
			print "The child's exit status is ", WEXITSTATUS($?), "\n";
		} elsif (WIFSIGNALED($?)) {
			print "The child was terminated by signal number ", WTERMSIG($?), "\n";
		} elsif (WIFSTOPPED($?)) {
			print "The child was stopped by signal number ", WSTOPSIG($?), "\n";
		} else {
			die "$0: couldn't find out how child ended up.";
		}
	}
}
