OpenSecurity/install/web.py-0.37/web/net.py
changeset 3 65432e6c6042
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/OpenSecurity/install/web.py-0.37/web/net.py	Mon Dec 02 14:02:05 2013 +0100
     1.3 @@ -0,0 +1,193 @@
     1.4 +"""
     1.5 +Network Utilities
     1.6 +(from web.py)
     1.7 +"""
     1.8 +
     1.9 +__all__ = [
    1.10 +  "validipaddr", "validipport", "validip", "validaddr", 
    1.11 +  "urlquote",
    1.12 +  "httpdate", "parsehttpdate", 
    1.13 +  "htmlquote", "htmlunquote", "websafe",
    1.14 +]
    1.15 +
    1.16 +import urllib, time
    1.17 +try: import datetime
    1.18 +except ImportError: pass
    1.19 +
    1.20 +def validipaddr(address):
    1.21 +    """
    1.22 +    Returns True if `address` is a valid IPv4 address.
    1.23 +    
    1.24 +        >>> validipaddr('192.168.1.1')
    1.25 +        True
    1.26 +        >>> validipaddr('192.168.1.800')
    1.27 +        False
    1.28 +        >>> validipaddr('192.168.1')
    1.29 +        False
    1.30 +    """
    1.31 +    try:
    1.32 +        octets = address.split('.')
    1.33 +        if len(octets) != 4:
    1.34 +            return False
    1.35 +        for x in octets:
    1.36 +            if not (0 <= int(x) <= 255):
    1.37 +                return False
    1.38 +    except ValueError:
    1.39 +        return False
    1.40 +    return True
    1.41 +
    1.42 +def validipport(port):
    1.43 +    """
    1.44 +    Returns True if `port` is a valid IPv4 port.
    1.45 +    
    1.46 +        >>> validipport('9000')
    1.47 +        True
    1.48 +        >>> validipport('foo')
    1.49 +        False
    1.50 +        >>> validipport('1000000')
    1.51 +        False
    1.52 +    """
    1.53 +    try:
    1.54 +        if not (0 <= int(port) <= 65535):
    1.55 +            return False
    1.56 +    except ValueError:
    1.57 +        return False
    1.58 +    return True
    1.59 +
    1.60 +def validip(ip, defaultaddr="0.0.0.0", defaultport=8080):
    1.61 +    """Returns `(ip_address, port)` from string `ip_addr_port`"""
    1.62 +    addr = defaultaddr
    1.63 +    port = defaultport
    1.64 +    
    1.65 +    ip = ip.split(":", 1)
    1.66 +    if len(ip) == 1:
    1.67 +        if not ip[0]:
    1.68 +            pass
    1.69 +        elif validipaddr(ip[0]):
    1.70 +            addr = ip[0]
    1.71 +        elif validipport(ip[0]):
    1.72 +            port = int(ip[0])
    1.73 +        else:
    1.74 +            raise ValueError, ':'.join(ip) + ' is not a valid IP address/port'
    1.75 +    elif len(ip) == 2:
    1.76 +        addr, port = ip
    1.77 +        if not validipaddr(addr) and validipport(port):
    1.78 +            raise ValueError, ':'.join(ip) + ' is not a valid IP address/port'
    1.79 +        port = int(port)
    1.80 +    else:
    1.81 +        raise ValueError, ':'.join(ip) + ' is not a valid IP address/port'
    1.82 +    return (addr, port)
    1.83 +
    1.84 +def validaddr(string_):
    1.85 +    """
    1.86 +    Returns either (ip_address, port) or "/path/to/socket" from string_
    1.87 +    
    1.88 +        >>> validaddr('/path/to/socket')
    1.89 +        '/path/to/socket'
    1.90 +        >>> validaddr('8000')
    1.91 +        ('0.0.0.0', 8000)
    1.92 +        >>> validaddr('127.0.0.1')
    1.93 +        ('127.0.0.1', 8080)
    1.94 +        >>> validaddr('127.0.0.1:8000')
    1.95 +        ('127.0.0.1', 8000)
    1.96 +        >>> validaddr('fff')
    1.97 +        Traceback (most recent call last):
    1.98 +            ...
    1.99 +        ValueError: fff is not a valid IP address/port
   1.100 +    """
   1.101 +    if '/' in string_:
   1.102 +        return string_
   1.103 +    else:
   1.104 +        return validip(string_)
   1.105 +
   1.106 +def urlquote(val):
   1.107 +    """
   1.108 +    Quotes a string for use in a URL.
   1.109 +    
   1.110 +        >>> urlquote('://?f=1&j=1')
   1.111 +        '%3A//%3Ff%3D1%26j%3D1'
   1.112 +        >>> urlquote(None)
   1.113 +        ''
   1.114 +        >>> urlquote(u'\u203d')
   1.115 +        '%E2%80%BD'
   1.116 +    """
   1.117 +    if val is None: return ''
   1.118 +    if not isinstance(val, unicode): val = str(val)
   1.119 +    else: val = val.encode('utf-8')
   1.120 +    return urllib.quote(val)
   1.121 +
   1.122 +def httpdate(date_obj):
   1.123 +    """
   1.124 +    Formats a datetime object for use in HTTP headers.
   1.125 +    
   1.126 +        >>> import datetime
   1.127 +        >>> httpdate(datetime.datetime(1970, 1, 1, 1, 1, 1))
   1.128 +        'Thu, 01 Jan 1970 01:01:01 GMT'
   1.129 +    """
   1.130 +    return date_obj.strftime("%a, %d %b %Y %H:%M:%S GMT")
   1.131 +
   1.132 +def parsehttpdate(string_):
   1.133 +    """
   1.134 +    Parses an HTTP date into a datetime object.
   1.135 +
   1.136 +        >>> parsehttpdate('Thu, 01 Jan 1970 01:01:01 GMT')
   1.137 +        datetime.datetime(1970, 1, 1, 1, 1, 1)
   1.138 +    """
   1.139 +    try:
   1.140 +        t = time.strptime(string_, "%a, %d %b %Y %H:%M:%S %Z")
   1.141 +    except ValueError:
   1.142 +        return None
   1.143 +    return datetime.datetime(*t[:6])
   1.144 +
   1.145 +def htmlquote(text):
   1.146 +    r"""
   1.147 +    Encodes `text` for raw use in HTML.
   1.148 +    
   1.149 +        >>> htmlquote(u"<'&\">")
   1.150 +        u'&lt;&#39;&amp;&quot;&gt;'
   1.151 +    """
   1.152 +    text = text.replace(u"&", u"&amp;") # Must be done first!
   1.153 +    text = text.replace(u"<", u"&lt;")
   1.154 +    text = text.replace(u">", u"&gt;")
   1.155 +    text = text.replace(u"'", u"&#39;")
   1.156 +    text = text.replace(u'"', u"&quot;")
   1.157 +    return text
   1.158 +
   1.159 +def htmlunquote(text):
   1.160 +    r"""
   1.161 +    Decodes `text` that's HTML quoted.
   1.162 +
   1.163 +        >>> htmlunquote(u'&lt;&#39;&amp;&quot;&gt;')
   1.164 +        u'<\'&">'
   1.165 +    """
   1.166 +    text = text.replace(u"&quot;", u'"')
   1.167 +    text = text.replace(u"&#39;", u"'")
   1.168 +    text = text.replace(u"&gt;", u">")
   1.169 +    text = text.replace(u"&lt;", u"<")
   1.170 +    text = text.replace(u"&amp;", u"&") # Must be done last!
   1.171 +    return text
   1.172 +    
   1.173 +def websafe(val):
   1.174 +    r"""Converts `val` so that it is safe for use in Unicode HTML.
   1.175 +
   1.176 +        >>> websafe("<'&\">")
   1.177 +        u'&lt;&#39;&amp;&quot;&gt;'
   1.178 +        >>> websafe(None)
   1.179 +        u''
   1.180 +        >>> websafe(u'\u203d')
   1.181 +        u'\u203d'
   1.182 +        >>> websafe('\xe2\x80\xbd')
   1.183 +        u'\u203d'
   1.184 +    """
   1.185 +    if val is None:
   1.186 +        return u''
   1.187 +    elif isinstance(val, str):
   1.188 +        val = val.decode('utf-8')
   1.189 +    elif not isinstance(val, unicode):
   1.190 +        val = unicode(val)
   1.191 +        
   1.192 +    return htmlquote(val)
   1.193 +
   1.194 +if __name__ == "__main__":
   1.195 +    import doctest
   1.196 +    doctest.testmod()