#!/usr/bin/python
""" $Id: headers,v 1.9 2014-01-30 19:02:00 brett Exp $
Maintainer: dom@w3.org
"""

import cgi
import sys
import os
import urlparse
import urllib
import http_head
import http_auth
import string

from cleanhtml import *

Page1 = """Content-Type: text/html; charset=utf-8

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
<head>
<link href="http://www.w3.org/StyleSheets/base" rel="stylesheet"/>

<title>HTTP HEAD service%s</title></head>
<body>

<p><a href="http://www.w3.org/"><img src="http://www.w3.org/Icons/w3c_home" alt="W3C"/></a></p>

<h1>HTTP Head%s</h1>
<h2>Description</h2>
<p>This tool takes the URI of a document as input and outputs the HTTP headers sent by the server for this resource.</p>
"""

Page2 = """
<form method="get" action="headers">
<p>
<label>URI of the document: <input type="text" name="url" value="%s"/></label><br />
<label>Proxy basic authentication for protected resources: <input type="checkbox" name="auth" %s/></label><br />
<!-- <label>Forward my browser's HTTP headers: <input type="checkbox" name="forward" %s/></label><br />-->
<input type="submit" value="Get results"/></p>
</form>
<p>Note that this script doesn't transmit your browsers HTTP headers when doing the request.</p>
<p>See also the <a href="http://dev.w3.org/cvsweb/2000/tidy-svc/">underlying Python scripts</a>.</p>
<hr />
<address>
script $Revision: 1.9 $ of $Date: 2014-01-30 19:02:00 $<br />
by <a href="http://www.w3.org/People/Dom/">Dominique Hazael-Massieux</a><br />
</address>
</body>
</html>
"""

class myURLopener(http_head.HEADURLopener,http_auth.ProxyAuthURLopener):
	def __init__(self,auth=0,*args):
		self.auth = auth
		apply(http_auth.ProxyAuthURLopener.__init__, (self,) + args)

	def http_error_default(self, url, fp, errcode, errmsg, headers):
		return None

	def http_error(self, url, fp, errcode, errmsg, headers, data=None):
		formatHeaders(errcode,errmsg,headers)
		return urllib.URLopener.http_error(self, url, fp, errcode, errmsg, headers, data)		

	def retry_http_basic_auth(self, url, realm, data=None):
                if self.auth==1:
                        return http_auth.ProxyAuthURLopener.retry_http_basic_auth(self,url,realm,data)
		else:
			return None

	def retry_https_basic_auth(self, url, realm, data=None):
                if self.auth==1:
                        return http_auth.ProxyAuthURLopener.retry_https_basic_auth(self,url,realm,data)
		else:
			return None


def formatHeaders(errcode,errmsg,headers):
	res = [clean_format("<span class='errcode'>%s</span> <span class='errmsg'>%s</span>", `errcode`, errmsg)]
	for key in headers.keys():
		headerName = '-'.join(word.capitalize()
                                      for word in key.split('-'))
		res.append(clean_format("<span class='headername'>%s</span>: <span class='headervalue'>%s</span>", headerName, headers[key]))
	res.append('')
	return "\n".join(res)


def serveRequest():
    fields = cgi.FieldStorage()
    uri = fields.getfirst('url')
    if uri is None:
            print Page1 % ("","")
            print Page2 % ("","","")
            sys.exit()
    auth = (fields.getfirst('auth', '') == 'on')
    if auth:
            auth_text = "checked='checked'"
    else:
            auth_text = ""
    url_opener = myURLopener(auth)
    remote_addr = os.environ.get('REMOTE_ADDR')
    if remote_addr:
            url_opener.addheader('X_Fwd_IP_Addr', remote_addr)
    try:	
            fp = url_opener.open(uri)
    except IOError as e:
            url_opener.error = "I/O error: %s %s" % (e.errno,e.strerror)
            fp = None
    esc_uri = clean_str(uri)
    title = " for %s" % (esc_uri)
    link = " for <a href='%s'>%s</a>" % (esc_uri, esc_uri)
    print Page1 % (title,link)
    print '<h2>Results</h2>\n<pre>'
    if fp:
            print formatHeaders(200,"OK",fp.info())
            fp.close()
    else:
            clean_print("An error occured %s", url_opener.error)
    print '</pre>'
    print Page2 % (esc_uri, auth_text, "")

if __name__ == '__main__':
    if os.environ.has_key('SCRIPT_NAME'):
        serveRequest()
