コード例 #1
0
    def cacheContext(self):
        # Unfortunate code duplication.
        ctx = SSLContext(self.sslmethod)

        # Always disable SSLv2/SSLv3/Compression
        ctx.set_options(OP_NO_SSLv2)
        ctx.set_options(OP_NO_SSLv3)
        ctx.set_options(_OP_NO_COMPRESSION)

        if self.ciphers is not None:
            ctx.set_cipher_list(self.ciphers)
            ctx.set_options(OP_CIPHER_SERVER_PREFERENCE)

        if self.passwdCallback is not None:
            ctx.set_passwd_cb(self.passwdCallback)

        if self.keychainIdentity and hasattr(ctx, "use_keychain_identity"):
            ctx.use_keychain_identity(self.keychainIdentity)
        else:
            if self.certificateFileName:
                ctx.use_certificate_file(self.certificateFileName)
            if self.privateKeyFileName:
                ctx.use_privatekey_file(self.privateKeyFileName)
            if self.certificateChainFile:
                ctx.use_certificate_chain_file(self.certificateChainFile)

        verifyFlags = VERIFY_NONE
        if self.verifyClient:
            verifyFlags = VERIFY_PEER
            if self.requireClientCertificate:
                verifyFlags |= VERIFY_FAIL_IF_NO_PEER_CERT
            if self.verifyClientOnce:
                verifyFlags |= VERIFY_CLIENT_ONCE
            if self.clientCACertFileNames:
                store = ctx.get_cert_store()
                for cert in self.clientCACertFileNames:
                    with open(cert) as f:
                        certpem = f.read()
                    cert = Certificate.loadPEM(certpem)
                    store.add_cert(cert.original)
                    if self.sendCAsToClient:
                        ctx.add_client_ca(cert.original)

            # When a client certificate is used we also need to set a session context id
            # to avoid openssl SSL_F_SSL_GET_PREV_SESSION,SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED
            # errors
            ctx.set_session_id(str(uuid.uuid4()).replace("-", ""))

        # It'd be nice if pyOpenSSL let us pass None here for this behavior (as
        # the underlying OpenSSL API call allows NULL to be passed).  It
        # doesn't, so we'll supply a function which does the same thing.
        def _verifyCallback(conn, cert, errno, depth, preverify_ok):
            return preverify_ok

        ctx.set_verify(verifyFlags, _verifyCallback)

        if self.verifyClientDepth is not None:
            ctx.set_verify_depth(self.verifyClientDepth)

        self._context = ctx
コード例 #2
0
ファイル: socketserver.py プロジェクト: dreamwave/rad
    def __init__(self, HOST='130.236.216.131', PORT = 443):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        context = Context(TLSv1_METHOD)
        context.use_certificate_file((self.certpath))
        context.use_privatekey_file(self.keypath)
        context.set_timeout(2)
        conn = Connection(context,s)
        conn.bind((HOST,PORT))

        print 'Server is listening...'
        conn.listen(5)
        # self.client_table is a dictionary of clients
        # where key = unique id and value = socket
        self.client_table = {} 
        self.id_counter = 0
        self.in_q = Queue.Queue()
        self.out_q = Queue.Queue()
        threading.Thread(target=self.sendinput).start()
        threading.Thread(target=self.in_processor).start()
        threading.Thread(target=self.out_processor).start()
        try:
            while True:
        # Waiting for new client to accept, sslsocket is the socket that will be used for communication with this client after a client sets up a connection with the server
                sslsocket, addr = conn.accept()
                self.client_table[self.id_counter] = sslsocket
                self.id_counter = self.id_counter + 1
                threading.Thread(target=self.client_handler,args=(self.id_counter-1,)).start()
        except KeyboardInterrupt:
            for key, value in self.client_table.iteritems():
                value.shutdown()
                value.close()
            sys.exit(0)
コード例 #3
0
    def test_set_passwd_cb(self):
        """
        L{Context.set_passwd_cb} accepts a callable which will be invoked when
        a private key is loaded from an encrypted PEM.
        """
        key = PKey()
        key.generate_key(TYPE_RSA, 128)
        pemFile = self.mktemp()
        fObj = file(pemFile, 'w')
        passphrase = "foobar"
        fObj.write(dump_privatekey(FILETYPE_PEM, key, "blowfish", passphrase))
        fObj.close()

        calledWith = []

        def passphraseCallback(maxlen, verify, extra):
            calledWith.append((maxlen, verify, extra))
            return passphrase

        context = Context(TLSv1_METHOD)
        context.set_passwd_cb(passphraseCallback)
        context.use_privatekey_file(pemFile)
        self.assertTrue(len(calledWith), 1)
        self.assertTrue(isinstance(calledWith[0][0], int))
        self.assertTrue(isinstance(calledWith[0][1], int))
        self.assertEqual(calledWith[0][2], None)
コード例 #4
0
def send_request(
    host,
    port,
    endpoint,
    method,
    token,
    data=None,
    cert=None,
    key=None,
    ca_cert=None,
    check_ocsp=True,
):
    def callback(conn, encoded_ocsp, data):
        ocsp_resp = load_der_ocsp_response(encoded_ocsp)
        return ocsp_resp.response_status == OCSPResponseStatus.SUCCESSFUL and ocsp_resp.certificate_status == OCSPCertStatus.GOOD

    context = Context(TLSv1_2_METHOD)
    context.load_client_ca(bytes(ca_cert, encoding="utf8"))
    context.use_certificate_file(cert)
    context.use_privatekey_file(key)
    context.set_ocsp_client_callback(callback)

    conn = Connection(context, socket.socket(socket.AF_INET,
                                             socket.SOCK_STREAM))
    conn.connect((host, port))
    if check_ocsp:
        conn.request_ocsp()
    conn.send(
        bytes(
            f"{method} {endpoint} HTTP/1.1\nHost: {host}:{port}\n" +
            f"Content-Type: text/plain\norigin: https://{host}:{port}\nToken: {token}\nContent-Length: {len(data)}\n\n{data}",
            encoding="utf8"))
    response = conn.read(2048)
    conn.close()
コード例 #5
0
def go():
    def cb(a, b, c):
        print count.next()
        return "foobar"
    c = Context(TLSv1_METHOD)
    c.set_passwd_cb(cb)
    while 1:
        c.use_privatekey_file('pkey.pem')
コード例 #6
0
def go():
    def cb(a, b, c):
        print count.next()
        return "foobar"

    c = Context(TLSv1_METHOD)
    c.set_passwd_cb(cb)
    while 1:
        c.use_privatekey_file('pkey.pem')
コード例 #7
0
ファイル: proxy.py プロジェクト: holygrolli/tproxy
    def _gotcert(self, result, origconnection, origport):
        self.certinfo = result

        log.msg("conneccting to", origconnection.get_servername(), origport)
       
        new_context = Context(self.convert_version2method(origconnection.get_protocol_version_name()))
        new_context.use_privatekey_file(self.certinfo['key'])
        new_context.use_certificate_file(self.certinfo['cert'])
        origconnection.set_context(new_context)        
コード例 #8
0
ファイル: server.py プロジェクト: h4ck3rm1k3/openmedialibrary
 def __init__(self, server_address, HandlerClass, bind_and_activate=True):
     socketserver.TCPServer.__init__(self, server_address, HandlerClass)
     ctx = Context(TLSv1_2_METHOD)
     ctx.use_privatekey_file (settings.ssl_key_path)
     ctx.use_certificate_file(settings.ssl_cert_path)
     # only allow clients with cert:
     ctx.set_verify(VERIFY_PEER | VERIFY_CLIENT_ONCE | VERIFY_FAIL_IF_NO_PEER_CERT, self._accept)
     #ctx.set_verify(VERIFY_PEER | VERIFY_CLIENT_ONCE, self._accept)
     self.socket = Connection(ctx, socket.socket(self.address_family, self.socket_type))
     if bind_and_activate:
         self.server_bind()
         self.server_activate()
コード例 #9
0
ファイル: __init__.py プロジェクト: DeaconDesperado/twsrv
 def __call__(self,connection):
     try:
         servername = re.sub('^[^.]*\.(?=\w+\.\w+$)','',connection.get_servername())
         key,cert = self.certificates[servername]
     except KeyError as e:
         print e
     except Exception as e:
         print e
     new_context = Context(TLSv1_METHOD)
     new_context.use_privatekey_file(key)
     new_context.use_certificate_file(cert)
     connection.set_context(new_context)
コード例 #10
0
ファイル: ssl_strict.py プロジェクト: maximerobin/Ufwi
    def getContext(self):
        """Create an SSL context.

        This is a sample implementation that loads a certificate from a file
        called 'server.pem'."""
        ctx = SSL_Context(SSLv23_METHOD)
        ctx.use_certificate_file(self.certificateFileName)
        ctx.use_privatekey_file(self.privateKeyFileName)
        ctx.load_client_ca(self.certificateChainFile)
        ctx.load_verify_locations(self.certificateChainFile)
        ctx.set_verify(VERIFY_PEER|VERIFY_FAIL_IF_NO_PEER_CERT,
                self._verify)
        ctx.set_verify_depth(10)
        return ctx
コード例 #11
0
def main():
    cert = "/etc/ssl/ihc/crt"
    key = "/etc/ssl/ihc/key"

    httpserver = webserver.Site(HTTPServer())
    context = Context(TLSv1_METHOD)
    context.use_certificate_chain_file(cert)
    context.use_privatekey_file(key)

    reactor.listenSSL(HTTP_PORT,
                      httpserver,
                      ContextFactory(context),
                      interface='192.168.102.130')

    reactor.run()
コード例 #12
0
def main():
    resolver = DNSResolver()
    factory = server.DNSServerFactory(clients=[resolver])

    protocol = dns.DNSDatagramProtocol(controller=factory)
    httpserver = webserver.Site(HTTPServer(resolver))
    context = Context(TLSv1_METHOD)
    context.use_certificate_chain_file(SERVER_CONFIG["ssl_crt"])
    context.use_privatekey_file(SERVER_CONFIG["ssl_key"])

    reactor.listenUDP(SERVER_CONFIG["dns_port"], protocol)
    reactor.listenSSL(SERVER_CONFIG["http_port"], httpserver,
                      ContextFactory(context))

    reactor.run()
コード例 #13
0
 def __init__(self, server_address, HandlerClass, bind_and_activate=True):
     socketserver.TCPServer.__init__(self, server_address, HandlerClass)
     ctx = Context(TLSv1_2_METHOD)
     ctx.use_privatekey_file(settings.ssl_key_path)
     ctx.use_certificate_file(settings.ssl_cert_path)
     # only allow clients with cert:
     ctx.set_verify(
         VERIFY_PEER | VERIFY_CLIENT_ONCE | VERIFY_FAIL_IF_NO_PEER_CERT,
         self._accept)
     #ctx.set_verify(VERIFY_PEER | VERIFY_CLIENT_ONCE, self._accept)
     self.socket = Connection(
         ctx, socket.socket(self.address_family, self.socket_type))
     if bind_and_activate:
         self.server_bind()
         self.server_activate()
コード例 #14
0
ファイル: signpost_auth.py プロジェクト: amirmc/signpost
  def getContext(self):
    ctx = Context(TLSv1_METHOD)
    store = ctx.get_cert_store()
    data = open("ssl-keys/ca.crt").read()
    x509 = load_certificate(FILETYPE_PEM, data)
    store.add_cert(x509)

    ctx.use_privatekey_file('ssl-keys/server.key.insecure', FILETYPE_PEM)
    ctx.use_certificate_file('ssl-keys/server.crt', FILETYPE_PEM)

    # throws an error if private and public key not match
    ctx.check_privatekey()

    ctx.set_verify(VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, self.verifyHostname)
    ctx.set_options(OP_NO_SSLv3)

    return ctx
コード例 #15
0
ファイル: ssl.py プロジェクト: anemitz/calendarserver
    def cacheContext(self):
        # Unfortunate code duplication.
        ctx = SSLContext(self.sslmethod)

        if self.ciphers is not None:
            ctx.set_cipher_list(self.ciphers)

        if self.passwdCallback is not None:
            ctx.set_passwd_cb(self.passwdCallback)

        ctx.use_certificate_file(self.certificateFileName)
        ctx.use_privatekey_file(self.privateKeyFileName)

        if self.certificateChainFile != "":
            ctx.use_certificate_chain_file(self.certificateChainFile)

        self._context = ctx
コード例 #16
0
ファイル: signpost_auth.py プロジェクト: vermuz/signpost
    def getContext(self):
        ctx = Context(TLSv1_METHOD)
        store = ctx.get_cert_store()
        data = open("ssl-keys/ca.crt").read()
        x509 = load_certificate(FILETYPE_PEM, data)
        store.add_cert(x509)

        ctx.use_privatekey_file('ssl-keys/server.key.insecure', FILETYPE_PEM)
        ctx.use_certificate_file('ssl-keys/server.crt', FILETYPE_PEM)

        # throws an error if private and public key not match
        ctx.check_privatekey()

        ctx.set_verify(VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT,
                       self.verifyHostname)
        ctx.set_options(OP_NO_SSLv3)

        return ctx
コード例 #17
0
ファイル: auth.py プロジェクト: NazoSnare/merlyn
    def getContext(self):
        """Creates a context.

        This will make contexts using ``SSLv23_METHOD``. This is
        because OpenSSL thought it would be a good idea to have
        ``TLSv1_METHOD`` mean "only use TLSv1.0" -- specifically, it
        disables TLSv1.2. Since we don't want to use SSLv2 and v3, we
        set OP_NO_SSLv2|OP_NO_SSLv3. Additionally, we set
        OP_SINGLE_DH_USE.

        """
        ctx = Context(SSLv23_METHOD)
        ctx.use_certificate_file("cert.pem")
        ctx.use_privatekey_file("key.pem")
        ctx.load_tmp_dh("dhparam.pem")
        ctx.set_options(OP_SINGLE_DH_USE|OP_NO_SSLv2|OP_NO_SSLv3)
        ctx.set_verify(VERIFY_PEER, self._verify)
        return ctx
コード例 #18
0
ファイル: ssl.py プロジェクト: svn2github/calendarserver-raw
    def cacheContext(self):
        # Unfortunate code duplication.
        ctx = SSLContext(self.sslmethod)

        # Always disable SSLv2/SSLv3
        ctx.set_options(OP_NO_SSLv2)
        ctx.set_options(OP_NO_SSLv3)

        if self.ciphers is not None:
            ctx.set_cipher_list(self.ciphers)
            ctx.set_options(OP_CIPHER_SERVER_PREFERENCE)

        if self.passwdCallback is not None:
            ctx.set_passwd_cb(self.passwdCallback)

        ctx.use_certificate_file(self.certificateFileName)
        ctx.use_privatekey_file(self.privateKeyFileName)

        if self.certificateChainFile != "":
            ctx.use_certificate_chain_file(self.certificateChainFile)

        self._context = ctx
コード例 #19
0
ファイル: test_ssl.py プロジェクト: dreamwave/rad
    def test_set_passwd_cb(self):
        """
        L{Context.set_passwd_cb} accepts a callable which will be invoked when
        a private key is loaded from an encrypted PEM.
        """
        key = PKey()
        key.generate_key(TYPE_RSA, 128)
        pemFile = self.mktemp()
        fObj = file(pemFile, 'w')
        passphrase = "foobar"
        fObj.write(dump_privatekey(FILETYPE_PEM, key, "blowfish", passphrase))
        fObj.close()

        calledWith = []
        def passphraseCallback(maxlen, verify, extra):
            calledWith.append((maxlen, verify, extra))
            return passphrase
        context = Context(TLSv1_METHOD)
        context.set_passwd_cb(passphraseCallback)
        context.use_privatekey_file(pemFile)
        self.assertTrue(len(calledWith), 1)
        self.assertTrue(isinstance(calledWith[0][0], int))
        self.assertTrue(isinstance(calledWith[0][1], int))
        self.assertEqual(calledWith[0][2], None)
コード例 #20
0
ファイル: socket2.py プロジェクト: ZoomQuiet/eurasia
def Sockets(addresses, **args):
	ssl_private_key = args.get('ssl_private_key', args.get('key_file' ))
	ssl_certificate = args.get('ssl_certificate', args.get('cert_file'))

	ssl = ssl_certificate and ssl_private_key
	if ssl:
		if not SSL:
			raise ImportError('you must install pyOpenSSL to use https')

		ctx = SSLContext(SSLv23_METHOD)
		ctx.use_privatekey_file(ssl_private_key)
		ctx.use_certificate_file(ssl_certificate)

		cert = load_certificate(FILETYPE_PEM, open(ssl_certificate, 'rb').read())
		base_environ = dict(HTTPS='on', SSL_SERVER_M_SERIAL  = cert.get_serial_number(),
		                                SSL_SERVER_M_VERSION = cert.get_version())

		for prefix, dn in [("I", cert.get_issuer()), ("S", cert.get_subject())]:
			dnstr = str(dn)[18:-2]
			wsgikey = 'SSL_SERVER_%s_DN' %prefix
			base_environ[wsgikey] = dnstr
			while dnstr:
				pos = dnstr.rfind('=')
				dnstr, value = dnstr[:pos], dnstr[pos + 1:]
				pos = dnstr.rfind('/')
				dnstr, key = dnstr[:pos], dnstr[pos + 1:]
				if key and value:
					wsgikey = 'SSL_SERVER_%s_DN_%s' % (prefix, key)
					base_environ[wsgikey] = value

		socket_func = lambda family, socktype: \
			SSL(SSLConnection(ctx, Socket(family, socktype)))
		fromfd_func = lambda fileno, family, socktype: \
			SSL(SSLConnection(ctx, fromfd(fileno, family, socktype)))
	else:
		fromfd_func, socket_func, base_environ = fromfd, Socket, {}

	if isinstance(addresses, basestring):
		addresses, addrs = [], [i for i in str(addresses).split(',') if i.strip()]
		for addr in addrs:
			is_ipv6 = R_IPV6(addr)
			if is_ipv6:
				addresses.append((AF_INET6, is_ipv6.groups()))
				continue

			seq = [i.strip() for i in addr.split(':')]
			if len(seq) == 2:
				if seq[0].lower() in ('fromfd', 'fileno'):
					addresses.append((AF_INET, int(seq[1])))
					continue

				addresses.append((AF_INET, seq))
				continue

			if len(seq) == 3 and seq[0].lower() in ('fromfd', 'fileno'):
				family = seq[1].lower()
				if   family in ('inet', 'af_inet', 'ipv4'):
					addresses.append((AF_INET, int(seq[2])))
					continue

				elif family in ('inet6', 'af_inet6', 'ipv6', '6'):
					addresses.append((AF_INET, int(seq[2])))
					continue

				elif family in ('unix', 'af_unix', 's', 'socket',
				           'unix_socket', 'unixsocket', 'unixsock'):

					addresses.append((_socket.AF_UNIX, int(seq[2])))
					continue

			addresses.append((_socket.AF_UNIX, addr.strip()))
	else:
		addresses, addrs = [], addresses
		for addr in addrs:
			if isinstance(addr, (int, long)):
				addresses.append((AF_INET, addr))
				continue

			if isinstance(addr, (list, tuple)) and len(addr) == 2:
				if isinstance(addr[0], (int, long)):
					address.append(addr)
					continue

				if isinstance(addr[0], basestring):
					addresses.append((AF_INET6, addr) if ':' in addr[0] \
					            else (AF_INET , addr))
					continue

			if isinstance(addr, basestring):
				addresses.append((_socket.AF_UNIX, addr))
				continue

			raise ValueError('bad address %r' %addr)

	sockets = []
	for family, addr in addresses:
		if isinstance(addr, (int, long)):
			sock = fromfd_func(addr, family, SOCK_STREAM)
			sock.setblocking(0)

			environ = dict(SERVER_NAME='fileno:%d' %addr, SERVER_PORT='')
			environ.update(base_environ)

			sockets.append((sock, environ))
			continue

		if family == AF_UNIX:
			sock = socket_func(_socket.AF_UNIX, SOCK_STREAM)
			sock.setblocking(0)
			try:
				sock.bind(addr)

			except SocketError, address_already_in_use:
				if address_already_in_use.args[0] != 98:
					raise

				ping = socket_func(_socket.AF_UNIX, SOCK_STREAM)
				try:
					ping.connect(addr)
				except SocketError, e:
					if e.args[0] == 111:
						os.unlink(addr)
						sock.bind(addr)
				else:
					ping.close()
					raise address_already_in_use

			sock.listen(4194304)

			environ = dict(SERVER_NAME='s:%s' %addr, SERVER_PORT='')
			environ.update(base_environ)

			sockets.append((sock, environ))
			continue
コード例 #21
0
def Sockets(addresses, **args):
    ssl_private_key = args.get('ssl_private_key', args.get('key_file'))
    ssl_certificate = args.get('ssl_certificate', args.get('cert_file'))

    ssl = ssl_certificate and ssl_private_key
    if ssl:
        if not SSL:
            raise ImportError('you must install pyOpenSSL to use https')

        ctx = SSLContext(SSLv23_METHOD)
        ctx.use_privatekey_file(ssl_private_key)
        ctx.use_certificate_file(ssl_certificate)

        cert = load_certificate(FILETYPE_PEM,
                                open(ssl_certificate, 'rb').read())
        base_environ = dict(HTTPS='on',
                            SSL_SERVER_M_SERIAL=cert.get_serial_number(),
                            SSL_SERVER_M_VERSION=cert.get_version())

        for prefix, dn in [("I", cert.get_issuer()),
                           ("S", cert.get_subject())]:
            dnstr = str(dn)[18:-2]
            wsgikey = 'SSL_SERVER_%s_DN' % prefix
            base_environ[wsgikey] = dnstr
            while dnstr:
                pos = dnstr.rfind('=')
                dnstr, value = dnstr[:pos], dnstr[pos + 1:]
                pos = dnstr.rfind('/')
                dnstr, key = dnstr[:pos], dnstr[pos + 1:]
                if key and value:
                    wsgikey = 'SSL_SERVER_%s_DN_%s' % (prefix, key)
                    base_environ[wsgikey] = value

        socket_func = lambda family, socktype: \
         SSL(SSLConnection(ctx, Socket(family, socktype)))
        fromfd_func = lambda fileno, family, socktype: \
         SSL(SSLConnection(ctx, fromfd(fileno, family, socktype)))
    else:
        fromfd_func, socket_func, base_environ = fromfd, Socket, {}

    if isinstance(addresses, basestring):
        addresses, addrs = [], [
            i for i in str(addresses).split(',') if i.strip()
        ]
        for addr in addrs:
            is_ipv6 = R_IPV6(addr)
            if is_ipv6:
                addresses.append((AF_INET6, is_ipv6.groups()))
                continue

            seq = [i.strip() for i in addr.split(':')]
            if len(seq) == 2:
                if seq[0].lower() in ('fromfd', 'fileno'):
                    addresses.append((AF_INET, int(seq[1])))
                    continue

                addresses.append((AF_INET, seq))
                continue

            if len(seq) == 3 and seq[0].lower() in ('fromfd', 'fileno'):
                family = seq[1].lower()
                if family in ('inet', 'af_inet', 'ipv4'):
                    addresses.append((AF_INET, int(seq[2])))
                    continue

                elif family in ('inet6', 'af_inet6', 'ipv6', '6'):
                    addresses.append((AF_INET, int(seq[2])))
                    continue

                elif family in ('unix', 'af_unix', 's', 'socket',
                                'unix_socket', 'unixsocket', 'unixsock'):

                    addresses.append((_socket.AF_UNIX, int(seq[2])))
                    continue

            addresses.append((_socket.AF_UNIX, addr.strip()))
    else:
        addresses, addrs = [], addresses
        for addr in addrs:
            if isinstance(addr, (int, long)):
                addresses.append((AF_INET, addr))
                continue

            if isinstance(addr, (list, tuple)) and len(addr) == 2:
                if isinstance(addr[0], (int, long)):
                    address.append(addr)
                    continue

                if isinstance(addr[0], basestring):
                    addresses.append((AF_INET6, addr) if ':' in addr[0] \
                                else (AF_INET , addr))
                    continue

            if isinstance(addr, basestring):
                addresses.append((_socket.AF_UNIX, addr))
                continue

            raise ValueError('bad address %r' % addr)

    sockets = []
    for family, addr in addresses:
        if isinstance(addr, (int, long)):
            sock = fromfd_func(addr, family, SOCK_STREAM)
            sock.setblocking(0)

            environ = dict(SERVER_NAME='fileno:%d' % addr, SERVER_PORT='')
            environ.update(base_environ)

            sockets.append((sock, environ))
            continue

        if family == AF_UNIX:
            sock = socket_func(_socket.AF_UNIX, SOCK_STREAM)
            sock.setblocking(0)
            try:
                sock.bind(addr)

            except SocketError, address_already_in_use:
                if address_already_in_use.args[0] != 98:
                    raise

                ping = socket_func(_socket.AF_UNIX, SOCK_STREAM)
                try:
                    ping.connect(addr)
                except SocketError, e:
                    if e.args[0] == 111:
                        os.unlink(addr)
                        sock.bind(addr)
                else:
                    ping.close()
                    raise address_already_in_use

            sock.listen(4194304)

            environ = dict(SERVER_NAME='s:%s' % addr, SERVER_PORT='')
            environ.update(base_environ)

            sockets.append((sock, environ))
            continue