1
# -*- test-case-name: twisted.test.test_compat -*-
3
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
4
# See LICENSE for details.
8
Compatability module to provide backwards compatability
9
for useful Python features.
11
This is mainly for use of internal Twisted code. We encourage you to use
12
the latest version of Python directly from your code, if possible.
15
import sys, string, socket, struct
17
def inet_pton(af, addr):
18
if af == socket.AF_INET:
19
return socket.inet_aton(addr)
20
elif af == getattr(socket, 'AF_INET6', 'AF_INET6'):
21
if [x for x in addr if x not in string.hexdigits + ':.']:
22
raise ValueError("Illegal characters: %r" % (''.join(x),))
24
parts = addr.split(':')
25
elided = parts.count('')
26
ipv4Component = '.' in parts[-1]
28
if len(parts) > (8 - ipv4Component) or elided > 3:
29
raise ValueError("Syntactically invalid address")
35
zeros = ['0'] * (8 - len(parts) - ipv4Component + elided)
37
if addr.startswith('::'):
39
elif addr.endswith('::'):
43
parts[idx:idx+1] = zeros
45
if len(parts) != 8 - ipv4Component:
46
raise ValueError("Syntactically invalid address")
48
if len(parts) != (8 - ipv4Component):
49
raise ValueError("Syntactically invalid address")
52
if parts[-1].count('.') != 3:
53
raise ValueError("Syntactically invalid address")
54
rawipv4 = socket.inet_aton(parts[-1])
55
unpackedipv4 = struct.unpack('!HH', rawipv4)
56
parts[-1:] = [hex(x)[2:] for x in unpackedipv4]
58
parts = [int(x, 16) for x in parts]
59
return struct.pack('!8H', *parts)
61
raise socket.error(97, 'Address family not supported by protocol')
63
def inet_ntop(af, addr):
64
if af == socket.AF_INET:
65
return socket.inet_ntoa(addr)
66
elif af == socket.AF_INET6:
68
raise ValueError("address length incorrect")
69
parts = struct.unpack('!8H', addr)
70
curBase = bestBase = None
78
if curBase is not None:
79
if bestBase is None or curLen > bestLen:
83
if curBase is not None and (bestBase is None or curLen > bestLen):
86
parts = [hex(x)[2:] for x in parts]
87
if bestBase is not None:
88
parts[bestBase:bestBase + bestLen] = ['']
92
parts.insert(len(parts) - 1, '')
93
return ':'.join(parts)
95
raise socket.error(97, 'Address family not supported by protocol')
98
socket.inet_pton(socket.AF_INET6, "::")
99
except (AttributeError, NameError, socket.error):
100
socket.inet_pton = inet_pton
101
socket.inet_ntop = inet_ntop
102
socket.AF_INET6 = 'AF_INET6'
106
# OpenSSL/__init__.py imports OpenSSL.tsafe. OpenSSL/tsafe.py imports
107
# threading. threading imports thread. All to make this stupid threadsafe
108
# version of its Connection class. We don't even care about threadsafe
109
# Connections. In the interest of not screwing over some crazy person
110
# calling into OpenSSL from another thread and trying to use Twisted's SSL
111
# support, we don't totally destroy OpenSSL.tsafe, but we will replace it
112
# with our own version which imports threading as late as possible.
117
OpenSSL.tsafe.Connection, defined in such a way as to not blow.
119
__module__ = 'OpenSSL.tsafe'
121
def __init__(self, *args):
122
from OpenSSL import SSL as _ssl
123
self._ssl_conn = apply(_ssl.Connection, args)
124
from threading import _RLock
125
self._lock = _RLock()
127
for f in ('get_context', 'pending', 'send', 'write', 'recv',
128
'read', 'renegotiate', 'bind', 'listen', 'connect',
129
'accept', 'setblocking', 'fileno', 'shutdown',
130
'close', 'get_cipher_list', 'getpeername',
131
'getsockname', 'getsockopt', 'setsockopt',
132
'makefile', 'get_app_data', 'set_app_data',
133
'state_string', 'sock_shutdown',
134
'get_peer_certificate', 'want_read', 'want_write',
135
'set_connect_state', 'set_accept_state',
136
'connect_ex', 'sendall'):
138
exec """def %s(self, *args):
141
return apply(self._ssl_conn.%s, args)
143
self._lock.release()\n""" % (f, f)
144
sys.modules['OpenSSL.tsafe'] = tsafe
149
except AttributeError:
150
class attrgetter(object):
151
def __init__(self, name):
153
def __call__(self, obj):
154
return getattr(obj, self.name)
155
operator.attrgetter = attrgetter