"""Parse the ``Host`` header."""
__docformat__ = "restructuredtext"
# Created: Thu Apr 28 03:07:43 PDT 2005
# Author: Shannon -jj Behrens
# Email: jjinux@users.sourceforge.net
#
# Copyright (c) Shannon -jj Behrens. All rights reserved.
import re
import aquarium.util.Ports as ports
def getHostnameRegex():
"""Return a regex for a valid hostname.
There's not much point in being overly strict about what you'll accept in
the HOST header, so I'll accept anything that's even vaguely similar to a
hostname or IP.
"""
return re.compile("^[a-zA-Z0-9_\-\.]+$")
def parseHost(header=None, defaultReturnValue=(None, None), isSecure=False):
"""Parse the ``Host`` header.
header
This is the value of the ``Host`` header or None.
defaultReturnValue
Return this if the header is absent or malformed.
isSecure
Is the current connection over SSL? This will tell me the default port.
Return a tuple ``(serverName, serverPort)``.
We're not very strict about requiring the ``Host`` header.
See also: Host_
.. _Host:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.23.
"""
if header is None:
return defaultReturnValue
if isSecure:
defaultPort = ports.HTTPS_PORT
else:
defaultPort = ports.HTTP_PORT
(serverName, serverPort) = (header.split(":") + [str(defaultPort)])[:2]
if not getHostnameRegex().match(serverName):
return defaultReturnValue
try:
port = int(serverPort)
except ValueError:
return defaultReturnValue
if port < ports.MIN_PORT or ports.MAX_PORT < port:
return defaultReturnValue
return (serverName, serverPort)
|