Files
tryton/trytond/pysocket.py
T

179 lines
5.9 KiB
Python
Raw Normal View History

2008-06-23 20:18:54 +02:00
#This file is part of Tryton. The COPYRIGHT file at the top level of this repository contains the full copyright notices and license terms.
2007-12-10 01:04:13 +01:00
import socket
2008-07-17 19:35:03 +02:00
# can't use/fall-back pickle due to different interface :-(
2007-12-10 01:04:13 +01:00
import cPickle
try:
import cStringIO as StringIO
except ImportError:
import StringIO
2007-12-10 01:04:13 +01:00
DNS_CACHE = {}
MAX_SIZE = 999999999
MAX_LENGHT = len(str(MAX_SIZE))
CONNECT_TIMEOUT = 5
TIMEOUT = 3600
2007-12-10 01:04:13 +01:00
2008-03-17 17:47:32 +01:00
_ALLOWED_MODULES = {'datetime': ['datetime', 'date'], 'decimal': ['Decimal']}
2008-02-25 21:19:32 +01:00
def checkfunction(module, klass):
if module in _ALLOWED_MODULES and klass in _ALLOWED_MODULES[module]:
mod = __import__(module, {}, {}, ['__all__'])
_class = getattr(mod, klass)
return _class
raise ValueError('Not supported: %s/%s' % (module, klass))
class PySocket:
2007-12-10 01:04:13 +01:00
def __init__(self, sock=None):
2008-02-25 21:19:32 +01:00
self.sock = sock
self.host = None
self.port = None
2008-03-04 14:42:51 +01:00
self.ssl = False
self.ssl_sock = None
2008-08-14 13:35:13 +02:00
self.connected = False
self.buffer = ''
2007-12-10 01:04:13 +01:00
def connect(self, host, port=False):
if not port:
buf = host.split('//')[1]
2008-03-27 11:19:12 +01:00
host, port = buf.rsplit(':', 1)
hostname = host
if host in DNS_CACHE:
host = DNS_CACHE[host]
2008-08-14 13:35:13 +02:00
self.sock = None
if socket.has_ipv6:
try:
socket.getaddrinfo(host, int(port), socket.AF_INET6)
self.sock = socket.socket(socket.AF_INET6,
socket.SOCK_STREAM)
self.sock.settimeout(CONNECT_TIMEOUT)
self.sock.connect((host, int(port)))
2008-08-14 13:35:13 +02:00
except:
self.sock = None
2008-08-14 13:35:13 +02:00
if self.sock is None:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.settimeout(CONNECT_TIMEOUT)
self.sock.connect((host, int(port)))
2008-03-27 11:19:12 +01:00
DNS_CACHE[hostname], port = self.sock.getpeername()[:2]
2008-03-04 14:42:51 +01:00
try:
2008-07-24 18:07:41 +02:00
sock = None
2008-03-04 14:42:51 +01:00
if socket.has_ipv6:
try:
socket.getaddrinfo(host, int(port), socket.AF_INET6)
2008-07-24 18:07:41 +02:00
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
sock.settimeout(CONNECT_TIMEOUT)
sock.connect((host, int(port)))
2008-03-04 14:42:51 +01:00
except:
sock = None
2008-07-24 18:07:41 +02:00
if sock is None:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(CONNECT_TIMEOUT)
sock.connect((host, int(port)))
2008-08-19 18:09:41 +02:00
if hasattr(socket, 'ssl'):
ssl_sock = socket.ssl(sock)
self.ssl = True
2008-03-04 14:42:51 +01:00
except:
pass
self.sock.settimeout(TIMEOUT)
2008-03-04 14:42:51 +01:00
if self.ssl:
self.ssl_sock = socket.ssl(self.sock)
self.host = host
2008-03-27 11:19:12 +01:00
self.hostname = hostname
self.port = port
2008-08-14 13:35:13 +02:00
self.connected = True
self.buffer = ''
2007-12-10 01:04:13 +01:00
def disconnect(self):
try:
2008-04-27 16:25:11 +02:00
if self.ssl:
try:
if hasattr(socket, 'SHUT_RDWR'):
self.ssl_sock.sock_shutdown(socket.SHUT_RDWR)
else:
self.ssl_sock.sock_shutdown(2)
except:
pass
self.ssl_sock.close()
2008-03-04 14:42:51 +01:00
else:
2008-04-27 16:25:11 +02:00
try:
if hasattr(socket, 'SHUT_RDWR'):
self.sock.shutdown(socket.SHUT_RDWR)
else:
self.sock.shutdown(2)
except:
pass
self.sock.close()
except:
pass
2008-08-14 13:35:13 +02:00
self.sock = None
self.connected = False
self.buffer = ''
def reconnect(self):
if self.host and self.port:
self.disconnect()
2008-08-14 14:18:03 +02:00
self.connect(self.host, self.port)
2007-12-10 01:04:13 +01:00
def send(self, msg, exception=False, traceback=None):
2008-06-07 13:25:30 +02:00
msg = cPickle.dumps([msg, traceback], protocol=2)
2007-12-10 01:04:13 +01:00
size = len(msg)
msg = str(size) + ' ' + (exception and "1" or "0") + msg
size = len(msg)
2007-12-10 01:04:13 +01:00
totalsent = 0
while totalsent < size:
2008-03-04 14:42:51 +01:00
if self.ssl:
sent = self.ssl_sock.write(msg[totalsent:])
else:
sent = self.sock.send(msg[totalsent:])
2007-12-10 01:04:13 +01:00
if sent == 0:
raise RuntimeError, "socket connection broken"
totalsent = totalsent + sent
def receive(self):
buf = self.buffer
while len(buf) < MAX_LENGHT:
2008-03-04 14:42:51 +01:00
if self.ssl:
chunk = self.ssl_sock.read(4096)
2008-03-04 14:42:51 +01:00
else:
chunk = self.sock.recv(4096)
2007-12-10 01:04:13 +01:00
if chunk == '':
raise RuntimeError, "socket connection broken"
buf += chunk
if ' ' in buf:
break
size, msg = buf.split(' ', 1)
size = int(size)
if size > MAX_SIZE:
raise RuntimeError, "socket connection broken"
if msg == '':
if self.ssl:
msg = self.ssl_sock.read(4096)
else:
msg = self.sock.recv(4096)
if msg == '':
raise RuntimeError, "socket connection broken"
if msg[0] != "0":
2007-12-10 01:04:13 +01:00
exception = buf
else:
exception = False
msg = msg[1:]
2007-12-10 01:04:13 +01:00
while len(msg) < size:
2008-03-04 14:42:51 +01:00
if self.ssl:
chunk = self.ssl_sock.read(size - len(msg))
2008-03-04 14:42:51 +01:00
else:
chunk = self.sock.recv(size - len(msg))
2007-12-10 01:04:13 +01:00
if chunk == '':
raise RuntimeError, "socket connection broken"
msg = msg + chunk
self.buffer = msg[size:]
msg = msg[:size]
msgio = StringIO.StringIO(msg)
2008-02-04 23:16:04 +01:00
unpickler = cPickle.Unpickler(msgio)
2008-07-17 19:35:03 +02:00
# cPickle mechanism to import instances (pickle differs here)
2008-02-25 21:19:32 +01:00
unpickler.find_global = checkfunction
2008-02-04 23:16:04 +01:00
res = unpickler.load()
if exception:
2008-07-17 19:35:03 +02:00
raise Exception(*(list(res[0]) + [res[1]]))
2007-12-10 01:04:13 +01:00
else:
return res[0]