
from __future__ import absolute_import
from __future__ import division

import base64
import socket

from six.moves import http_client
from six.moves import xmlrpc_client


class UnixXmlRpcClient(xmlrpc_client.ServerProxy):
    def __init__(self, sock_path):
        uri = base64.b16encode(sock_path.encode('utf-8')).decode('utf-8')
        xmlrpc_client.ServerProxy.__init__(
            self,
            'http://' + uri,
            transport=UnixXmlRpcTransport(),
            allow_none=1)


class UnixXmlRpcTransport(xmlrpc_client.Transport):
    def make_connection(self, host):
        return UnixXmlRpcHttpConnection(host)


class UnixXmlRpcHttpConnection(http_client.HTTPConnection):
    def connect(self):
        self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        self.sock.connect(base64.b16decode(self.host))
