Python socket.fromfd() Examples

The following are code examples for showing how to use socket.fromfd(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: node-agent   Author: Tendrl   File: handler.py    (license) View Source Project 6 votes vote down vote up
def bind_unix_listener(self):
        # http://0pointer.de/blog/projects/systemd.html (search "file
        # descriptor 3")
        try:
            socket_fd = 3
            self.sock = socket.fromfd(socket_fd, socket.AF_UNIX,
                                      socket.SOCK_STREAM)
            self.sock.listen(50)
            return self.sock
        except (TypeError, BlockingIOError, socket.error, ValueError):
            pass
        try:
            self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            if os.path.exists(MESSAGE_SOCK_PATH):
                os.remove(MESSAGE_SOCK_PATH)
            self.sock.bind(MESSAGE_SOCK_PATH)
            self.sock.listen(50)
            return self.sock
        except Exception as ex:
            exc_type, exc_value, exc_tb = sys.exc_info()
            traceback.print_exception(exc_type, exc_value, exc_tb,
                                      file=sys.stderr)
            raise ex 
Example 2
Project: bluetool   Author: emlid   File: blueserver.py    (license) View Source Project 6 votes vote down vote up
def NewConnection(self, path, fd, properties):
        address = str(path)
        address = address[len(address) - 17:len(address)]
        address = address.replace("_", ":")
        print_info("Connected: {}\n".format(address))

        blue_socket = socket.fromfd(
            fd.take(), socket.AF_UNIX, socket.SOCK_STREAM)

        socket_sink = SocketSink(sock=blue_socket)
        self.bridge = TCPBridge(
            sink=socket_sink,
            port_in=self.tcp_port_in,
            port_out=self.tcp_port_out)

        try:
            self.bridge.start(in_background=False)
        except TCPBridgeError as error:
            print_error(str(error) + "\n")

        self.bridge.stop()
        blue_socket.close()

        print_info("Disconnected: {}\n".format(address))
        Bluetooth().disconnect(address) 
Example 3
Project: CodeLabs   Author: TheIoTLearningInitiative   File: bluetoothspp.py    (license) View Source Project 6 votes vote down vote up
def NewConnection(self, path, fd, properties):
		self.fd = fd.take()
		print("NewConnection(%s, %d)" % (path, self.fd))


		server_sock = socket.fromfd(self.fd, socket.AF_UNIX, socket.SOCK_STREAM)
		server_sock.setblocking(1)
		server_sock.send("This is Edison SPP loopback test\nAll data will be loopback\nPlease start:\n")

		myfifo.openFifo()

		print('enter recv loop\n')
		try:
		    while True:
		        data = server_sock.recv(1024)
		        print("received: %s" % data)
		        myfifo.writeFifo(data)
		        #server_sock.send("looping back: %s\n" % data)
		except IOError as err:
		    print (err)
		    pass

		server_sock.close()
		print("all done") 
Example 4
Project: CodeLabs   Author: TheIoTLearningInitiative   File: SPP-loopback.py    (license) View Source Project 6 votes vote down vote up
def NewConnection(self, path, fd, properties):
		self.fd = fd.take()
		print("NewConnection(%s, %d)" % (path, self.fd))


		server_sock = socket.fromfd(self.fd, socket.AF_UNIX, socket.SOCK_STREAM)
		server_sock.setblocking(1)
		server_sock.send("This is Edison SPP loopback test\nAll data will be loopback\nPlease start:\n")

		try:
		    while True:
		        data = server_sock.recv(1024)
		        print("received: %s" % data)
			server_sock.send("looping back: %s\n" % data)
		except IOError:
		    pass

		server_sock.close()
		print("all done") 
Example 5
Project: CodeLabs   Author: TheIoTLearningInitiative   File: spp.py    (license) View Source Project 6 votes vote down vote up
def NewConnection(self, path, fd, properties):
		self.fd = fd.take()
                device_path = os.path.basename(path)
		print("\nConnected to %s\nPress [ENTER] to continue" % device_path)

		server_sock = socket.fromfd(self.fd, socket.AF_UNIX, socket.SOCK_STREAM)
		server_sock.settimeout(1)
		server_sock.send("Hello, this is Edison!")
		try:
		    while True:
                        try:
                            data = server_sock.recv(1024)
                            gardening_system.function(data)
                            if data == 'b':
                                server_sock.send(gardening_system.requestData())
                        except socket.timeout:
                            pass
                        gardening_system.myProgram()
		except IOError:
		    pass
		server_sock.close()
                print("\nYour device is now disconnected\nPress [ENTER] to continue") 
Example 6
Project: CodeLabs   Author: TheIoTLearningInitiative   File: spp.py    (license) View Source Project 6 votes vote down vote up
def processSockets(fd):
    data = ""
    server_sock = socket.fromfd(fd,
                                socket.AF_UNIX,
                                socket.SOCK_STREAM)
    server_sock.settimeout(1)
    server_sock.send("Hello, this is Edison!")
    try:
        while not closing:
            try:
                data = server_sock.recv(1024)
                print ("Here's data %s" % data)
                result = ha.callFunction(data)
                if result:
                    server_sock.send(result)
            except socket.timeout:
                pass
    except IOError:
        pass
    server_sock.close()


# Agent class 
Example 7
Project: CodeLabs   Author: TheIoTLearningInitiative   File: spp.py    (license) View Source Project 6 votes vote down vote up
def NewConnection(self, path, fd, properties):
		self.fd = fd.take()
                device_path = os.path.basename(path)
		print("\nConnected to %s\nPress [ENTER] to continue" % device_path)

		server_sock = socket.fromfd(self.fd, socket.AF_UNIX, socket.SOCK_STREAM)
		server_sock.settimeout(1)
		server_sock.send("Hello, this is Edison!")
		try:
		    while True:
                        try:
                            data = server_sock.recv(1024)
                            temperature_monitor.function(data)
                            if data == 'get':
                                server_sock.send(temperature_monitor.requestData())
                        except socket.timeout:
                            pass
                        temperature_monitor.myProgram()
		except IOError:
		    pass
		server_sock.close()
                print("\nYour device is now disconnected\nPress [ENTER] to continue") 
Example 8
Project: ouroboros   Author: pybee   File: _test_multiprocessing.py    (license) View Source Project 6 votes vote down vote up
def get_high_socket_fd(self):
        if WIN32:
            # The child process will not have any socket handles, so
            # calling socket.fromfd() should produce WSAENOTSOCK even
            # if there is a handle of the same number.
            return socket.socket().detach()
        else:
            # We want to produce a socket with an fd high enough that a
            # freshly created child process will not have any fds as high.
            fd = socket.socket().detach()
            to_close = []
            while fd < 50:
                to_close.append(fd)
                fd = os.dup(fd)
            for x in to_close:
                os.close(x)
            return fd 
Example 9
Project: zenchmarks   Author: squeaky-pl   File: pullpipe.py    (license) View Source Project 6 votes vote down vote up
def recvfd(socketfd):
    """
    Receive a file descriptor from a L{sendmsg} message on the given C{AF_UNIX}
    socket.

    @param socketfd: An C{AF_UNIX} socket, attached to another process waiting
        to send sockets via the ancillary data mechanism in L{send1msg}.

    @param fd: C{int}

    @return: a 2-tuple of (new file descriptor, description).
    @rtype: 2-tuple of (C{int}, C{bytes})
    """
    ourSocket = socket.fromfd(socketfd, socket.AF_UNIX, socket.SOCK_STREAM)
    data, ancillary, flags = recvmsg(ourSocket)
    [(cmsgLevel, cmsgType, packedFD)] = ancillary
    # cmsgLevel and cmsgType really need to be SOL_SOCKET / SCM_RIGHTS, but
    # since those are the *only* standard values, there's not much point in
    # checking.
    [unpackedFD] = unpack("i", packedFD)
    return (unpackedFD, data) 
Example 10
Project: zenchmarks   Author: squeaky-pl   File: tcp.py    (license) View Source Project 6 votes vote down vote up
def _fromListeningDescriptor(cls, reactor, fd, addressFamily, factory):
        """
        Create a new L{Port} based on an existing listening I{SOCK_STREAM}
        socket.

        Arguments are the same as to L{Port.__init__}, except where noted.

        @param fd: An integer file descriptor associated with a listening
            socket.  The socket must be in non-blocking mode.  Any additional
            attributes desired, such as I{FD_CLOEXEC}, must also be set already.

        @param addressFamily: The address family (sometimes called I{domain}) of
            the existing socket.  For example, L{socket.AF_INET}.

        @return: A new instance of C{cls} wrapping the socket given by C{fd}.
        """
        port = socket.fromfd(fd, addressFamily, cls.socketType)
        interface = port.getsockname()[0]
        self = cls(None, factory, None, interface, reactor)
        self._preexistingSocket = port
        return self 
Example 11
Project: plex-for-kodi-mod   Author: mrclemds   File: http.py    (license) View Source Project 6 votes vote down vote up
def killSocket(self):
        if not self.currentResponse:
            return

        try:
            socket.fromfd(self.currentResponse.raw.fileno(), socket.AF_INET, socket.SOCK_STREAM).shutdown(socket.SHUT_RDWR)
            return
        except AttributeError:
            pass
        except Exception, e:
            util.ERROR(err=e)

        try:
            self.currentResponse.raw._fp.fp._sock.shutdown(socket.SHUT_RDWR)
        except AttributeError:
            pass
        except Exception, e:
            util.ERROR(err=e) 
Example 12
Project: kbe_server   Author: xiaohaoppy   File: _test_multiprocessing.py    (license) View Source Project 6 votes vote down vote up
def get_high_socket_fd(self):
        if WIN32:
            # The child process will not have any socket handles, so
            # calling socket.fromfd() should produce WSAENOTSOCK even
            # if there is a handle of the same number.
            return socket.socket().detach()
        else:
            # We want to produce a socket with an fd high enough that a
            # freshly created child process will not have any fds as high.
            fd = socket.socket().detach()
            to_close = []
            while fd < 50:
                to_close.append(fd)
                fd = os.dup(fd)
            for x in to_close:
                os.close(x)
            return fd 
Example 13
Project: kinect-2-libras   Author: inessadl   File: reduction.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def fromfd(fd, family, type_, proto=0):
    s = socket.fromfd(fd, family, type_, proto)
    if s.__class__ is not socket.socket:
        s = socket.socket(_sock=s)
    return s 
Example 14
Project: kinect-2-libras   Author: inessadl   File: reduction.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def rebuild_socket(reduced_handle, family, type_, proto):
    fd = rebuild_handle(reduced_handle)
    _sock = fromfd(fd, family, type_, proto)
    close(fd)
    return _sock 
Example 15
Project: Flask_Blog   Author: sugarguo   File: preforkserver.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def socketpair():
        s1, s2 = eunuchs.socketpair.socketpair()
        p, c = (socket.fromfd(s1, socket.AF_UNIX, socket.SOCK_STREAM),
                socket.fromfd(s2, socket.AF_UNIX, socket.SOCK_STREAM))
        os.close(s1)
        os.close(s2)
        return p, c 
Example 16
Project: Flask_Blog   Author: sugarguo   File: serving.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def __init__(self, host, port, app, handler=None,
                 passthrough_errors=False, ssl_context=None, fd=None):
        if handler is None:
            handler = WSGIRequestHandler

        self.address_family = select_ip_version(host, port)

        if fd is not None:
            real_sock = socket.fromfd(fd, self.address_family,
                                      socket.SOCK_STREAM)
            port = 0
        HTTPServer.__init__(self, (host, int(port)), handler)
        self.app = app
        self.passthrough_errors = passthrough_errors
        self.shutdown_signal = False
        self.host = host
        self.port = port

        # Patch in the original socket.
        if fd is not None:
            self.socket.close()
            self.socket = real_sock
            self.server_address = self.socket.getsockname()

        if ssl_context is not None:
            if isinstance(ssl_context, tuple):
                ssl_context = load_ssl_context(*ssl_context)
            if ssl_context == 'adhoc':
                ssl_context = generate_adhoc_ssl_context()
            # If we are on Python 2 the return value from socket.fromfd
            # is an internal socket object but what we need for ssl wrap
            # is the wrapper around it :(
            sock = self.socket
            if PY2 and not isinstance(sock, socket.socket):
                sock = socket.socket(sock.family, sock.type, sock.proto, sock)
            self.socket = ssl_context.wrap_socket(sock, server_side=True)
            self.ssl_context = ssl_context
        else:
            self.ssl_context = None 
Example 17
Project: swjtu-pyscraper   Author: Desgard   File: serving.py    (MIT License) View Source Project 5 votes vote down vote up
def __init__(self, host, port, app, handler=None,
                 passthrough_errors=False, ssl_context=None, fd=None):
        if handler is None:
            handler = WSGIRequestHandler

        self.address_family = select_ip_version(host, port)

        if fd is not None:
            real_sock = socket.fromfd(fd, self.address_family,
                                      socket.SOCK_STREAM)
            port = 0
        HTTPServer.__init__(self, (host, int(port)), handler)
        self.app = app
        self.passthrough_errors = passthrough_errors
        self.shutdown_signal = False
        self.host = host
        self.port = port

        # Patch in the original socket.
        if fd is not None:
            self.socket.close()
            self.socket = real_sock
            self.server_address = self.socket.getsockname()

        if ssl_context is not None:
            if isinstance(ssl_context, tuple):
                ssl_context = load_ssl_context(*ssl_context)
            if ssl_context == 'adhoc':
                ssl_context = generate_adhoc_ssl_context()
            # If we are on Python 2 the return value from socket.fromfd
            # is an internal socket object but what we need for ssl wrap
            # is the wrapper around it :(
            sock = self.socket
            if PY2 and not isinstance(sock, socket.socket):
                sock = socket.socket(sock.family, sock.type, sock.proto, sock)
            self.socket = ssl_context.wrap_socket(sock, server_side=True)
            self.ssl_context = ssl_context
        else:
            self.ssl_context = None 
Example 18
Project: ave   Author: sonyxperiadev   File: _broker.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 5 votes vote down vote up
def adopt_sessions(self):
        if not self.fdtx_path:
            return
        fdtx = FdTx(None)
        fdtx.connect(self.fdtx_path, 5)
        # receive open file descriptors together with their associated authkeys
        while True:
            try: # future safety: double the needed message length, two fd's
                authkey, fd = fdtx.get(AUTHKEY_LENGTH*2, 2)
            except ConnectionClosed:
                break # other end sent all it had
            if authkey not in self.adoption:
                continue # session died during handover
            self.adoption[authkey]['fd'] = fd[0] # just one fd per message
        for authkey in self.adoption:
            if 'fd' not in self.adoption[authkey]:
                continue # session died during handover
            # reconnect the session
            fd      = self.adoption[authkey]['fd']
            pid     = self.adoption[authkey]['pid']
            address = tuple(self.adoption[authkey]['address'])
            # represent the adopted session by an AdoptedSession instance that
            # only implements .pid and .terminate()
            local   = AdoptedSession(pid)
            sock    = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
            remote  = RemoteSession(address, authkey, timeout=1, sock=sock)
            self.add_connection(remote._connection, authkey)
            self.sessions[authkey] = (local, remote)

            # recreate the allocation records
            alloc   = self.adoption[authkey]['allocations']
            for a in alloc:
                resource   = a['profile']
                collateral = a['collateral']
                self.allocators['local'].allocate(resource, remote, collateral) 
Example 19
Project: ave   Author: sonyxperiadev   File: _broker.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 5 votes vote down vote up
def adopt_sessions(self):
        if not self.fdtx_path:
            return
        fdtx = FdTx(None)
        fdtx.connect(self.fdtx_path, 5)
        # receive open file descriptors together with their associated authkeys
        while True:
            try: # future safety: double the needed message length, two fd's
                authkey, fd = fdtx.get(AUTHKEY_LENGTH*2, 2)
            except ConnectionClosed:
                break # other end sent all it had
            if authkey not in self.adoption:
                continue # session died during handover
            self.adoption[authkey]['fd'] = fd[0] # just one fd per message
        for authkey in self.adoption:
            if 'fd' not in self.adoption[authkey]:
                continue # session died during handover
            # reconnect the session
            fd      = self.adoption[authkey]['fd']
            pid     = self.adoption[authkey]['pid']
            address = tuple(self.adoption[authkey]['address'])
            # represent the adopted session by an AdoptedSession instance that
            # only implements .pid and .terminate()
            local   = AdoptedSession(pid)
            sock    = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
            remote  = RemoteSession(address, authkey, timeout=1, sock=sock)
            self.add_connection(remote._connection, authkey)
            self.sessions[authkey] = (local, remote)

            # recreate the allocation records
            alloc   = self.adoption[authkey]['allocations']
            for a in alloc:
                resource   = a['profile']
                collateral = a['collateral']
                self.allocators['local'].allocate(resource, remote, collateral) 
Example 20
Project: abusehelper   Author: Exploit-install   File: roomgraph.py    (license) View Source Project 5 votes vote down vote up
def _start_worker(self):
        env = dict(os.environ)
        env["ABUSEHELPER_SUBPROCESS"] = ""

        # Find out the full package & module name. Don't refer to the
        # variable __loader__ directly to keep flake8 (version 2.5.0)
        # linter happy.
        fullname = globals()["__loader__"].fullname

        own_conn, other_conn = native_socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
        try:
            process = subprocess.Popen(
                [sys.executable, "-m", fullname],
                preexec_fn=os.setpgrp,
                stdin=other_conn.fileno(),
                close_fds=True,
                env=env
            )

            try:
                conn = socket.fromfd(own_conn.fileno(), socket.AF_UNIX, socket.SOCK_STREAM)
            except:
                process.terminate()
                process.wait()
                raise
        finally:
            own_conn.close()
            other_conn.close()
        return process, conn 
Example 21
Project: zanph   Author: zanph   File: serving.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, host, port, app, handler=None,
                 passthrough_errors=False, ssl_context=None, fd=None):
        if handler is None:
            handler = WSGIRequestHandler

        self.address_family = select_ip_version(host, port)

        if fd is not None:
            real_sock = socket.fromfd(fd, self.address_family,
                                      socket.SOCK_STREAM)
            port = 0
        HTTPServer.__init__(self, (host, int(port)), handler)
        self.app = app
        self.passthrough_errors = passthrough_errors
        self.shutdown_signal = False
        self.host = host
        self.port = port

        # Patch in the original socket.
        if fd is not None:
            self.socket.close()
            self.socket = real_sock
            self.server_address = self.socket.getsockname()

        if ssl_context is not None:
            if isinstance(ssl_context, tuple):
                ssl_context = load_ssl_context(*ssl_context)
            if ssl_context == 'adhoc':
                ssl_context = generate_adhoc_ssl_context()
            # If we are on Python 2 the return value from socket.fromfd
            # is an internal socket object but what we need for ssl wrap
            # is the wrapper around it :(
            sock = self.socket
            if PY2 and not isinstance(sock, socket.socket):
                sock = socket.socket(sock.family, sock.type, sock.proto, sock)
            self.socket = ssl_context.wrap_socket(sock, server_side=True)
            self.ssl_context = ssl_context
        else:
            self.ssl_context = None 
Example 22
Project: hostapd-mana   Author: adde88   File: reduction.py    (license) View Source Project 5 votes vote down vote up
def fromfd(fd, family, type_, proto=0):
    s = socket.fromfd(fd, family, type_, proto)
    if s.__class__ is not socket.socket:
        s = socket.socket(_sock=s)
    return s 
Example 23
Project: hostapd-mana   Author: adde88   File: reduction.py    (license) View Source Project 5 votes vote down vote up
def rebuild_socket(reduced_handle, family, type_, proto):
    fd = rebuild_handle(reduced_handle)
    _sock = fromfd(fd, family, type_, proto)
    close(fd)
    return _sock 
Example 24
Project: etcd3-gateway   Author: dims   File: watch.py    (license) View Source Project 5 votes vote down vote up
def stop(self):
        try:
            if six.PY2:
                self._response.raw._fp.close()
            else:
                s = socket.fromfd(self._response.raw._fp.fileno(),
                                  socket.AF_INET,
                                  socket.SOCK_STREAM)
                s.shutdown(socket.SHUT_RDWR)
                s.close()
        except Exception:
            pass
        self._response.connection.close()
        self._executor.shutdown(wait=False) 
Example 25
Project: Sci-Finder   Author: snverse   File: serving.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, host, port, app, handler=None,
                 passthrough_errors=False, ssl_context=None, fd=None):
        if handler is None:
            handler = WSGIRequestHandler

        self.address_family = select_ip_version(host, port)

        if fd is not None:
            real_sock = socket.fromfd(fd, self.address_family,
                                      socket.SOCK_STREAM)
            port = 0
        HTTPServer.__init__(self, (host, int(port)), handler)
        self.app = app
        self.passthrough_errors = passthrough_errors
        self.shutdown_signal = False
        self.host = host
        self.port = self.socket.getsockname()[1]

        # Patch in the original socket.
        if fd is not None:
            self.socket.close()
            self.socket = real_sock
            self.server_address = self.socket.getsockname()

        if ssl_context is not None:
            if isinstance(ssl_context, tuple):
                ssl_context = load_ssl_context(*ssl_context)
            if ssl_context == 'adhoc':
                ssl_context = generate_adhoc_ssl_context()
            # If we are on Python 2 the return value from socket.fromfd
            # is an internal socket object but what we need for ssl wrap
            # is the wrapper around it :(
            sock = self.socket
            if PY2 and not isinstance(sock, socket.socket):
                sock = socket.socket(sock.family, sock.type, sock.proto, sock)
            self.socket = ssl_context.wrap_socket(sock, server_side=True)
            self.ssl_context = ssl_context
        else:
            self.ssl_context = None 
Example 26
Project: Sci-Finder   Author: snverse   File: serving.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, host, port, app, handler=None,
                 passthrough_errors=False, ssl_context=None, fd=None):
        if handler is None:
            handler = WSGIRequestHandler

        self.address_family = select_ip_version(host, port)

        if fd is not None:
            real_sock = socket.fromfd(fd, self.address_family,
                                      socket.SOCK_STREAM)
            port = 0
        HTTPServer.__init__(self, (host, int(port)), handler)
        self.app = app
        self.passthrough_errors = passthrough_errors
        self.shutdown_signal = False
        self.host = host
        self.port = self.socket.getsockname()[1]

        # Patch in the original socket.
        if fd is not None:
            self.socket.close()
            self.socket = real_sock
            self.server_address = self.socket.getsockname()

        if ssl_context is not None:
            if isinstance(ssl_context, tuple):
                ssl_context = load_ssl_context(*ssl_context)
            if ssl_context == 'adhoc':
                ssl_context = generate_adhoc_ssl_context()
            # If we are on Python 2 the return value from socket.fromfd
            # is an internal socket object but what we need for ssl wrap
            # is the wrapper around it :(
            sock = self.socket
            if PY2 and not isinstance(sock, socket.socket):
                sock = socket.socket(sock.family, sock.type, sock.proto, sock)
            self.socket = ssl_context.wrap_socket(sock, server_side=True)
            self.ssl_context = ssl_context
        else:
            self.ssl_context = None 
Example 27
Project: harbour-sailfinder   Author: DylanVanAssche   File: serving.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, host, port, app, handler=None,
                 passthrough_errors=False, ssl_context=None, fd=None):
        if handler is None:
            handler = WSGIRequestHandler

        self.address_family = select_ip_version(host, port)

        if fd is not None:
            real_sock = socket.fromfd(fd, self.address_family,
                                      socket.SOCK_STREAM)
            port = 0
        HTTPServer.__init__(self, (host, int(port)), handler)
        self.app = app
        self.passthrough_errors = passthrough_errors
        self.shutdown_signal = False
        self.host = host
        self.port = port

        # Patch in the original socket.
        if fd is not None:
            self.socket.close()
            self.socket = real_sock
            self.server_address = self.socket.getsockname()

        if ssl_context is not None:
            if isinstance(ssl_context, tuple):
                ssl_context = load_ssl_context(*ssl_context)
            if ssl_context == 'adhoc':
                ssl_context = generate_adhoc_ssl_context()
            # If we are on Python 2 the return value from socket.fromfd
            # is an internal socket object but what we need for ssl wrap
            # is the wrapper around it :(
            sock = self.socket
            if PY2 and not isinstance(sock, socket.socket):
                sock = socket.socket(sock.family, sock.type, sock.proto, sock)
            self.socket = ssl_context.wrap_socket(sock, server_side=True)
            self.ssl_context = ssl_context
        else:
            self.ssl_context = None 
Example 28
Project: harbour-sailfinder   Author: DylanVanAssche   File: serving.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, host, port, app, handler=None,
                 passthrough_errors=False, ssl_context=None, fd=None):
        if handler is None:
            handler = WSGIRequestHandler

        self.address_family = select_ip_version(host, port)

        if fd is not None:
            real_sock = socket.fromfd(fd, self.address_family,
                                      socket.SOCK_STREAM)
            port = 0
        HTTPServer.__init__(self, (host, int(port)), handler)
        self.app = app
        self.passthrough_errors = passthrough_errors
        self.shutdown_signal = False
        self.host = host
        self.port = port

        # Patch in the original socket.
        if fd is not None:
            self.socket.close()
            self.socket = real_sock
            self.server_address = self.socket.getsockname()

        if ssl_context is not None:
            if isinstance(ssl_context, tuple):
                ssl_context = load_ssl_context(*ssl_context)
            if ssl_context == 'adhoc':
                ssl_context = generate_adhoc_ssl_context()
            # If we are on Python 2 the return value from socket.fromfd
            # is an internal socket object but what we need for ssl wrap
            # is the wrapper around it :(
            sock = self.socket
            if PY2 and not isinstance(sock, socket.socket):
                sock = socket.socket(sock.family, sock.type, sock.proto, sock)
            self.socket = ssl_context.wrap_socket(sock, server_side=True)
            self.ssl_context = ssl_context
        else:
            self.ssl_context = None 
Example 29
Project: Texty   Author: sarthfrey   File: serving.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, host, port, app, handler=None,
                 passthrough_errors=False, ssl_context=None, fd=None):
        if handler is None:
            handler = WSGIRequestHandler

        self.address_family = select_ip_version(host, port)

        if fd is not None:
            real_sock = socket.fromfd(fd, self.address_family,
                                      socket.SOCK_STREAM)
            port = 0
        HTTPServer.__init__(self, (host, int(port)), handler)
        self.app = app
        self.passthrough_errors = passthrough_errors
        self.shutdown_signal = False
        self.host = host
        self.port = port

        # Patch in the original socket.
        if fd is not None:
            self.socket.close()
            self.socket = real_sock
            self.server_address = self.socket.getsockname()

        if ssl_context is not None:
            if isinstance(ssl_context, tuple):
                ssl_context = load_ssl_context(*ssl_context)
            if ssl_context == 'adhoc':
                ssl_context = generate_adhoc_ssl_context()
            self.socket = ssl_context.wrap_socket(self.socket,
                                                  server_side=True)
            self.ssl_context = ssl_context
        else:
            self.ssl_context = None 
Example 30
Project: packet-queue   Author: google   File: libnetfilter_queue.py    (license) View Source Project 5 votes vote down vote up
def __init__(self):
    self.handle = nfq.nfq_open()
    self.fileno = nfq.nfq_fd(self.handle)
    self.socket = socket.fromfd(self.fileno, socket.AF_UNIX, socket.SOCK_RAW)

    if nfq.nfq_unbind_pf(self.handle, socket.AF_INET) < 0:
      raise OSError('nfq_unbind_pf() failed. Are you root?')

    if nfq.nfq_bind_pf(self.handle, socket.AF_INET) < 0:
      raise OSError('nfq_bind_pf() failed. Are you root?') 
Example 31
Project: RPoint   Author: george17-meet   File: serving.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, host, port, app, handler=None,
                 passthrough_errors=False, ssl_context=None, fd=None):
        if handler is None:
            handler = WSGIRequestHandler

        self.address_family = select_ip_version(host, port)

        if fd is not None:
            real_sock = socket.fromfd(fd, self.address_family,
                                      socket.SOCK_STREAM)
            port = 0
        HTTPServer.__init__(self, (host, int(port)), handler)
        self.app = app
        self.passthrough_errors = passthrough_errors
        self.shutdown_signal = False
        self.host = host
        self.port = self.socket.getsockname()[1]

        # Patch in the original socket.
        if fd is not None:
            self.socket.close()
            self.socket = real_sock
            self.server_address = self.socket.getsockname()

        if ssl_context is not None:
            if isinstance(ssl_context, tuple):
                ssl_context = load_ssl_context(*ssl_context)
            if ssl_context == 'adhoc':
                ssl_context = generate_adhoc_ssl_context()
            # If we are on Python 2 the return value from socket.fromfd
            # is an internal socket object but what we need for ssl wrap
            # is the wrapper around it :(
            sock = self.socket
            if PY2 and not isinstance(sock, socket.socket):
                sock = socket.socket(sock.family, sock.type, sock.proto, sock)
            self.socket = ssl_context.wrap_socket(sock, server_side=True)
            self.ssl_context = ssl_context
        else:
            self.ssl_context = None 
Example 32
Project: isni-reconcile   Author: cmh2166   File: serving.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, host, port, app, handler=None,
                 passthrough_errors=False, ssl_context=None, fd=None):
        if handler is None:
            handler = WSGIRequestHandler

        self.address_family = select_ip_version(host, port)

        if fd is not None:
            real_sock = socket.fromfd(fd, self.address_family,
                                      socket.SOCK_STREAM)
            port = 0
        HTTPServer.__init__(self, (host, int(port)), handler)
        self.app = app
        self.passthrough_errors = passthrough_errors
        self.shutdown_signal = False
        self.host = host
        self.port = port

        # Patch in the original socket.
        if fd is not None:
            self.socket.close()
            self.socket = real_sock
            self.server_address = self.socket.getsockname()

        if ssl_context is not None:
            if isinstance(ssl_context, tuple):
                ssl_context = load_ssl_context(*ssl_context)
            if ssl_context == 'adhoc':
                ssl_context = generate_adhoc_ssl_context()
            # If we are on Python 2 the return value from socket.fromfd
            # is an internal socket object but what we need for ssl wrap
            # is the wrapper around it :(
            sock = self.socket
            if PY2 and not isinstance(sock, socket.socket):
                sock = socket.socket(sock.family, sock.type, sock.proto, sock)
            self.socket = ssl_context.wrap_socket(sock, server_side=True)
            self.ssl_context = ssl_context
        else:
            self.ssl_context = None 
Example 33
Project: flasky   Author: RoseOu   File: sock.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, address, conf, log, fd=None):
        self.log = log
        self.conf = conf

        self.cfg_addr = address
        if fd is None:
            sock = socket.socket(self.FAMILY, socket.SOCK_STREAM)
        else:
            sock = socket.fromfd(fd, self.FAMILY, socket.SOCK_STREAM)

        self.sock = self.set_options(sock, bound=(fd is not None)) 
Example 34
Project: bitmask-dev   Author: leapcode   File: daemon.py    (license) View Source Project 5 votes vote down vote up
def is_socket(fd):
    """ Determine whether the file descriptor is a socket.

        :param fd: The file descriptor to interrogate.
        :return: ``True`` iff the file descriptor is a socket; otherwise
            ``False``.

        Query the socket type of `fd`. If there is no error, the file is a
        socket.

        """
    result = False

    file_socket = socket.fromfd(fd, socket.AF_INET, socket.SOCK_RAW)

    try:
        socket_type = file_socket.getsockopt(
            socket.SOL_SOCKET, socket.SO_TYPE)
    except socket.error as exc:
        exc_errno = exc.args[0]
        if exc_errno == errno.ENOTSOCK:
            # Socket operation on non-socket.
            pass
        else:
            # Some other socket error.
            result = True
    else:
        # No error getting socket type.
        result = True

    return result 
Example 35
Project: trio   Author: python-trio   File: _socket.py    (license) View Source Project 5 votes vote down vote up
def fromfd(*args, **kwargs):
    """Like :func:`socket.fromfd`, but returns a trio socket object.

    """
    return from_stdlib_socket(_stdlib_socket.fromfd(*args, **kwargs)) 
Example 36
Project: trio   Author: python-trio   File: test_socket.py    (license) View Source Project 5 votes vote down vote up
def test_from_fd():
    sa, sb = stdlib_socket.socketpair()
    ta = tsocket.fromfd(sa.fileno(), sa.family, sa.type, sa.proto)
    with sa, sb, ta:
        assert ta.fileno() != sa.fileno()
        await ta.send(b"x")
        assert sb.recv(3) == b"x" 
Example 37
Project: RealtimePythonChat   Author: quangtqag   File: serving.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, host, port, app, handler=None,
                 passthrough_errors=False, ssl_context=None, fd=None):
        if handler is None:
            handler = WSGIRequestHandler

        self.address_family = select_ip_version(host, port)

        if fd is not None:
            real_sock = socket.fromfd(fd, self.address_family,
                                      socket.SOCK_STREAM)
            port = 0
        HTTPServer.__init__(self, (host, int(port)), handler)
        self.app = app
        self.passthrough_errors = passthrough_errors
        self.shutdown_signal = False
        self.host = host
        self.port = port

        # Patch in the original socket.
        if fd is not None:
            self.socket.close()
            self.socket = real_sock
            self.server_address = self.socket.getsockname()

        if ssl_context is not None:
            if isinstance(ssl_context, tuple):
                ssl_context = load_ssl_context(*ssl_context)
            if ssl_context == 'adhoc':
                ssl_context = generate_adhoc_ssl_context()
            # If we are on Python 2 the return value from socket.fromfd
            # is an internal socket object but what we need for ssl wrap
            # is the wrapper around it :(
            sock = self.socket
            if PY2 and not isinstance(sock, socket.socket):
                sock = socket.socket(sock.family, sock.type, sock.proto, sock)
            self.socket = ssl_context.wrap_socket(sock, server_side=True)
            self.ssl_context = ssl_context
        else:
            self.ssl_context = None 
Example 38
Project: pyh2o   Author: iceb0y   File: test_e2e.py    (license) View Source Project 5 votes vote down vote up
def test_peername(self):
        response = self.http_get(PEERNAME_PATH)
        sock = socket.fromfd(response.fileno(), socket.AF_INET, socket.SOCK_STREAM)
        sockname = sock.getsockname()
        self.assertEqual(response.read(),
                         (sockname[0] + ':' + str(sockname[1])).encode())
        sock.close() 
Example 39
Project: Indushell   Author: SecarmaLabs   File: serving.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, host, port, app, handler=None,
                 passthrough_errors=False, ssl_context=None, fd=None):
        if handler is None:
            handler = WSGIRequestHandler

        self.address_family = select_ip_version(host, port)

        if fd is not None:
            real_sock = socket.fromfd(fd, self.address_family,
                                      socket.SOCK_STREAM)
            port = 0
        HTTPServer.__init__(self, (host, int(port)), handler)
        self.app = app
        self.passthrough_errors = passthrough_errors
        self.shutdown_signal = False
        self.host = host
        self.port = self.socket.getsockname()[1]

        # Patch in the original socket.
        if fd is not None:
            self.socket.close()
            self.socket = real_sock
            self.server_address = self.socket.getsockname()

        if ssl_context is not None:
            if isinstance(ssl_context, tuple):
                ssl_context = load_ssl_context(*ssl_context)
            if ssl_context == 'adhoc':
                ssl_context = generate_adhoc_ssl_context()
            # If we are on Python 2 the return value from socket.fromfd
            # is an internal socket object but what we need for ssl wrap
            # is the wrapper around it :(
            sock = self.socket
            if PY2 and not isinstance(sock, socket.socket):
                sock = socket.socket(sock.family, sock.type, sock.proto, sock)
            self.socket = ssl_context.wrap_socket(sock, server_side=True)
            self.ssl_context = ssl_context
        else:
            self.ssl_context = None 
Example 40
Project: Liljimbo-Chatbot   Author: chrisjim316   File: serving.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, host, port, app, handler=None,
                 passthrough_errors=False, ssl_context=None, fd=None):
        if handler is None:
            handler = WSGIRequestHandler

        self.address_family = select_ip_version(host, port)

        if fd is not None:
            real_sock = socket.fromfd(fd, self.address_family,
                                      socket.SOCK_STREAM)
            port = 0
        HTTPServer.__init__(self, (host, int(port)), handler)
        self.app = app
        self.passthrough_errors = passthrough_errors
        self.shutdown_signal = False
        self.host = host
        self.port = self.socket.getsockname()[1]

        # Patch in the original socket.
        if fd is not None:
            self.socket.close()
            self.socket = real_sock
            self.server_address = self.socket.getsockname()

        if ssl_context is not None:
            if isinstance(ssl_context, tuple):
                ssl_context = load_ssl_context(*ssl_context)
            if ssl_context == 'adhoc':
                ssl_context = generate_adhoc_ssl_context()
            # If we are on Python 2 the return value from socket.fromfd
            # is an internal socket object but what we need for ssl wrap
            # is the wrapper around it :(
            sock = self.socket
            if PY2 and not isinstance(sock, socket.socket):
                sock = socket.socket(sock.family, sock.type, sock.proto, sock)
            self.socket = ssl_context.wrap_socket(sock, server_side=True)
            self.ssl_context = ssl_context
        else:
            self.ssl_context = None 
Example 41
Project: flask_system   Author: prashasy   File: serving.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, host, port, app, handler=None,
                 passthrough_errors=False, ssl_context=None, fd=None):
        if handler is None:
            handler = WSGIRequestHandler

        self.address_family = select_ip_version(host, port)

        if fd is not None:
            real_sock = socket.fromfd(fd, self.address_family,
                                      socket.SOCK_STREAM)
            port = 0
        HTTPServer.__init__(self, (host, int(port)), handler)
        self.app = app
        self.passthrough_errors = passthrough_errors
        self.shutdown_signal = False
        self.host = host
        self.port = self.socket.getsockname()[1]

        # Patch in the original socket.
        if fd is not None:
            self.socket.close()
            self.socket = real_sock
            self.server_address = self.socket.getsockname()

        if ssl_context is not None:
            if isinstance(ssl_context, tuple):
                ssl_context = load_ssl_context(*ssl_context)
            if ssl_context == 'adhoc':
                ssl_context = generate_adhoc_ssl_context()
            # If we are on Python 2 the return value from socket.fromfd
            # is an internal socket object but what we need for ssl wrap
            # is the wrapper around it :(
            sock = self.socket
            if PY2 and not isinstance(sock, socket.socket):
                sock = socket.socket(sock.family, sock.type, sock.proto, sock)
            self.socket = ssl_context.wrap_socket(sock, server_side=True)
            self.ssl_context = ssl_context
        else:
            self.ssl_context = None 
Example 42
Project: zippy   Author: securesystemslab   File: reduction.py    (license) View Source Project 5 votes vote down vote up
def fromfd(fd, family, type_, proto=0):
    s = socket.fromfd(fd, family, type_, proto)
    if s.__class__ is not socket.socket:
        s = socket.socket(_sock=s)
    return s 
Example 43
Project: zippy   Author: securesystemslab   File: reduction.py    (license) View Source Project 5 votes vote down vote up
def rebuild_socket(reduced_handle, family, type_, proto):
    fd = rebuild_handle(reduced_handle)
    _sock = fromfd(fd, family, type_, proto)
    close(fd)
    return _sock 
Example 44
Project: zippy   Author: securesystemslab   File: test_socket.py    (license) View Source Project 5 votes vote down vote up
def testFromFd(self):
        # Testing fromfd()
        fd = self.cli_conn.fileno()
        sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
        self.addCleanup(sock.close)
        self.assertIsInstance(sock, socket.socket)
        msg = sock.recv(1024)
        self.assertEqual(msg, MSG) 
Example 45
Project: chihu   Author: yelongyu   File: sock.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, address, conf, log, fd=None):
        self.log = log
        self.conf = conf

        self.cfg_addr = address
        if fd is None:
            sock = socket.socket(self.FAMILY, socket.SOCK_STREAM)
        else:
            sock = socket.fromfd(fd, self.FAMILY, socket.SOCK_STREAM)

        self.sock = self.set_options(sock, bound=(fd is not None)) 
Example 46
Project: chihu   Author: yelongyu   File: serving.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, host, port, app, handler=None,
                 passthrough_errors=False, ssl_context=None, fd=None):
        if handler is None:
            handler = WSGIRequestHandler

        self.address_family = select_ip_version(host, port)

        if fd is not None:
            real_sock = socket.fromfd(fd, self.address_family,
                                      socket.SOCK_STREAM)
            port = 0
        HTTPServer.__init__(self, (host, int(port)), handler)
        self.app = app
        self.passthrough_errors = passthrough_errors
        self.shutdown_signal = False
        self.host = host
        self.port = port

        # Patch in the original socket.
        if fd is not None:
            self.socket.close()
            self.socket = real_sock
            self.server_address = self.socket.getsockname()

        if ssl_context is not None:
            if isinstance(ssl_context, tuple):
                ssl_context = load_ssl_context(*ssl_context)
            if ssl_context == 'adhoc':
                ssl_context = generate_adhoc_ssl_context()
            # If we are on Python 2 the return value from socket.fromfd
            # is an internal socket object but what we need for ssl wrap
            # is the wrapper around it :(
            sock = self.socket
            if PY2 and not isinstance(sock, socket.socket):
                sock = socket.socket(sock.family, sock.type, sock.proto, sock)
            self.socket = ssl_context.wrap_socket(sock, server_side=True)
            self.ssl_context = ssl_context
        else:
            self.ssl_context = None 
Example 47
Project: ShelbySearch   Author: Agentscreech   File: sock.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, address, conf, log, fd=None):
        self.log = log
        self.conf = conf

        self.cfg_addr = address
        if fd is None:
            sock = socket.socket(self.FAMILY, socket.SOCK_STREAM)
            bound = False
        else:
            sock = socket.fromfd(fd, self.FAMILY, socket.SOCK_STREAM)
            os.close(fd)
            bound = True

        self.sock = self.set_options(sock, bound=bound) 
Example 48
Project: ShelbySearch   Author: Agentscreech   File: serving.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, host, port, app, handler=None,
                 passthrough_errors=False, ssl_context=None, fd=None):
        if handler is None:
            handler = WSGIRequestHandler

        self.address_family = select_ip_version(host, port)

        if fd is not None:
            real_sock = socket.fromfd(fd, self.address_family,
                                      socket.SOCK_STREAM)
            port = 0
        HTTPServer.__init__(self, (host, int(port)), handler)
        self.app = app
        self.passthrough_errors = passthrough_errors
        self.shutdown_signal = False
        self.host = host
        self.port = self.socket.getsockname()[1]

        # Patch in the original socket.
        if fd is not None:
            self.socket.close()
            self.socket = real_sock
            self.server_address = self.socket.getsockname()

        if ssl_context is not None:
            if isinstance(ssl_context, tuple):
                ssl_context = load_ssl_context(*ssl_context)
            if ssl_context == 'adhoc':
                ssl_context = generate_adhoc_ssl_context()
            # If we are on Python 2 the return value from socket.fromfd
            # is an internal socket object but what we need for ssl wrap
            # is the wrapper around it :(
            sock = self.socket
            if PY2 and not isinstance(sock, socket.socket):
                sock = socket.socket(sock.family, sock.type, sock.proto, sock)
            self.socket = ssl_context.wrap_socket(sock, server_side=True)
            self.ssl_context = ssl_context
        else:
            self.ssl_context = None 
Example 49
Project: pyetje   Author: rorlika   File: serving.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, host, port, app, handler=None,
                 passthrough_errors=False, ssl_context=None, fd=None):
        if handler is None:
            handler = WSGIRequestHandler

        self.address_family = select_ip_version(host, port)

        if fd is not None:
            real_sock = socket.fromfd(fd, self.address_family,
                                      socket.SOCK_STREAM)
            port = 0
        HTTPServer.__init__(self, (host, int(port)), handler)
        self.app = app
        self.passthrough_errors = passthrough_errors
        self.shutdown_signal = False
        self.host = host
        self.port = port

        # Patch in the original socket.
        if fd is not None:
            self.socket.close()
            self.socket = real_sock
            self.server_address = self.socket.getsockname()

        if ssl_context is not None:
            if isinstance(ssl_context, tuple):
                ssl_context = load_ssl_context(*ssl_context)
            if ssl_context == 'adhoc':
                ssl_context = generate_adhoc_ssl_context()
            # If we are on Python 2 the return value from socket.fromfd
            # is an internal socket object but what we need for ssl wrap
            # is the wrapper around it :(
            sock = self.socket
            if PY2 and not isinstance(sock, socket.socket):
                sock = socket.socket(sock.family, sock.type, sock.proto, sock)
            self.socket = ssl_context.wrap_socket(sock, server_side=True)
            self.ssl_context = ssl_context
        else:
            self.ssl_context = None 
Example 50
Project: respeaker_virtualenv   Author: respeaker   File: test_process.py    (license) View Source Project 5 votes vote down vote up
def test_connection_fromfd(self):
        with contextlib.closing(socket.socket()) as sock:
            sock.bind(('localhost', 0))
            sock.listen(1)
            p = psutil.Process()
            for conn in p.connections():
                if conn.fd == sock.fileno():
                    break
            else:
                self.fail("couldn't find socket fd")
            dupsock = socket.fromfd(conn.fd, conn.family, conn.type)
            with contextlib.closing(dupsock):
                self.assertEqual(dupsock.getsockname(), conn.laddr)
                self.assertNotEqual(sock.fileno(), dupsock.fileno())