import AuthedXMLRPCServer
import XMLRPCServerProxy
import string
import socket
import logging

# some ideas stolen from
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/165375

class Server(AuthedXMLRPCServer.AuthedSSLXMLRPCServer):
    
    def __init__(self, addr, port, cert, ca, peer):
        
        # The one part about this code I think is stupid is the certs dict
        c = {}
        c['key_and_cert'] = cert
        c['ca_cert'] = ca
        # CA that's signed the client
        c['peer_ca_cert'] = peer
        
        AuthedXMLRPCServer.AuthedSSLXMLRPCServer.__init__(self, (addr, port),
                                                          self.auth_cb, c)

    def auth_cb(self, request, client_address):
        # Directly from AuthedXMLRPCServer
        import random
        peer_cert = request.get_peer_certificate()
        email = peer_cert.get_subject().countryName
        return "AUTH: %s - %d" % (email, random.randint(1, 100))

    def server_bind(self):
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        AuthedXMLRPCServer.AuthedSSLXMLRPCServer.server_bind(self)

    def verify_request(self, request, client_address):
        self.client_address = client_address
        return True

    def handle_error(self, request, client_address):
        # XXX: Log the traceback somewhere
        logging.getLogger().warning("Execption in XMLRPC server...continuing.")


class ServerProxy(XMLRPCServerProxy.PlgXMLRPCServerProxy):

    def __init__(self, uri, cert, ca, peer):
        c = {}
        c['key_and_cert'] = cert
        c['ca_cert'] = ca
        c['peer_ca_cert'] = peer

        XMLRPCServerProxy.PlgXMLRPCServerProxy.__init__(self, uri, c)
        
