#!/usr/bin/env python

__author__ = "Manuel Amador (Rudd-O) <dragonfear@gmail.com>"

""" A UNIX socket transport compatibility class for the xmlrpclib client.

Usage instructions:

Traditionally, you would instantiate an xmlrpclib.ServerProxy(...) instance
in your application.  Do that, but pass an instance of the
UnixSocketTransport class, like this:

path_to_socket_file = "/tmp/socket"
ust = UnixSocketTransport(path_to_socket_file)
server = xmlrpclib.ServerProxy(transport=ust)
"""

# FIXME make its own installable module

from xmlrpclib import ServerProxy, Transport
from httplib import HTTP, HTTPConnection
import socket 

class SocketHTTPConnection(HTTPConnection):

	def connect(self):
		"""Connect to the host and port specified in __init__."""
		msg = "cannot connect to UNIX domain socket"
		sa = self.host
		try:
			self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
			if self.debuglevel > 0:
				print "connect: (%s, %s)" % (self.host, "UNIX stream socket")
			self.sock.connect(sa)
		except socket.error, msg:
			if self.debuglevel > 0:
				print 'connect fail:', (self.host, "UNIX stream socket")
			if self.sock:
				self.sock.close()
				self.sock = None
		if not self.sock:
			raise socket.error, msg


class UnixSocketHTTP(HTTP):
	_connection_class = SocketHTTPConnection


class UnixSocketTransport(Transport):
	"""You would use this in your application:
	server = xmlrpclib.ServerProxy("http://localhost",UnixSocketTransport("/var/lib/sock.sock"))
	and the server proxy would use /var/lib/sock as the communication channel."""
	
	unix_socket = None
	
	def __init__(self,unixsocket):
		self.unix_socket = unixsocket
		
	def make_connection(self,host):
		return UnixSocketHTTP(self.unix_socket)
		
