Python errno.ENOPROTOOPT Examples

The following are 30 code examples of errno.ENOPROTOOPT(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module errno , or try the search function .
Example #1
Source File: test_socket.py    From CTFCrackTools with GNU General Public License v3.0 6 votes vote down vote up
def _testOption(self, level, option, values):
        for flag, func in [
            (self.test_udp,        self._testUDPOption),
            (self.test_tcp_client, self._testTCPClientOption),
            (self.test_tcp_server, self._testTCPServerOption),
        ]:
            if flag:
                func(level, option, values)
            else:
                try:
                    func(level, option, values)
                except socket.error, se:
                    self.failUnlessEqual(se[0], errno.ENOPROTOOPT, "Wrong errno from unsupported option exception: %d" % se[0])
                except Exception, x:
                    self.fail("Wrong exception raised from unsupported option: %s" % str(x))
                else:
                    self.fail("Setting unsupported option should have raised an exception") 
Example #2
Source File: test_socket.py    From medicare-demo with Apache License 2.0 6 votes vote down vote up
def _testOption(self, level, option, values):
        for flag, func in [
            (self.test_udp,        self._testUDPOption),
            (self.test_tcp_server, self._testTCPServerOption),
            (self.test_tcp_client, self._testTCPClientOption),
        ]:
            if flag:
                func(level, option, values)
            else:
                try:
                    func(level, option, values)
                except socket.error, se:
                    self.failUnlessEqual(se[0], errno.ENOPROTOOPT, "Wrong errno from unsupported option exception: %d" % se[0])
                except Exception, x:
                    self.fail("Wrong exception raised from unsupported option: %s" % str(x))
                else:
                    self.fail("Setting unsupported option should have raised an exception") 
Example #3
Source File: wsgi_server_test.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def test_ignore_other_errors(self):
    inet4_server = self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer)
    inet6_server = self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer)
    self.mox.StubOutWithMock(wsgi_server, '_SingleAddressWsgiServer')
    self.mox.StubOutWithMock(socket, 'getaddrinfo')
    socket.getaddrinfo('localhost', 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
                       socket.AI_PASSIVE).AndReturn(
                           [(None, None, None, None, ('127.0.0.1', 0, 'baz')),
                            (None, None, None, None, ('::1', 0, 'baz'))])
    wsgi_server._SingleAddressWsgiServer(('127.0.0.1', 0), None).AndReturn(
        inet4_server)
    inet4_server.start()
    inet4_server.port = 123
    wsgi_server._SingleAddressWsgiServer(('::1', 123), None).AndReturn(
        inet6_server)
    inet6_server.start().AndRaise(
        wsgi_server.BindError('message', (errno.ENOPROTOOPT, 'no protocol')))
    self.mox.ReplayAll()
    self.server.start()
    self.mox.VerifyAll()
    self.assertItemsEqual([inet4_server],
                          self.server._servers) 
Example #4
Source File: _socket.py    From CTFCrackTools-V2 with GNU General Public License v3.0 6 votes vote down vote up
def getsockopt(self, level, optname, buflen=None):
        # Pseudo options for interrogating the status of this socket
        if level == SOL_SOCKET:
            if optname == SO_ACCEPTCONN:
                if self.socket_type == SERVER_SOCKET:
                    return 1
                elif self.type == SOCK_STREAM:
                    return 0
                else:
                    raise error(errno.ENOPROTOOPT, "Protocol not available")
            if optname == SO_TYPE:
                return self.type
            if optname == SO_ERROR:
                last_error = self._last_error
                self._last_error = 0
                return last_error

        # Normal options
        try:
            option, _ = _socket_options[self.proto][(level, optname)]
        except KeyError:
            raise error(errno.ENOPROTOOPT, "Protocol not available")
        log.debug("Shadow option settings %s", self.options, extra={"sock": self})
        return self.options.get(option, 0) 
Example #5
Source File: wsgi_server_test.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
def test_ignore_other_errors(self):
    inet4_server = self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer)
    inet6_server = self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer)
    self.mox.StubOutWithMock(wsgi_server, '_SingleAddressWsgiServer')
    self.mox.StubOutWithMock(socket, 'getaddrinfo')
    socket.getaddrinfo('localhost', 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
                       socket.AI_PASSIVE).AndReturn(
                           [(None, None, None, None, ('127.0.0.1', 0, 'baz')),
                            (None, None, None, None, ('::1', 0, 'baz'))])
    wsgi_server._SingleAddressWsgiServer(('127.0.0.1', 0), None).AndReturn(
        inet4_server)
    inet4_server.start()
    inet4_server.port = 123
    wsgi_server._SingleAddressWsgiServer(('::1', 123), None).AndReturn(
        inet6_server)
    inet6_server.start().AndRaise(
        wsgi_server.BindError('message', (errno.ENOPROTOOPT, 'no protocol')))
    self.mox.ReplayAll()
    self.server.start()
    self.mox.VerifyAll()
    self.assertItemsEqual([inet4_server],
                          self.server._servers) 
Example #6
Source File: _socket.py    From CTFCrackTools-V2 with GNU General Public License v3.0 6 votes vote down vote up
def getsockopt(self, level, optname, buflen=None):
        # Pseudo options for interrogating the status of this socket
        if level == SOL_SOCKET:
            if optname == SO_ACCEPTCONN:
                if self.socket_type == SERVER_SOCKET:
                    return 1
                elif self.type == SOCK_STREAM:
                    return 0
                else:
                    raise error(errno.ENOPROTOOPT, "Protocol not available")
            if optname == SO_TYPE:
                return self.type
            if optname == SO_ERROR:
                last_error = self._last_error
                self._last_error = 0
                return last_error

        # Normal options
        try:
            option, _ = _socket_options[self.proto][(level, optname)]
        except KeyError:
            raise error(errno.ENOPROTOOPT, "Protocol not available")
        log.debug("Shadow option settings %s", self.options, extra={"sock": self})
        return self.options.get(option, 0) 
Example #7
Source File: test_socket.py    From CTFCrackTools-V2 with GNU General Public License v3.0 6 votes vote down vote up
def _testOption(self, level, option, values):
        for flag, func in [
            (self.test_udp,        self._testUDPOption),
            (self.test_tcp_client, self._testTCPClientOption),
            (self.test_tcp_server, self._testTCPServerOption),
        ]:
            if flag:
                func(level, option, values)
            else:
                try:
                    func(level, option, values)
                except socket.error, se:
                    self.failUnlessEqual(se[0], errno.ENOPROTOOPT, "Wrong errno from unsupported option exception: %d" % se[0])
                except Exception, x:
                    self.fail("Wrong exception raised from unsupported option: %s" % str(x))
                else:
                    self.fail("Setting unsupported option should have raised an exception") 
Example #8
Source File: socket.py    From thriftpy2 with MIT License 6 votes vote down vote up
def _init_sock(self):
        if self.unix_socket:
            # try remove the sock file it already exists
            _sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            try:
                _sock.connect(self.unix_socket)
            except (socket.error, OSError) as err:
                if err.args[0] == errno.ECONNREFUSED:
                    os.unlink(self.unix_socket)
        else:
            _sock = socket.socket(self.socket_family, socket.SOCK_STREAM)

        _sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        if hasattr(socket, "SO_REUSEPORT"):
            try:
                _sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
            except socket.error as err:
                if err[0] in (errno.ENOPROTOOPT, errno.EINVAL):
                    pass
                else:
                    raise
        _sock.settimeout(None)
        self.sock = _sock 
Example #9
Source File: socket.py    From thriftpy2 with MIT License 6 votes vote down vote up
def _init_sock(self):
        if self.unix_socket:
            # try remove the sock file it already exists
            _sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            try:
                _sock.connect(self.unix_socket)
            except (socket.error, OSError) as err:
                if err.args[0] == errno.ECONNREFUSED:
                    os.unlink(self.unix_socket)
        else:
            _sock = socket.socket(self.socket_family, socket.SOCK_STREAM)

        _sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        if hasattr(socket, "SO_REUSEPORT"):
            try:
                _sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
            except socket.error as err:
                if err[0] in (errno.ENOPROTOOPT, errno.EINVAL):
                    pass
                else:
                    raise
        _sock.settimeout(None)
        self.raw_sock = _sock 
Example #10
Source File: _socket.py    From CTFCrackTools with GNU General Public License v3.0 6 votes vote down vote up
def getsockopt(self, level, optname, buflen=None):
        # Pseudo options for interrogating the status of this socket
        if level == SOL_SOCKET:
            if optname == SO_ACCEPTCONN:
                if self.socket_type == SERVER_SOCKET:
                    return 1
                elif self.type == SOCK_STREAM:
                    return 0
                else:
                    raise error(errno.ENOPROTOOPT, "Protocol not available")
            if optname == SO_TYPE:
                return self.type
            if optname == SO_ERROR:
                last_error = self._last_error
                self._last_error = 0
                return last_error

        # Normal options
        try:
            option, _ = _socket_options[self.proto][(level, optname)]
        except KeyError:
            raise error(errno.ENOPROTOOPT, "Protocol not available")
        log.debug("Shadow option settings %s", self.options, extra={"sock": self})
        return self.options.get(option, 0) 
Example #11
Source File: _socket.py    From CTFCrackTools with GNU General Public License v3.0 6 votes vote down vote up
def getsockopt(self, level, optname, buflen=None):
        # Pseudo options for interrogating the status of this socket
        if level == SOL_SOCKET:
            if optname == SO_ACCEPTCONN:
                if self.socket_type == SERVER_SOCKET:
                    return 1
                elif self.type == SOCK_STREAM:
                    return 0
                else:
                    raise error(errno.ENOPROTOOPT, "Protocol not available")
            if optname == SO_TYPE:
                return self.type
            if optname == SO_ERROR:
                last_error = self._last_error
                self._last_error = 0
                return last_error

        # Normal options
        try:
            option, _ = _socket_options[self.proto][(level, optname)]
        except KeyError:
            raise error(errno.ENOPROTOOPT, "Protocol not available")
        log.debug("Shadow option settings %s", self.options, extra={"sock": self})
        return self.options.get(option, 0) 
Example #12
Source File: iostream.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def _handle_connect(self) -> None:
        try:
            err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        except socket.error as e:
            # Hurd doesn't allow SO_ERROR for loopback sockets because all
            # errors for such sockets are reported synchronously.
            if errno_from_exception(e) == errno.ENOPROTOOPT:
                err = 0
        if err != 0:
            self.error = socket.error(err, os.strerror(err))
            # IOLoop implementations may vary: some of them return
            # an error state before the socket becomes writable, so
            # in that case a connection failure would be handled by the
            # error path in _handle_events instead of here.
            if self._connect_future is None:
                gen_log.warning(
                    "Connect error on fd %s: %s",
                    self.socket.fileno(),
                    errno.errorcode[err],
                )
            self.close()
            return
        if self._connect_future is not None:
            future = self._connect_future
            self._connect_future = None
            future_set_result_unless_cancelled(future, self)
        self._connecting = False 
Example #13
Source File: netutil.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def bind_unix_socket(
        file: str, mode: int = 0o600, backlog: int = _DEFAULT_BACKLOG
    ) -> socket.socket:
        """Creates a listening unix socket.

        If a socket with the given name already exists, it will be deleted.
        If any other file with that name exists, an exception will be
        raised.

        Returns a socket object (not a list of socket objects like
        `bind_sockets`)
        """
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        set_close_exec(sock.fileno())
        try:
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        except socket.error as e:
            if errno_from_exception(e) != errno.ENOPROTOOPT:
                # Hurd doesn't support SO_REUSEADDR
                raise
        sock.setblocking(False)
        try:
            st = os.stat(file)
        except OSError as err:
            if errno_from_exception(err) != errno.ENOENT:
                raise
        else:
            if stat.S_ISSOCK(st.st_mode):
                os.remove(file)
            else:
                raise ValueError("File %s exists and is not a socket", file)
        sock.bind(file)
        os.chmod(file, mode)
        sock.listen(backlog)
        return sock 
Example #14
Source File: zeroconf.py    From RepetierIntegration with GNU Affero General Public License v3.0 5 votes vote down vote up
def new_socket():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # SO_REUSEADDR should be equivalent to SO_REUSEPORT for
    # multicast UDP sockets (p 731, "TCP/IP Illustrated,
    # Volume 2"), but some BSD-derived systems require
    # SO_REUSEPORT to be specified explicity.  Also, not all
    # versions of Python have SO_REUSEPORT available.
    # Catch OSError and socket.error for kernel versions <3.9 because lacking
    # SO_REUSEPORT support.
    try:
        reuseport = socket.SO_REUSEPORT
    except AttributeError:
        pass
    else:
        try:
            s.setsockopt(socket.SOL_SOCKET, reuseport, 1)
        except (OSError, socket.error) as err:
            # OSError on python 3, socket.error on python 2
            if not err.errno == errno.ENOPROTOOPT:
                raise

    # OpenBSD needs the ttl and loop values for the IP_MULTICAST_TTL and
    # IP_MULTICAST_LOOP socket options as an unsigned char.
    ttl = struct.pack(b'B', 255)
    s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
    loop = struct.pack(b'B', 1)
    s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, loop)

    s.bind(('', _MDNS_PORT))
    return s 
Example #15
Source File: plugin.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def _makeHTTPService(self):
        """Create the HTTP service."""
        from provisioningserver.rackdservices.http import HTTPResource
        from twisted.application.internet import StreamServerEndpointService
        from twisted.internet.endpoints import AdoptedStreamServerEndpoint
        from provisioningserver.utils.twisted import SiteNoLog

        port = 5249
        s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        try:
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
        except socket_error as e:
            if e.errno != ENOPROTOOPT:
                raise e
        s.bind(("::", port))
        # Use a backlog of 50, which seems to be fairly common.
        s.listen(50)
        # Adopt this socket into Twisted's reactor.
        site_endpoint = AdoptedStreamServerEndpoint(
            reactor, s.fileno(), s.family
        )
        site_endpoint.port = port  # Make it easy to get the port number.
        site_endpoint.socket = s  # Prevent garbage collection.

        http_service = StreamServerEndpointService(
            site_endpoint, SiteNoLog(HTTPResource())
        )
        http_service.setName("http_service")
        return http_service 
Example #16
Source File: zeroconf.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def new_socket():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # SO_REUSEADDR should be equivalent to SO_REUSEPORT for
    # multicast UDP sockets (p 731, "TCP/IP Illustrated,
    # Volume 2"), but some BSD-derived systems require
    # SO_REUSEPORT to be specified explicity.  Also, not all
    # versions of Python have SO_REUSEPORT available.
    # Catch OSError and socket.error for kernel versions <3.9 because lacking
    # SO_REUSEPORT support.
    try:
        reuseport = socket.SO_REUSEPORT
    except AttributeError:
        pass
    else:
        try:
            s.setsockopt(socket.SOL_SOCKET, reuseport, 1)
        except (OSError, socket.error) as err:
            # OSError on python 3, socket.error on python 2
            if not err.errno == errno.ENOPROTOOPT:
                raise

    # OpenBSD needs the ttl and loop values for the IP_MULTICAST_TTL and
    # IP_MULTICAST_LOOP socket options as an unsigned char.
    ttl = struct.pack(b'B', 255)
    s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
    loop = struct.pack(b'B', 1)
    s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, loop)

    s.bind(('', _MDNS_PORT))
    return s 
Example #17
Source File: _socket.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def setsockopt(self, level, optname, value):
        try:
            option, cast = _socket_options[self.proto][(level, optname)]
        except KeyError:
            raise error(errno.ENOPROTOOPT, "Protocol not available")

        cast_value = cast(value)
        self.options[option] = cast_value
        log.debug("Setting option %s to %s", optname, value, extra={"sock": self})
        if self.channel:
            _set_option(self.channel.config().setOption, option, cast_value) 
Example #18
Source File: _socket.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def setsockopt(self, level, optname, value):
        try:
            option, cast = _socket_options[self.proto][(level, optname)]
        except KeyError:
            raise error(errno.ENOPROTOOPT, "Protocol not available")

        cast_value = cast(value)
        self.options[option] = cast_value
        log.debug("Setting option %s to %s", optname, value, extra={"sock": self})
        if self.channel:
            _set_option(self.channel.config().setOption, option, cast_value) 
Example #19
Source File: _socket.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def setsockopt(self, level, optname, value):
        try:
            option, cast = _socket_options[self.proto][(level, optname)]
        except KeyError:
            raise error(errno.ENOPROTOOPT, "Protocol not available")

        cast_value = cast(value)
        self.options[option] = cast_value
        log.debug("Setting option %s to %s", optname, value, extra={"sock": self})
        if self.channel:
            _set_option(self.channel.config().setOption, option, cast_value) 
Example #20
Source File: _socket.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def setsockopt(self, level, optname, value):
        try:
            option, cast = _socket_options[self.proto][(level, optname)]
        except KeyError:
            raise error(errno.ENOPROTOOPT, "Protocol not available")

        cast_value = cast(value)
        self.options[option] = cast_value
        log.debug("Setting option %s to %s", optname, value, extra={"sock": self})
        if self.channel:
            _set_option(self.channel.config().setOption, option, cast_value) 
Example #21
Source File: socket.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def setsockopt(self, level, option, value):
        if (level, option) in self.options:
            if option == SO_LINGER:
                values = struct.unpack('ii', value)
                self.jsocket.setSoLinger(*values)
            else:
                getattr(self.jsocket, "set%s" % self.options[ (level, option) ])(value)
        else:
            raise error(errno.ENOPROTOOPT, "Socket option '%s' (level '%s') not supported on socket(%s)" % (_constant_to_name(option), _constant_to_name(level), str(self.jsocket))) 
Example #22
Source File: error.py    From libnl with GNU Lesser General Public License v2.1 5 votes vote down vote up
def nl_syserr2nlerr(error_):
    """https://github.com/thom311/libnl/blob/libnl3_2_25/lib/error.c#L84."""
    error_ = abs(error_)
    legend = {
        errno.EBADF: libnl.errno_.NLE_BAD_SOCK,
        errno.EADDRINUSE: libnl.errno_.NLE_EXIST,
        errno.EEXIST: libnl.errno_.NLE_EXIST,
        errno.EADDRNOTAVAIL: libnl.errno_.NLE_NOADDR,
        errno.ESRCH: libnl.errno_.NLE_OBJ_NOTFOUND,
        errno.ENOENT: libnl.errno_.NLE_OBJ_NOTFOUND,
        errno.EINTR: libnl.errno_.NLE_INTR,
        errno.EAGAIN: libnl.errno_.NLE_AGAIN,
        errno.ENOTSOCK: libnl.errno_.NLE_BAD_SOCK,
        errno.ENOPROTOOPT: libnl.errno_.NLE_INVAL,
        errno.EFAULT: libnl.errno_.NLE_INVAL,
        errno.EACCES: libnl.errno_.NLE_NOACCESS,
        errno.EINVAL: libnl.errno_.NLE_INVAL,
        errno.ENOBUFS: libnl.errno_.NLE_NOMEM,
        errno.ENOMEM: libnl.errno_.NLE_NOMEM,
        errno.EAFNOSUPPORT: libnl.errno_.NLE_AF_NOSUPPORT,
        errno.EPROTONOSUPPORT: libnl.errno_.NLE_PROTO_MISMATCH,
        errno.EOPNOTSUPP: libnl.errno_.NLE_OPNOTSUPP,
        errno.EPERM: libnl.errno_.NLE_PERM,
        errno.EBUSY: libnl.errno_.NLE_BUSY,
        errno.ERANGE: libnl.errno_.NLE_RANGE,
        errno.ENODEV: libnl.errno_.NLE_NODEV,
    }
    return int(legend.get(error_, libnl.errno_.NLE_FAILURE)) 
Example #23
Source File: netutil.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def bind_unix_socket(
        file: str, mode: int = 0o600, backlog: int = _DEFAULT_BACKLOG
    ) -> socket.socket:
        """Creates a listening unix socket.

        If a socket with the given name already exists, it will be deleted.
        If any other file with that name exists, an exception will be
        raised.

        Returns a socket object (not a list of socket objects like
        `bind_sockets`)
        """
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        set_close_exec(sock.fileno())
        try:
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        except socket.error as e:
            if errno_from_exception(e) != errno.ENOPROTOOPT:
                # Hurd doesn't support SO_REUSEADDR
                raise
        sock.setblocking(False)
        try:
            st = os.stat(file)
        except OSError as err:
            if errno_from_exception(err) != errno.ENOENT:
                raise
        else:
            if stat.S_ISSOCK(st.st_mode):
                os.remove(file)
            else:
                raise ValueError("File %s exists and is not a socket", file)
        sock.bind(file)
        os.chmod(file, mode)
        sock.listen(backlog)
        return sock 
Example #24
Source File: iostream.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def _handle_connect(self) -> None:
        try:
            err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        except socket.error as e:
            # Hurd doesn't allow SO_ERROR for loopback sockets because all
            # errors for such sockets are reported synchronously.
            if errno_from_exception(e) == errno.ENOPROTOOPT:
                err = 0
        if err != 0:
            self.error = socket.error(err, os.strerror(err))
            # IOLoop implementations may vary: some of them return
            # an error state before the socket becomes writable, so
            # in that case a connection failure would be handled by the
            # error path in _handle_events instead of here.
            if self._connect_future is None:
                gen_log.warning(
                    "Connect error on fd %s: %s",
                    self.socket.fileno(),
                    errno.errorcode[err],
                )
            self.close()
            return
        if self._connect_future is not None:
            future = self._connect_future
            self._connect_future = None
            future_set_result_unless_cancelled(future, self)
        self._connecting = False 
Example #25
Source File: udp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def createInternetSocket(self):
        skt = Port.createInternetSocket(self)
        if self.listenMultiple:
            skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            if hasattr(socket, "SO_REUSEPORT"):
                try:
                    skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
                except socket.error as le:
                    # RHEL6 defines SO_REUSEPORT but it doesn't work
                    if le.errno == ENOPROTOOPT:
                        pass
                    else:
                        raise
        return skt 
Example #26
Source File: netutil.py    From teleport with Apache License 2.0 5 votes vote down vote up
def bind_unix_socket(file, mode=0o600, backlog=_DEFAULT_BACKLOG):
        """Creates a listening unix socket.

        If a socket with the given name already exists, it will be deleted.
        If any other file with that name exists, an exception will be
        raised.

        Returns a socket object (not a list of socket objects like
        `bind_sockets`)
        """
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        set_close_exec(sock.fileno())
        try:
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        except socket.error as e:
            if errno_from_exception(e) != errno.ENOPROTOOPT:
                # Hurd doesn't support SO_REUSEADDR
                raise
        sock.setblocking(0)
        try:
            st = os.stat(file)
        except OSError as err:
            if errno_from_exception(err) != errno.ENOENT:
                raise
        else:
            if stat.S_ISSOCK(st.st_mode):
                os.remove(file)
            else:
                raise ValueError("File %s exists and is not a socket", file)
        sock.bind(file)
        os.chmod(file, mode)
        sock.listen(backlog)
        return sock 
Example #27
Source File: iostream.py    From teleport with Apache License 2.0 5 votes vote down vote up
def _handle_connect(self):
        try:
            err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        except socket.error as e:
            # Hurd doesn't allow SO_ERROR for loopback sockets because all
            # errors for such sockets are reported synchronously.
            if errno_from_exception(e) == errno.ENOPROTOOPT:
                err = 0
        if err != 0:
            self.error = socket.error(err, os.strerror(err))
            # IOLoop implementations may vary: some of them return
            # an error state before the socket becomes writable, so
            # in that case a connection failure would be handled by the
            # error path in _handle_events instead of here.
            if self._connect_future is None:
                gen_log.warning("Connect error on fd %s: %s",
                                self.socket.fileno(), errno.errorcode[err])
            self.close()
            return
        if self._connect_callback is not None:
            callback = self._connect_callback
            self._connect_callback = None
            self._run_callback(callback)
        if self._connect_future is not None:
            future = self._connect_future
            self._connect_future = None
            future.set_result(self)
        self._connecting = False 
Example #28
Source File: netutil.py    From teleport with Apache License 2.0 5 votes vote down vote up
def bind_unix_socket(
        file: str, mode: int = 0o600, backlog: int = _DEFAULT_BACKLOG
    ) -> socket.socket:
        """Creates a listening unix socket.

        If a socket with the given name already exists, it will be deleted.
        If any other file with that name exists, an exception will be
        raised.

        Returns a socket object (not a list of socket objects like
        `bind_sockets`)
        """
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        set_close_exec(sock.fileno())
        try:
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        except socket.error as e:
            if errno_from_exception(e) != errno.ENOPROTOOPT:
                # Hurd doesn't support SO_REUSEADDR
                raise
        sock.setblocking(False)
        try:
            st = os.stat(file)
        except OSError as err:
            if errno_from_exception(err) != errno.ENOENT:
                raise
        else:
            if stat.S_ISSOCK(st.st_mode):
                os.remove(file)
            else:
                raise ValueError("File %s exists and is not a socket", file)
        sock.bind(file)
        os.chmod(file, mode)
        sock.listen(backlog)
        return sock 
Example #29
Source File: iostream.py    From teleport with Apache License 2.0 5 votes vote down vote up
def _handle_connect(self) -> None:
        try:
            err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        except socket.error as e:
            # Hurd doesn't allow SO_ERROR for loopback sockets because all
            # errors for such sockets are reported synchronously.
            if errno_from_exception(e) == errno.ENOPROTOOPT:
                err = 0
        if err != 0:
            self.error = socket.error(err, os.strerror(err))
            # IOLoop implementations may vary: some of them return
            # an error state before the socket becomes writable, so
            # in that case a connection failure would be handled by the
            # error path in _handle_events instead of here.
            if self._connect_future is None:
                gen_log.warning(
                    "Connect error on fd %s: %s",
                    self.socket.fileno(),
                    errno.errorcode[err],
                )
            self.close()
            return
        if self._connect_future is not None:
            future = self._connect_future
            self._connect_future = None
            future_set_result_unless_cancelled(future, self)
        self._connecting = False 
Example #30
Source File: netutil.py    From teleport with Apache License 2.0 5 votes vote down vote up
def bind_unix_socket(
        file: str, mode: int = 0o600, backlog: int = _DEFAULT_BACKLOG
    ) -> socket.socket:
        """Creates a listening unix socket.

        If a socket with the given name already exists, it will be deleted.
        If any other file with that name exists, an exception will be
        raised.

        Returns a socket object (not a list of socket objects like
        `bind_sockets`)
        """
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        set_close_exec(sock.fileno())
        try:
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        except socket.error as e:
            if errno_from_exception(e) != errno.ENOPROTOOPT:
                # Hurd doesn't support SO_REUSEADDR
                raise
        sock.setblocking(False)
        try:
            st = os.stat(file)
        except OSError as err:
            if errno_from_exception(err) != errno.ENOENT:
                raise
        else:
            if stat.S_ISSOCK(st.st_mode):
                os.remove(file)
            else:
                raise ValueError("File %s exists and is not a socket", file)
        sock.bind(file)
        os.chmod(file, mode)
        sock.listen(backlog)
        return sock