#!/usr/bin/env python
"""
TAAC - TAAC Ain't Access Control CGI Proxy

This script acts as a filter to all requests for files within this
directory.  If a file is associated with a policy in ./policies.n3, it will
send a 401 error requiring FOAF+SSL authentication.

This gateway uses a standard CGI setup.  See proxy.py for a mod_python setup.
"""

import os
import httplib
import logging

from taac.server import TAACServer
from taac.tmswap import uripath
import taac.util

def do_access():
    "Perform access control."
    base_uri = ''
    if (os.environ.has_key('HTTPS') and \
        os.environ['HTTPS'] == 'on'):
        base_uri = "https://%s" % (os.environ['SERVER_NAME'])
        if os.environ['SERVER_PORT'] == '443':
            base_uri += '/'
        else:
            base_uri += ':%s/' % (os.environ['SERVER_PORT'])
    else:
        base_uri = "http://%s" % (os.environ['SERVER_NAME'])
        if os.environ['SERVER_PORT'] == '80':
            base_uri += '/'
        else:
            base_uri += ':%s/' % (os.environ['SERVER_PORT'])
    
    # Now, append the relative URI from the request.
    base_uri = uripath.join(base_uri, os.path.dirname(os.environ['REQUEST_URI']) + '/')
    base_path = os.path.dirname(os.path.abspath(__file__)) + '/'
    
    # Change the working directory.
    os.chdir(base_path)

    # Create the TAACServer object...
    logging.basicConfig(level=logging.DEBUG)
    server = TAACServer(base_uri, base_path, os.environ,
                        logging.StreamHandler())

    # And try checking for valid access.
    retval = server.allow_access(os.environ.get('QUERY_STRING', ''))

    # WARNING: This CGI assumes that no rewriting to this proxy is
    # done when accessed locally.  Otherwise, we get an infinite loop.

    # We also need the HTTPS variable set if we're behind a secure connection.
    if retval == taac.util.HTTP_OK:
        # Make another request and pipe the result.
        if 'HTTPS' in os.environ and os.environ['HTTPS'] == 'on':
            conn = httplib.HTTPSConnection(os.environ['SERVER_NAME'],
                                           int(os.environ['SERVER_PORT']))
        else:
            conn = httplib.HTTPConnection(os.environ['SERVER_NAME'],
                                          int(os.environ['SERVER_PORT']))
        # TODO: Support piping POSTS and other requests.
        conn.request("GET", os.environ['REQUEST_URI'])
        resp = conn.getresponse()
        print 'Status:', resp.status, resp.reason
        for header in resp.getheaders():
            print header[0] + ': ' + header[1]
        print
        print resp.read()
        conn.close()
    else:
        print 'Status:', retval
        print 'Content-type: text/html'
        print
        print taac.util.error_body[retval]

do_access()
