f



Securing a multiprocessing.BaseManager connection via SSL

Hi,
how can I secure the communication between two BaseManager objects?
Regarding the socket/SSL documentation I just need to secure the
socket by SSL. How can i get the socket object within the
multiprocessing
module?

Best regards,

Jonas
0
11/6/2009 2:56:45 PM
comp.lang.python 77058 articles. 6 followers. Post Follow

3 Replies
912 Views

Similar Articles

[PageSpeed] 30

In article <f788be3b-62cd-4545-9ba8-50b7eaea0556@p8g2000yqb.googlegroups.com>,
Jonas  <jonas.weismueller@gmail.com> wrote:
>
>how can I secure the communication between two BaseManager objects?
>Regarding the socket/SSL documentation I just need to secure the socket
>by SSL. How can i get the socket object within the multiprocessing
>module?

You'll need to create subclasses of the objects in connection.py, but I'm
not sure how to make multiprocessing use them.
-- 
Aahz (aahz@pythoncraft.com)           <*>         http://www.pythoncraft.com/

[on old computer technologies and programmers]  "Fancy tail fins on a
brand new '59 Cadillac didn't mean throwing out a whole generation of
mechanics who started with model As."  --Andrew Dalke
0
aahz (2032)
11/11/2009 9:06:07 PM
Hi Jonas

I've having same need so i found a solution but you need to hack a bit

I am using python 2.6.3 but i suppose it could be applicable to your
case.

First of all u need to edit /usr/lib/python2.6/lib/python2.6/
multiprocessing/connection.py

This is mine:

#
# A higher level module for using sockets (or Windows named pipes)
#
# multiprocessing/connection.py
#
# Copyright (c) 2006-2008, R Oudkerk --- see COPYING.txt
#

__all__ = [ 'Client', 'Listener', 'Pipe' ]

import os
import sys
import socket
import errno
import time
import tempfile
import itertools
# Added by Xavi
import ssl

import _multiprocessing
from multiprocessing import current_process, AuthenticationError
from multiprocessing.util import get_temp_dir, Finalize, sub_debug,
debug
from multiprocessing.forking import duplicate, close


#
#
#

BUFSIZE = 8192

_mmap_counter = itertools.count()

default_family = 'AF_INET'
families = ['AF_INET']

if hasattr(socket, 'AF_UNIX'):
    default_family = 'AF_UNIX'
    families += ['AF_UNIX']

if sys.platform == 'win32':
    default_family = 'AF_PIPE'
    families += ['AF_PIPE']

#
#
#

def arbitrary_address(family):
    '''
    Return an arbitrary free address for the given family
    '''
    if family == 'AF_INET':
        return ('localhost', 0)
    elif family == 'AF_UNIX':
        return tempfile.mktemp(prefix='listener-', dir=get_temp_dir())
    elif family == 'AF_PIPE':
        return tempfile.mktemp(prefix=r'\\.\pipe\pyc-%d-%d-' %
                               (os.getpid(), _mmap_counter.next()))
    else:
        raise ValueError('unrecognized family')


def address_type(address):
    '''
    Return the types of the address

    This can be 'AF_INET', 'AF_UNIX', or 'AF_PIPE'
    '''
    if type(address) == tuple:
        return 'AF_INET'
    elif type(address) is str and address.startswith('\\\\'):
        return 'AF_PIPE'
    elif type(address) is str:
        return 'AF_UNIX'
    else:
        raise ValueError('address type of %r unrecognized' % address)

#
# Public functions
#

class Listener(object):
    '''
    Returns a listener object.

    This is a wrapper for a bound socket which is 'listening' for
    connections, or for a Windows named pipe.
    '''
    def __init__(self, address=None, family=None, backlog=1,
authkey=None, sslsock=True):
        family = family or (address and address_type(address)) \
                 or default_family
        address = address or arbitrary_address(family)

        if family == 'AF_PIPE':
            self._listener = PipeListener(address, backlog)
        else:
            self._listener = SocketListener(address, family, backlog,
sslsock)
        if authkey is not None and not isinstance(authkey, bytes):
            raise TypeError, 'authkey should be a byte string'

        self._authkey = authkey

    def accept(self):
        '''
        Accept a connection on the bound socket or named pipe of
`self`.

        Returns a `Connection` object.
        '''
        c = self._listener.accept()
        if self._authkey:
            deliver_challenge(c, self._authkey)
            answer_challenge(c, self._authkey)
        return c

    def close(self):
        '''
        Close the bound socket or named pipe of `self`.
        '''
        return self._listener.close()

    address = property(lambda self: self._listener._address)
    last_accepted = property(lambda self:
self._listener._last_accepted)


def Client(address, family=None, authkey=None, sslsock=True):
    '''
    Returns a connection to the address of a `Listener`
    '''
    family = family or address_type(address)
    if family == 'AF_PIPE':
        c = PipeClient(address)
    else:
        c = SocketClient(address,sslsock)

    if authkey is not None and not isinstance(authkey, bytes):
        raise TypeError, 'authkey should be a byte string'

    if authkey is not None:
        answer_challenge(c, authkey)
        deliver_challenge(c, authkey)

    return c


if sys.platform != 'win32':

    def Pipe(duplex=True):
        '''
        Returns pair of connection objects at either end of a pipe
        '''
        if duplex:
            s1, s2 = socket.socketpair()
            c1 = _multiprocessing.Connection(os.dup(s1.fileno()))
            c2 = _multiprocessing.Connection(os.dup(s2.fileno()))
            s1.close()
            s2.close()
        else:
            fd1, fd2 = os.pipe()
            c1 = _multiprocessing.Connection(fd1, writable=False)
            c2 = _multiprocessing.Connection(fd2, readable=False)

        return c1, c2

else:

    from ._multiprocessing import win32

    def Pipe(duplex=True):
        '''
        Returns pair of connection objects at either end of a pipe
        '''
        address = arbitrary_address('AF_PIPE')
        if duplex:
            openmode = win32.PIPE_ACCESS_DUPLEX
            access = win32.GENERIC_READ | win32.GENERIC_WRITE
            obsize, ibsize = BUFSIZE, BUFSIZE
        else:
            openmode = win32.PIPE_ACCESS_INBOUND
            access = win32.GENERIC_WRITE
            obsize, ibsize = 0, BUFSIZE

        h1 = win32.CreateNamedPipe(
            address, openmode,
            win32.PIPE_TYPE_MESSAGE | win32.PIPE_READMODE_MESSAGE |
            win32.PIPE_WAIT,
            1, obsize, ibsize, win32.NMPWAIT_WAIT_FOREVER, win32.NULL
            )
        h2 = win32.CreateFile(
            address, access, 0, win32.NULL, win32.OPEN_EXISTING, 0,
win32.NULL
            )
        win32.SetNamedPipeHandleState(
            h2, win32.PIPE_READMODE_MESSAGE, None, None
            )

        try:
            win32.ConnectNamedPipe(h1, win32.NULL)
        except WindowsError, e:
            if e.args[0] != win32.ERROR_PIPE_CONNECTED:
                raise

        c1 = _multiprocessing.PipeConnection(h1, writable=duplex)
        c2 = _multiprocessing.PipeConnection(h2, readable=duplex)

        return c1, c2

#
# Definitions for connections based on sockets
#

class SocketListener(object):
    '''
    Representation of a socket which is bound to an address and
listening
    '''
# Aadido sslsock por xavi
    def __init__(self, address, family, backlog=1, sslsock=True):
        self._socket = socket.socket(getattr(socket, family))
        if sslsock == True:
            print "SSL Enabled"
            self._socket = ssl.wrap_socket
(self._socket,certfile="cert.pem",server_side=True,ssl_version=ssl.PROTOCOL_TLSv1)
        self._socket.setsockopt(socket.SOL_SOCKET,
socket.SO_REUSEADDR, 1)
        self._socket.bind(address)
        self._socket.listen(backlog)
        self._address = self._socket.getsockname()
        self._family = family
        self._last_accepted = None

        if family == 'AF_UNIX':
            self._unlink = Finalize(
                self, os.unlink, args=(address,), exitpriority=0
                )
        else:
            self._unlink = None


    def accept(self):
        s, self._last_accepted = self._socket.accept()
        fd = duplicate(s.fileno())
        conn = _multiprocessing.Connection(fd)
        s.close()
        return conn

    def close(self):
        self._socket.close()
        if self._unlink is not None:
            self._unlink()


def SocketClient(address, sslsock=True):
    '''
    Return a connection object connected to the socket given by
`address`
    '''
    family = address_type(address)
    s = socket.socket( getattr(socket, family) )
    if sslsock == True:
        '''
        print "SSL Enabled"
        '''
        s = ssl.wrap_socket
(s,ssl_version=ssl.PROTOCOL_TLSv1,cert_reqs=ssl.CERT_NONE,ca_certs=None)
    while 1:
        try:
            s.connect(address)
        except socket.error, e:
            if e.args[0] != errno.ECONNREFUSED: # connection refused
                debug('failed to connect to address %s', address)
                raise
            time.sleep(0.01)
        else:
            break
    else:
        raise

    fd = duplicate(s.fileno())
    conn = _multiprocessing.Connection(fd)
    s.close()
    return conn

#
# Definitions for connections based on named pipes
#

if sys.platform == 'win32':

    class PipeListener(object):
        '''
        Representation of a named pipe
        '''
        def __init__(self, address, backlog=None):
            self._address = address
            handle = win32.CreateNamedPipe(
                address, win32.PIPE_ACCESS_DUPLEX,
                win32.PIPE_TYPE_MESSAGE | win32.PIPE_READMODE_MESSAGE
|
                win32.PIPE_WAIT,
                win32.PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE,
                win32.NMPWAIT_WAIT_FOREVER, win32.NULL
                )
            self._handle_queue = [handle]
            self._last_accepted = None

            sub_debug('listener created with address=%r',
self._address)

            self.close = Finalize(
                self, PipeListener._finalize_pipe_listener,
                args=(self._handle_queue, self._address),
exitpriority=0
                )

        def accept(self):
            newhandle = win32.CreateNamedPipe(
                self._address, win32.PIPE_ACCESS_DUPLEX,
                win32.PIPE_TYPE_MESSAGE | win32.PIPE_READMODE_MESSAGE
|
                win32.PIPE_WAIT,
                win32.PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE,
                win32.NMPWAIT_WAIT_FOREVER, win32.NULL
                )
            self._handle_queue.append(newhandle)
            handle = self._handle_queue.pop(0)
            try:
                win32.ConnectNamedPipe(handle, win32.NULL)
            except WindowsError, e:
                if e.args[0] != win32.ERROR_PIPE_CONNECTED:
                    raise
            return _multiprocessing.PipeConnection(handle)

        @staticmethod
        def _finalize_pipe_listener(queue, address):
            sub_debug('closing listener with address=%r', address)
            for handle in queue:
                close(handle)

    def PipeClient(address):
        '''
        Return a connection object connected to the pipe given by
`address`
        '''
        while 1:
            try:
                win32.WaitNamedPipe(address, 1000)
                h = win32.CreateFile(
                    address, win32.GENERIC_READ | win32.GENERIC_WRITE,
                    0, win32.NULL, win32.OPEN_EXISTING, 0, win32.NULL
                    )
            except WindowsError, e:
                if e.args[0] not in (win32.ERROR_SEM_TIMEOUT,
                                     win32.ERROR_PIPE_BUSY):
                    raise
            else:
                break
        else:
            raise

        win32.SetNamedPipeHandleState(
            h, win32.PIPE_READMODE_MESSAGE, None, None
            )
        return _multiprocessing.PipeConnection(h)

#
# Authentication stuff
#

MESSAGE_LENGTH = 20

CHALLENGE = b'#CHALLENGE#'
WELCOME = b'#WELCOME#'
FAILURE = b'#FAILURE#'

def deliver_challenge(connection, authkey):
    import hmac
    assert isinstance(authkey, bytes)
    message = os.urandom(MESSAGE_LENGTH)
    connection.send_bytes(CHALLENGE + message)
    digest = hmac.new(authkey, message).digest()
    response = connection.recv_bytes(256)        # reject large
message
    if response == digest:
        connection.send_bytes(WELCOME)
    else:
        connection.send_bytes(FAILURE)
        raise AuthenticationError('digest received was wrong')

def answer_challenge(connection, authkey):
    import hmac
    assert isinstance(authkey, bytes)
    message = connection.recv_bytes(256)         # reject large
message
    assert message[:len(CHALLENGE)] == CHALLENGE, 'message = %r' %
message
    message = message[len(CHALLENGE):]
    digest = hmac.new(authkey, message).digest()
    connection.send_bytes(digest)
    response = connection.recv_bytes(256)        # reject large
message
    if response != WELCOME:
        raise AuthenticationError('digest sent was rejected')

#
# Support for using xmlrpclib for serialization
#

class ConnectionWrapper(object):
    def __init__(self, conn, dumps, loads):
        self._conn = conn
        self._dumps = dumps
        self._loads = loads
        for attr in ('fileno', 'close', 'poll', 'recv_bytes',
'send_bytes'):
            obj = getattr(conn, attr)
            setattr(self, attr, obj)
    def send(self, obj):
        s = self._dumps(obj)
        self._conn.send_bytes(s)
    def recv(self):
        s = self._conn.recv_bytes()
        return self._loads(s)

def _xml_dumps(obj):
    return xmlrpclib.dumps((obj,), None, None, None, 1).encode('utf8')

def _xml_loads(s):
    (obj,), method = xmlrpclib.loads(s.decode('utf8'))
    return obj

class XmlListener(Listener):
    def accept(self):
        global xmlrpclib
        import xmlrpclib
        obj = Listener.accept(self)
        return ConnectionWrapper(obj, _xml_dumps, _xml_loads)

def XmlClient(*args, **kwds):
    global xmlrpclib
    import xmlrpclib
    return ConnectionWrapper(Client(*args, **kwds), _xml_dumps,
_xml_loads)

================================

If u take a look u can observe i've imported ssl module and added a
sslsock parameter in SocketListener and SocketClient.

There is a certificate file required called 'cert.pem', you can
generate one by typing this:

openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem

In same directory where your python server program runs.

Encryption it's setup to AES-256 and mandatory, so it would raise and
error if certificate file is missing.

U don't need to change any code in your program.

U can use tcpdump or wireshark to test that it works.








On 6 nov, 15:56, Jonas <jonas.weismuel...@gmail.com> wrote:
> Hi,
> how can I secure the communication between two BaseManager objects?
> Regarding the socket/SSL documentation I just need to secure the
> socket by SSL. How can i get the socket object within themultiprocessing
> module?
>
> Best regards,
>
> Jonas

0
x.sanz35 (3)
11/24/2009 9:45:37 PM
I recommend u to test it before use it in production environment.

On 24 nov, 22:45, Xavier Sanz <x.san...@gmail.com> wrote:
> Hi Jonas
>
> I've having same need so i found a solution but you need to hack a bit
>
> I am using python 2.6.3 but i suppose it could be applicable to your
> case.
>
> First of all u need to edit /usr/lib/python2.6/lib/python2.6/multiprocess=
ing/connection.py
>
> This is mine:
>
> #
> # A higher level module for using sockets (or Windows named pipes)
> #
> #multiprocessing/connection.py
> #
> # Copyright (c) 2006-2008, R Oudkerk --- see COPYING.txt
> #
>
> __all__ =3D [ 'Client', 'Listener', 'Pipe' ]
>
> import os
> import sys
> import socket
> import errno
> import time
> import tempfile
> import itertools
> # Added by Xavi
> import ssl
>
> import _multiprocessing
> frommultiprocessingimport current_process, AuthenticationError
> frommultiprocessing.util import get_temp_dir, Finalize, sub_debug,
> debug
> frommultiprocessing.forking import duplicate, close
>
> #
> #
> #
>
> BUFSIZE =3D 8192
>
> _mmap_counter =3D itertools.count()
>
> default_family =3D 'AF_INET'
> families =3D ['AF_INET']
>
> if hasattr(socket, 'AF_UNIX'):
> =A0 =A0 default_family =3D 'AF_UNIX'
> =A0 =A0 families +=3D ['AF_UNIX']
>
> if sys.platform =3D=3D 'win32':
> =A0 =A0 default_family =3D 'AF_PIPE'
> =A0 =A0 families +=3D ['AF_PIPE']
>
> #
> #
> #
>
> def arbitrary_address(family):
> =A0 =A0 '''
> =A0 =A0 Return an arbitrary free address for the given family
> =A0 =A0 '''
> =A0 =A0 if family =3D=3D 'AF_INET':
> =A0 =A0 =A0 =A0 return ('localhost', 0)
> =A0 =A0 elif family =3D=3D 'AF_UNIX':
> =A0 =A0 =A0 =A0 return tempfile.mktemp(prefix=3D'listener-', dir=3Dget_te=
mp_dir())
> =A0 =A0 elif family =3D=3D 'AF_PIPE':
> =A0 =A0 =A0 =A0 return tempfile.mktemp(prefix=3Dr'\\.\pipe\pyc-%d-%d-' %
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0(os.getpid=
(), _mmap_counter.next()))
> =A0 =A0 else:
> =A0 =A0 =A0 =A0 raise ValueError('unrecognized family')
>
> def address_type(address):
> =A0 =A0 '''
> =A0 =A0 Return the types of the address
>
> =A0 =A0 This can be 'AF_INET', 'AF_UNIX', or 'AF_PIPE'
> =A0 =A0 '''
> =A0 =A0 if type(address) =3D=3D tuple:
> =A0 =A0 =A0 =A0 return 'AF_INET'
> =A0 =A0 elif type(address) is str and address.startswith('\\\\'):
> =A0 =A0 =A0 =A0 return 'AF_PIPE'
> =A0 =A0 elif type(address) is str:
> =A0 =A0 =A0 =A0 return 'AF_UNIX'
> =A0 =A0 else:
> =A0 =A0 =A0 =A0 raise ValueError('address type of %r unrecognized' % addr=
ess)
>
> #
> # Public functions
> #
>
> class Listener(object):
> =A0 =A0 '''
> =A0 =A0 Returns a listener object.
>
> =A0 =A0 This is a wrapper for a bound socket which is 'listening' for
> =A0 =A0 connections, or for a Windows named pipe.
> =A0 =A0 '''
> =A0 =A0 def __init__(self, address=3DNone, family=3DNone, backlog=3D1,
> authkey=3DNone, sslsock=3DTrue):
> =A0 =A0 =A0 =A0 family =3D family or (address and address_type(address)) =
\
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0or default_family
> =A0 =A0 =A0 =A0 address =3D address or arbitrary_address(family)
>
> =A0 =A0 =A0 =A0 if family =3D=3D 'AF_PIPE':
> =A0 =A0 =A0 =A0 =A0 =A0 self._listener =3D PipeListener(address, backlog)
> =A0 =A0 =A0 =A0 else:
> =A0 =A0 =A0 =A0 =A0 =A0 self._listener =3D SocketListener(address, family=
, backlog,
> sslsock)
> =A0 =A0 =A0 =A0 if authkey is not None and not isinstance(authkey, bytes)=
:
> =A0 =A0 =A0 =A0 =A0 =A0 raise TypeError, 'authkey should be a byte string=
'
>
> =A0 =A0 =A0 =A0 self._authkey =3D authkey
>
> =A0 =A0 def accept(self):
> =A0 =A0 =A0 =A0 '''
> =A0 =A0 =A0 =A0 Accept a connection on the bound socket or named pipe of
> `self`.
>
> =A0 =A0 =A0 =A0 Returns a `Connection` object.
> =A0 =A0 =A0 =A0 '''
> =A0 =A0 =A0 =A0 c =3D self._listener.accept()
> =A0 =A0 =A0 =A0 if self._authkey:
> =A0 =A0 =A0 =A0 =A0 =A0 deliver_challenge(c, self._authkey)
> =A0 =A0 =A0 =A0 =A0 =A0 answer_challenge(c, self._authkey)
> =A0 =A0 =A0 =A0 return c
>
> =A0 =A0 def close(self):
> =A0 =A0 =A0 =A0 '''
> =A0 =A0 =A0 =A0 Close the bound socket or named pipe of `self`.
> =A0 =A0 =A0 =A0 '''
> =A0 =A0 =A0 =A0 return self._listener.close()
>
> =A0 =A0 address =3D property(lambda self: self._listener._address)
> =A0 =A0 last_accepted =3D property(lambda self:
> self._listener._last_accepted)
>
> def Client(address, family=3DNone, authkey=3DNone, sslsock=3DTrue):
> =A0 =A0 '''
> =A0 =A0 Returns a connection to the address of a `Listener`
> =A0 =A0 '''
> =A0 =A0 family =3D family or address_type(address)
> =A0 =A0 if family =3D=3D 'AF_PIPE':
> =A0 =A0 =A0 =A0 c =3D PipeClient(address)
> =A0 =A0 else:
> =A0 =A0 =A0 =A0 c =3D SocketClient(address,sslsock)
>
> =A0 =A0 if authkey is not None and not isinstance(authkey, bytes):
> =A0 =A0 =A0 =A0 raise TypeError, 'authkey should be a byte string'
>
> =A0 =A0 if authkey is not None:
> =A0 =A0 =A0 =A0 answer_challenge(c, authkey)
> =A0 =A0 =A0 =A0 deliver_challenge(c, authkey)
>
> =A0 =A0 return c
>
> if sys.platform !=3D 'win32':
>
> =A0 =A0 def Pipe(duplex=3DTrue):
> =A0 =A0 =A0 =A0 '''
> =A0 =A0 =A0 =A0 Returns pair of connection objects at either end of a pip=
e
> =A0 =A0 =A0 =A0 '''
> =A0 =A0 =A0 =A0 if duplex:
> =A0 =A0 =A0 =A0 =A0 =A0 s1, s2 =3D socket.socketpair()
> =A0 =A0 =A0 =A0 =A0 =A0 c1 =3D _multiprocessing.Connection(os.dup(s1.file=
no()))
> =A0 =A0 =A0 =A0 =A0 =A0 c2 =3D _multiprocessing.Connection(os.dup(s2.file=
no()))
> =A0 =A0 =A0 =A0 =A0 =A0 s1.close()
> =A0 =A0 =A0 =A0 =A0 =A0 s2.close()
> =A0 =A0 =A0 =A0 else:
> =A0 =A0 =A0 =A0 =A0 =A0 fd1, fd2 =3D os.pipe()
> =A0 =A0 =A0 =A0 =A0 =A0 c1 =3D _multiprocessing.Connection(fd1, writable=
=3DFalse)
> =A0 =A0 =A0 =A0 =A0 =A0 c2 =3D _multiprocessing.Connection(fd2, readable=
=3DFalse)
>
> =A0 =A0 =A0 =A0 return c1, c2
>
> else:
>
> =A0 =A0 from ._multiprocessing import win32
>
> =A0 =A0 def Pipe(duplex=3DTrue):
> =A0 =A0 =A0 =A0 '''
> =A0 =A0 =A0 =A0 Returns pair of connection objects at either end of a pip=
e
> =A0 =A0 =A0 =A0 '''
> =A0 =A0 =A0 =A0 address =3D arbitrary_address('AF_PIPE')
> =A0 =A0 =A0 =A0 if duplex:
> =A0 =A0 =A0 =A0 =A0 =A0 openmode =3D win32.PIPE_ACCESS_DUPLEX
> =A0 =A0 =A0 =A0 =A0 =A0 access =3D win32.GENERIC_READ | win32.GENERIC_WRI=
TE
> =A0 =A0 =A0 =A0 =A0 =A0 obsize, ibsize =3D BUFSIZE, BUFSIZE
> =A0 =A0 =A0 =A0 else:
> =A0 =A0 =A0 =A0 =A0 =A0 openmode =3D win32.PIPE_ACCESS_INBOUND
> =A0 =A0 =A0 =A0 =A0 =A0 access =3D win32.GENERIC_WRITE
> =A0 =A0 =A0 =A0 =A0 =A0 obsize, ibsize =3D 0, BUFSIZE
>
> =A0 =A0 =A0 =A0 h1 =3D win32.CreateNamedPipe(
> =A0 =A0 =A0 =A0 =A0 =A0 address, openmode,
> =A0 =A0 =A0 =A0 =A0 =A0 win32.PIPE_TYPE_MESSAGE | win32.PIPE_READMODE_MES=
SAGE |
> =A0 =A0 =A0 =A0 =A0 =A0 win32.PIPE_WAIT,
> =A0 =A0 =A0 =A0 =A0 =A0 1, obsize, ibsize, win32.NMPWAIT_WAIT_FOREVER, wi=
n32.NULL
> =A0 =A0 =A0 =A0 =A0 =A0 )
> =A0 =A0 =A0 =A0 h2 =3D win32.CreateFile(
> =A0 =A0 =A0 =A0 =A0 =A0 address, access, 0, win32.NULL, win32.OPEN_EXISTI=
NG, 0,
> win32.NULL
> =A0 =A0 =A0 =A0 =A0 =A0 )
> =A0 =A0 =A0 =A0 win32.SetNamedPipeHandleState(
> =A0 =A0 =A0 =A0 =A0 =A0 h2, win32.PIPE_READMODE_MESSAGE, None, None
> =A0 =A0 =A0 =A0 =A0 =A0 )
>
> =A0 =A0 =A0 =A0 try:
> =A0 =A0 =A0 =A0 =A0 =A0 win32.ConnectNamedPipe(h1, win32.NULL)
> =A0 =A0 =A0 =A0 except WindowsError, e:
> =A0 =A0 =A0 =A0 =A0 =A0 if e.args[0] !=3D win32.ERROR_PIPE_CONNECTED:
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 raise
>
> =A0 =A0 =A0 =A0 c1 =3D _multiprocessing.PipeConnection(h1, writable=3Ddup=
lex)
> =A0 =A0 =A0 =A0 c2 =3D _multiprocessing.PipeConnection(h2, readable=3Ddup=
lex)
>
> =A0 =A0 =A0 =A0 return c1, c2
>
> #
> # Definitions for connections based on sockets
> #
>
> class SocketListener(object):
> =A0 =A0 '''
> =A0 =A0 Representation of a socket which is bound to an address and
> listening
> =A0 =A0 '''
> # Aadido sslsock por xavi
> =A0 =A0 def __init__(self, address, family, backlog=3D1, sslsock=3DTrue):
> =A0 =A0 =A0 =A0 self._socket =3D socket.socket(getattr(socket, family))
> =A0 =A0 =A0 =A0 if sslsock =3D=3D True:
> =A0 =A0 =A0 =A0 =A0 =A0 print "SSL Enabled"
> =A0 =A0 =A0 =A0 =A0 =A0 self._socket =3D ssl.wrap_socket
> (self._socket,certfile=3D"cert.pem",server_side=3DTrue,ssl_version=3Dssl.=
PROTOCOL_TLSv1)
> =A0 =A0 =A0 =A0 self._socket.setsockopt(socket.SOL_SOCKET,
> socket.SO_REUSEADDR, 1)
> =A0 =A0 =A0 =A0 self._socket.bind(address)
> =A0 =A0 =A0 =A0 self._socket.listen(backlog)
> =A0 =A0 =A0 =A0 self._address =3D self._socket.getsockname()
> =A0 =A0 =A0 =A0 self._family =3D family
> =A0 =A0 =A0 =A0 self._last_accepted =3D None
>
> =A0 =A0 =A0 =A0 if family =3D=3D 'AF_UNIX':
> =A0 =A0 =A0 =A0 =A0 =A0 self._unlink =3D Finalize(
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 self, os.unlink, args=3D(address,), exitp=
riority=3D0
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 )
> =A0 =A0 =A0 =A0 else:
> =A0 =A0 =A0 =A0 =A0 =A0 self._unlink =3D None
>
> =A0 =A0 def accept(self):
> =A0 =A0 =A0 =A0 s, self._last_accepted =3D self._socket.accept()
> =A0 =A0 =A0 =A0 fd =3D duplicate(s.fileno())
> =A0 =A0 =A0 =A0 conn =3D _multiprocessing.Connection(fd)
> =A0 =A0 =A0 =A0 s.close()
> =A0 =A0 =A0 =A0 return conn
>
> =A0 =A0 def close(self):
> =A0 =A0 =A0 =A0 self._socket.close()
> =A0 =A0 =A0 =A0 if self._unlink is not None:
> =A0 =A0 =A0 =A0 =A0 =A0 self._unlink()
>
> def SocketClient(address, sslsock=3DTrue):
> =A0 =A0 '''
> =A0 =A0 Return a connection object connected to the socket given by
> `address`
> =A0 =A0 '''
> =A0 =A0 family =3D address_type(address)
> =A0 =A0 s =3D socket.socket( getattr(socket, family) )
> =A0 =A0 if sslsock =3D=3D True:
> =A0 =A0 =A0 =A0 '''
> =A0 =A0 =A0 =A0 print "SSL Enabled"
> =A0 =A0 =A0 =A0 '''
> =A0 =A0 =A0 =A0 s =3D ssl.wrap_socket
> (s,ssl_version=3Dssl.PROTOCOL_TLSv1,cert_reqs=3Dssl.CERT_NONE,ca_certs=3D=
None)
> =A0 =A0 while 1:
> =A0 =A0 =A0 =A0 try:
> =A0 =A0 =A0 =A0 =A0 =A0 s.connect(address)
> =A0 =A0 =A0 =A0 except socket.error, e:
> =A0 =A0 =A0 =A0 =A0 =A0 if e.args[0] !=3D errno.ECONNREFUSED: # connectio=
n refused
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 debug('failed to connect to address %s', =
address)
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 raise
> =A0 =A0 =A0 =A0 =A0 =A0 time.sleep(0.01)
> =A0 =A0 =A0 =A0 else:
> =A0 =A0 =A0 =A0 =A0 =A0 break
> =A0 =A0 else:
> =A0 =A0 =A0 =A0 raise
>
> =A0 =A0 fd =3D duplicate(s.fileno())
> =A0 =A0 conn =3D _multiprocessing.Connection(fd)
> =A0 =A0 s.close()
> =A0 =A0 return conn
>
> #
> # Definitions for connections based on named pipes
> #
>
> if sys.platform =3D=3D 'win32':
>
> =A0 =A0 class PipeListener(object):
> =A0 =A0 =A0 =A0 '''
> =A0 =A0 =A0 =A0 Representation of a named pipe
> =A0 =A0 =A0 =A0 '''
> =A0 =A0 =A0 =A0 def __init__(self, address, backlog=3DNone):
> =A0 =A0 =A0 =A0 =A0 =A0 self._address =3D address
> =A0 =A0 =A0 =A0 =A0 =A0 handle =3D win32.CreateNamedPipe(
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 address, win32.PIPE_ACCESS_DUPLEX,
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 win32.PIPE_TYPE_MESSAGE | win32.PIPE_READ=
MODE_MESSAGE
> |
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 win32.PIPE_WAIT,
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 win32.PIPE_UNLIMITED_INSTANCES, BUFSIZE, =
BUFSIZE,
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 win32.NMPWAIT_WAIT_FOREVER, win32.NULL
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 )
> =A0 =A0 =A0 =A0 =A0 =A0 self._handle_queue =3D [handle]
> =A0 =A0 =A0 =A0 =A0 =A0 self._last_accepted =3D None
>
> =A0 =A0 =A0 =A0 =A0 =A0 sub_debug('listener created with address=3D%r',
> self._address)
>
> =A0 =A0 =A0 =A0 =A0 =A0 self.close =3D Finalize(
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 self, PipeListener._finalize_pipe_listene=
r,
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 args=3D(self._handle_queue, self._address=
),
> exitpriority=3D0
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 )
>
> =A0 =A0 =A0 =A0 def accept(self):
> =A0 =A0 =A0 =A0 =A0 =A0 newhandle =3D win32.CreateNamedPipe(
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 self._address, win32.PIPE_ACCESS_DUPLEX,
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 win32.PIPE_TYPE_MESSAGE | win32.PIPE_READ=
MODE_MESSAGE
> |
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 win32.PIPE_WAIT,
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 win32.PIPE_UNLIMITED_INSTANCES, BUFSIZE, =
BUFSIZE,
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 win32.NMPWAIT_WAIT_FOREVER, win32.NULL
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 )
> =A0 =A0 =A0 =A0 =A0 =A0 self._handle_queue.append(newhandle)
> =A0 =A0 =A0 =A0 =A0 =A0 handle =3D self._handle_queue.pop(0)
> =A0 =A0 =A0 =A0 =A0 =A0 try:
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 win32.ConnectNamedPipe(handle, win32.NULL=
)
> =A0 =A0 =A0 =A0 =A0 =A0 except WindowsError, e:
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 if e.args[0] !=3D win32.ERROR_PIPE_CONNEC=
TED:
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 raise
> =A0 =A0 =A0 =A0 =A0 =A0 return _multiprocessing.PipeConnection(handle)
>
> =A0 =A0 =A0 =A0 @staticmethod
> =A0 =A0 =A0 =A0 def _finalize_pipe_listener(queue, address):
> =A0 =A0 =A0 =A0 =A0 =A0 sub_debug('closing listener with address=3D%r', a=
ddress)
> =A0 =A0 =A0 =A0 =A0 =A0 for handle in queue:
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 close(handle)
>
> =A0 =A0 def PipeClient(address):
> =A0 =A0 =A0 =A0 '''
> =A0 =A0 =A0 =A0 Return a connection object connected to the pipe given by=
....
>
> leer m=E1s =BB

0
x.sanz35 (3)
11/24/2009 10:11:45 PM
Reply: