/usr/share/pyshared/tryton/jsonrpc.py is in tryton-client 2.2.1-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 | #This file is part of Tryton. The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
import xmlrpclib
try:
import simplejson as json
except ImportError:
import json
import ssl
import httplib
from decimal import Decimal
import datetime
import socket
import gzip
import StringIO
import hashlib
import sys
import base64
__all__ = ["ResponseError", "Fault", "ProtocolError", "Transport",
"ServerProxy"]
CONNECT_TIMEOUT = 5
DEFAULT_TIMEOUT = None
class ResponseError(xmlrpclib.ResponseError):
pass
class Fault(xmlrpclib.Fault):
def __init__(self, faultCode, faultString='', **extra):
super(Fault, self).__init__(faultCode, str(faultString), **extra)
self.args = faultString
class ProtocolError(xmlrpclib.ProtocolError):
pass
def object_hook(dct):
if '__class__' in dct:
if dct['__class__'] == 'datetime':
return datetime.datetime(dct['year'], dct['month'], dct['day'],
dct['hour'], dct['minute'], dct['second'])
elif dct['__class__'] == 'date':
return datetime.date(dct['year'], dct['month'], dct['day'])
elif dct['__class__'] == 'buffer':
return buffer(base64.decodestring(dct['base64']))
elif dct['__class__'] == 'Decimal':
return Decimal(dct['decimal'])
return dct
class JSONEncoder(json.JSONEncoder):
def __init__(self, *args, **kwargs):
super(JSONEncoder, self).__init__(*args, **kwargs)
# Force to use our custom decimal with simplejson
self.use_decimal = False
def default(self, obj):
if isinstance(obj, datetime.date):
if isinstance(obj, datetime.datetime):
return {'__class__': 'datetime',
'year': obj.year,
'month': obj.month,
'day': obj.day,
'hour': obj.hour,
'minute': obj.minute,
'second': obj.second,
}
return {'__class__': 'date',
'year': obj.year,
'month': obj.month,
'day': obj.day,
}
elif isinstance(obj, buffer):
return {'__class__': 'buffer',
'base64': base64.encodestring(obj),
}
elif isinstance(obj, Decimal):
return {'__class__': 'Decimal',
'decimal': str(obj),
}
return super(JSONEncoder, self).default(obj)
class JSONParser(object):
def __init__(self, target):
self.__targer = target
def feed(self, data):
self.__targer.feed(data)
def close(self):
pass
class JSONUnmarshaller(object):
data = ''
def feed(self, data):
self.data += data
def close(self):
return json.loads(self.data, object_hook=object_hook)
class Transport(xmlrpclib.Transport, xmlrpclib.SafeTransport):
accept_gzip_encoding = True
encode_threshold = 1400 # common MTU
def __init__(self, fingerprints=None, ca_certs=None):
xmlrpclib.Transport.__init__(self)
self._connection = (None, None)
self.__fingerprints = fingerprints
self.__ca_certs = ca_certs
def getparser(self):
target = JSONUnmarshaller()
parser = JSONParser(target)
return parser, target
def get_host_info(self, host):
host, extra_headers, x509 = xmlrpclib.Transport.get_host_info(self, host)
if extra_headers is None:
extra_headers = []
extra_headers.append(('Connection', 'keep-alive'))
return host, extra_headers, x509
def send_content(self, connection, request_body):
connection.putheader("Content-Type", "text/json")
if (self.encode_threshold is not None and
self.encode_threshold < len(request_body) and
gzip):
connection.putheader("Content-Encoding", "gzip")
buffer = StringIO.StringIO()
output = gzip.GzipFile(mode='wb', fileobj=buffer)
output.write(request_body)
output.close()
buffer.seek(0)
request_body = buffer.getvalue()
connection.putheader("Content-Length", str(len(request_body)))
connection.endheaders()
if request_body:
connection.send(request_body)
def make_connection(self, host):
if self._connection and host == self._connection[0]:
return self._connection[1]
host, extra_headers, x509 = self.get_host_info(host)
ca_certs = self.__ca_certs
cert_reqs = ssl.CERT_REQUIRED if ca_certs else ssl.CERT_NONE
class HTTPSConnection(httplib.HTTPSConnection):
def connect(self):
sock = socket.create_connection((self.host, self.port),
self.timeout)
if self._tunnel_host:
self.sock = sock
self._tunnel()
self.sock = ssl.wrap_socket(sock, self.key_file,
self.cert_file, ca_certs=ca_certs, cert_reqs=cert_reqs)
def http_connection():
self._connection = host, httplib.HTTPConnection(host,
timeout=CONNECT_TIMEOUT)
self._connection[1].connect()
def https_connection():
self._connection = host, HTTPSConnection(host,
timeout=CONNECT_TIMEOUT)
try:
self._connection[1].connect()
sock = self._connection[1].sock
try:
peercert = sock.getpeercert(True)
except socket.error:
peercert = None
def format_hash(value):
return reduce(lambda x, y: x + y[1].upper() +
((y[0] % 2 and y[0] + 1 < len(value)) and ':' or ''),
enumerate(value), '')
return format_hash(hashlib.sha1(peercert).hexdigest())
except ssl.SSLError, e:
http_connection()
fingerprint = ''
if self.__fingerprints is not None and host in self.__fingerprints:
if self.__fingerprints[host]:
fingerprint = https_connection()
else:
http_connection()
else:
fingerprint = https_connection()
if self.__fingerprints is not None:
if host in self.__fingerprints and self.__fingerprints[host]:
if self.__fingerprints[host] != fingerprint:
self.close()
raise ssl.SSLError('BadFingerprint')
else:
self.__fingerprints[host] = fingerprint
self._connection[1].timeout = DEFAULT_TIMEOUT
self._connection[1].sock.settimeout(DEFAULT_TIMEOUT)
return self._connection[1]
if sys.version_info[:2] <= (2, 6):
def request(self, host, handler, request_body, verbose=0):
h = self.make_connection(host)
if verbose:
h.set_debuglevel(1)
self.send_request(h, handler, request_body)
self.send_host(h, host)
self.send_user_agent(h)
self.send_content(h, request_body)
response = h.getresponse()
if response.status != 200:
raise ProtocolError(
host + handler,
response.status,
response.reason,
response.getheaders()
)
self.verbose = verbose
try:
sock = h._conn.sock
except AttributeError:
sock = None
if response.getheader("Content-Encoding", "") == "gzip":
response = gzip.GzipFile(mode="rb",
fileobj=StringIO.StringIO(response.read()))
sock = None
return self._parse_response(response, sock)
def send_request(self, connection, handler, request_body):
xmlrpclib.Transport.send_request(self, connection, handler,
request_body)
connection.putheader("Accept-Encoding", "gzip")
def close(self):
if self._connection[1]:
self._connection[1].close()
self._connection = (None, None)
class ServerProxy(xmlrpclib.ServerProxy):
__id = 0
def __init__(self, host, port, database='', verbose=0,
fingerprints=None, ca_certs=None):
self.__host = '%s:%s' % (host, port)
self.__handler = '/' + database
self.__transport = Transport(fingerprints, ca_certs)
self.__verbose = verbose
def __request(self, methodname, params):
self.__id += 1
id_ = self.__id
request = json.dumps({
'id': id_,
'method': methodname,
'params': params,
}, cls=JSONEncoder)
try:
response = self.__transport.request(
self.__host,
self.__handler,
request,
verbose=self.__verbose
)
except (socket.error, httplib.HTTPException), v:
# trap 'Broken pipe'
if isinstance(v, socket.error) and v.args[0] != 32:
raise
# try one more time
self.__transport.close()
response = self.__transport.request(
self.__host,
self.__handler,
request,
verbose=self.__verbose
)
except:
self.__transport.close()
raise
if response['id'] != id_:
raise ResponseError('Invalid response id (%s) excpected %s' %
(response['id'], id_))
if response.get('error'):
raise Fault(*response['error'])
return response['result']
def close(self):
self.__transport.close()
@property
def ssl(self):
return isinstance(self.__transport.make_connection(self.__host),
httplib.HTTPSConnection)
|