Example #1
0
 def sendall(self, data, flags=0):
     # *NOTE: gross, copied code from ssl.py becase it's not factored well enough to be used as-is
     if self._sslobj:
         if flags != 0:
             raise ValueError(
                 "non-zero flags not allowed in calls to sendall() on %s" %
                 self.__class__)
         amount = len(data)
         count = 0
         data_to_send = data
         while (count < amount):
             v = self.send(data_to_send)
             count += v
             if v == 0:
                 trampoline(self,
                            write=True,
                            timeout_exc=timeout_exc('timed out'))
             else:
                 data_to_send = data[count:]
         return amount
     else:
         while True:
             try:
                 return socket.sendall(self, data, flags)
             except orig_socket.error as e:
                 if self.act_non_blocking:
                     raise
                 if get_errno(e) == errno.EWOULDBLOCK:
                     trampoline(self,
                                write=True,
                                timeout=self.gettimeout(),
                                timeout_exc=timeout_exc('timed out'))
                 if get_errno(e) in SOCKET_CLOSED:
                     return ''
                 raise
Example #2
0
 def connect_ex(self, address):
     if self.act_non_blocking:
         return self.fd.connect_ex(address)
     fd = self.fd
     if self.gettimeout() is None:
         while not socket_connect(fd, address):
             try:
                 self._trampoline(fd, write=True)
                 socket_checkerr(fd)
             except socket.error as ex:
                 return get_errno(ex)
             except IOClosed:
                 return errno.EBADFD
     else:
         end = time.time() + self.gettimeout()
         while True:
             try:
                 if socket_connect(fd, address):
                     return 0
                 if time.time() >= end:
                     raise socket.timeout(errno.EAGAIN)
                 self._trampoline(fd, write=True, timeout=end - time.time(),
                            timeout_exc=socket.timeout(errno.EAGAIN))
                 socket_checkerr(fd)
             except socket.error as ex:
                 return get_errno(ex)
             except IOClosed:
                 return errno.EBADFD
Example #3
0
 def _socket_connect(self, addr):
     real_connect = socket.connect
     if self.act_non_blocking:
         return real_connect(self, addr)
     else:
         # *NOTE: gross, copied code from greenio because it's not factored
         # well enough to reuse
         if self.gettimeout() is None:
             while True:
                 try:
                     return real_connect(self, addr)
                 except orig_socket.error as exc:
                     if get_errno(exc) in CONNECT_ERR:
                         trampoline(self, write=True)
                     elif get_errno(exc) in CONNECT_SUCCESS:
                         return
                     else:
                         raise
         else:
             end = time.time() + self.gettimeout()
             while True:
                 try:
                     real_connect(self, addr)
                 except orig_socket.error as exc:
                     if get_errno(exc) in CONNECT_ERR:
                         trampoline(self,
                                    write=True,
                                    timeout=end - time.time(),
                                    timeout_exc=timeout_exc('timed out'))
                     elif get_errno(exc) in CONNECT_SUCCESS:
                         return
                     else:
                         raise
                 if time.time() >= end:
                     raise timeout_exc('timed out')
Example #4
0
    def wait(self, seconds=None):
        readers = self.listeners[self.READ]
        writers = self.listeners[self.WRITE]
        if not readers and not writers:
            if seconds:
                time.sleep(seconds)
            return
        reader_fds = list(readers)
        writer_fds = list(writers)
        all_fds = reader_fds + writer_fds
        try:
            r, w, er = select.select(reader_fds, writer_fds, all_fds, seconds)
        except select.error as e:
            if support.get_errno(e) == errno.EINTR:
                return
            elif support.get_errno(e) in BAD_SOCK:
                self._remove_bad_fds()
                return
            else:
                raise

        for fileno in er:
            readers.get(fileno, hub.noop).cb(fileno)
            writers.get(fileno, hub.noop).cb(fileno)

        for listeners, events in ((readers, r), (writers, w)):
            for fileno in events:
                try:
                    listeners.get(fileno, hub.noop).cb(fileno)
                except self.SYSTEM_EXCEPTIONS:
                    raise
                except:
                    self.squelch_exception(fileno, sys.exc_info())
                    support.clear_sys_exc_info()
Example #5
0
 def recv(self, buflen=1024, flags=0):
     # *NOTE: gross, copied code from ssl.py becase it's not factored well enough to be used as-is
     if self._sslobj:
         if flags != 0:
             raise ValueError(
                 "non-zero flags not allowed in calls to recv() on %s" %
                 self.__class__)
         read = self.read(buflen)
         return read
     else:
         while True:
             try:
                 return socket.recv(self, buflen, flags)
             except orig_socket.error as e:
                 if self.act_non_blocking:
                     raise
                 if get_errno(e) == errno.EWOULDBLOCK:
                     try:
                         trampoline(
                             self, read=True,
                             timeout=self.gettimeout(), timeout_exc=timeout_exc('timed out'))
                     except IOClosed:
                         return b''
                 if get_errno(e) in SOCKET_CLOSED:
                     return b''
                 raise
Example #6
0
    def _recv_loop(self, recv_meth, empty_val, *args):
        if self.act_non_blocking:
            return recv_meth(*args)

        while True:
            try:
                # recv: bufsize=0?
                # recv_into: buffer is empty?
                # This is needed because behind the scenes we use sockets in
                # nonblocking mode and builtin recv* methods. Attempting to read
                # 0 bytes from a nonblocking socket using a builtin recv* method
                # does not raise a timeout exception. Since we're simulating
                # a blocking socket here we need to produce a timeout exception
                # if needed, hence the call to trampoline.
                if not args[0]:
                    self._read_trampoline()
                return recv_meth(*args)
            except socket.error as e:
                if get_errno(e) in SOCKET_BLOCKING:
                    pass
                elif get_errno(e) in SOCKET_CLOSED:
                    return empty_val
                else:
                    raise

            try:
                self._read_trampoline()
            except IOClosed as e:
                # Perhaps we should return '' instead?
                raise EOFError()
Example #7
0
 def sendall (self, data, flags=0):
     # *NOTE: gross, copied code from ssl.py becase it's not factored well enough to be used as-is
     if self._sslobj:
         if flags != 0:
             raise ValueError(
                 "non-zero flags not allowed in calls to sendall() on %s" %
                 self.__class__)
         amount = len(data)
         count = 0
         while (count < amount):
             v = self.send(data[count:])
             count += v
         return amount
     else:
         while True:
             try:
                 return socket.sendall(self, buflen, flags)
             except orig_socket.error, e:
                 if self.act_non_blocking:
                     raise
                 if get_errno(e) == errno.EWOULDBLOCK:
                     trampoline(self, write=True, 
                                timeout=self.gettimeout(), timeout_exc=timeout_exc('timed out'))
                 if get_errno(e) in SOCKET_CLOSED:
                     return ''
                 raise
Example #8
0
 def _socket_connect(self, addr):
     real_connect = socket.connect
     if self.act_non_blocking:
         return real_connect(self, addr)
     else:
         # *NOTE: gross, copied code from greenio because it's not factored
         # well enough to reuse
         if self.gettimeout() is None:
             while True:
                 try:
                     return real_connect(self, addr)
                 except orig_socket.error as exc:
                     if get_errno(exc) in CONNECT_ERR:
                         trampoline(self, write=True)
                     elif get_errno(exc) in CONNECT_SUCCESS:
                         return
                     else:
                         raise
         else:
             end = time.time() + self.gettimeout()
             while True:
                 try:
                     real_connect(self, addr)
                 except orig_socket.error as exc:
                     if get_errno(exc) in CONNECT_ERR:
                         trampoline(
                             self, write=True,
                             timeout=end - time.time(), timeout_exc=timeout_exc('timed out'))
                     elif get_errno(exc) in CONNECT_SUCCESS:
                         return
                     else:
                         raise
                 if time.time() >= end:
                     raise timeout_exc('timed out')
Example #9
0
 def connect_ex(self, address):
     if self.act_non_blocking:
         return self.fd.connect_ex(address)
     fd = self.fd
     if self.gettimeout() is None:
         while not socket_connect(fd, address):
             try:
                 self._trampoline(fd, write=True)
                 socket_checkerr(fd)
             except socket.error as ex:
                 return get_errno(ex)
             except IOClosed:
                 return errno.EBADFD
     else:
         end = time.time() + self.gettimeout()
         timeout_exc = socket.timeout(errno.EAGAIN)
         while True:
             try:
                 if socket_connect(fd, address):
                     return 0
                 if time.time() >= end:
                     raise timeout_exc
                 self._trampoline(fd,
                                  write=True,
                                  timeout=end - time.time(),
                                  timeout_exc=timeout_exc)
                 socket_checkerr(fd)
             except socket.error as ex:
                 return get_errno(ex)
             except IOClosed:
                 return errno.EBADFD
Example #10
0
 def recv(self, buflen=1024, flags=0):
     # *NOTE: gross, copied code from ssl.py becase it's not factored well enough to be used as-is
     if self._sslobj:
         if flags != 0:
             raise ValueError(
                 "non-zero flags not allowed in calls to recv() on %s" %
                 self.__class__)
         read = self.read(buflen)
         return read
     else:
         while True:
             try:
                 return socket.recv(self, buflen, flags)
             except orig_socket.error as e:
                 if self.act_non_blocking:
                     raise
                 if get_errno(e) == errno.EWOULDBLOCK:
                     try:
                         trampoline(self,
                                    read=True,
                                    timeout=self.gettimeout(),
                                    timeout_exc=timeout_exc('timed out'))
                     except IOClosed:
                         return b''
                 if get_errno(e) in SOCKET_CLOSED:
                     return b''
                 raise
Example #11
0
    def _recv_loop(self, recv_meth, *args):
        fd = self.fd
        if self.act_non_blocking:
            return recv_meth(*args)

        while True:
            try:
                # recv: bufsize=0?
                # recv_into: buffer is empty?
                # This is needed because behind the scenes we use sockets in
                # nonblocking mode and builtin recv* methods. Attempting to read
                # 0 bytes from a nonblocking socket using a builtin recv* method
                # does not raise a timeout exception. Since we're simulating
                # a blocking socket here we need to produce a timeout exception
                # if needed, hence the call to trampoline.
                if not args[0]:
                    self._read_trampoline()
                return recv_meth(*args)
            except socket.error as e:
                if get_errno(e) in SOCKET_BLOCKING:
                    pass
                elif get_errno(e) in SOCKET_CLOSED:
                    return b''
                else:
                    raise

            try:
                self._read_trampoline()
            except IOClosed as e:
                # Perhaps we should return '' instead?
                raise EOFError()
    def wait(self, seconds=None):
        readers = self.listeners[READ]
        writers = self.listeners[WRITE]
        if not readers and not writers:
            if seconds:
                time.sleep(seconds)
            return
        all_fds = list(readers) + list(writers)
        try:
            r, w, er = select.select(readers.keys(), writers.keys(), all_fds,
                                     seconds)
        except select.error as e:
            if get_errno(e) == errno.EINTR:
                return
            elif get_errno(e) in BAD_SOCK:
                self._remove_bad_fds()
                return
            else:
                raise

        for fileno in er:
            readers.get(fileno, noop).cb(fileno)
            writers.get(fileno, noop).cb(fileno)

        for listeners, events in ((readers, r), (writers, w)):
            for fileno in events:
                try:
                    listeners.get(fileno, noop).cb(fileno)
                except self.SYSTEM_EXCEPTIONS:
                    raise
                except:
                    self.squelch_exception(fileno, sys.exc_info())
                    clear_sys_exc_info()
Example #13
0
 def _call_trampolining(self, func, *a, **kw):
     if self.act_non_blocking:
         return func(*a, **kw)
     else:
         while True:
             try:
                 return func(*a, **kw)
             except SSLError as exc:
                 if get_errno(exc) == SSL_ERROR_WANT_READ:
                     trampoline(self, read=True, timeout=self.gettimeout(), timeout_exc=timeout_exc("timed out"))
                 elif get_errno(exc) == SSL_ERROR_WANT_WRITE:
                     trampoline(self, write=True, timeout=self.gettimeout(), timeout_exc=timeout_exc("timed out"))
                 else:
                     raise
Example #14
0
def write(fd, st):
    """write(fd, string) -> byteswritten
    
    Write a string to a file descriptor.
    """
    while True:
        try:
            return __original_write__(fd, st)
        except (OSError, IOError), e:
            if get_errno(e) != errno.EAGAIN:
                raise
        except socket.error, e:
            if get_errno(e) != errno.EPIPE:
                raise
Example #15
0
def read(fd, n):
    """read(fd, buffersize) -> string
    
    Read a file descriptor."""
    while True:
        try:
            return __original_read__(fd, n)
        except (OSError, IOError), e:
            if get_errno(e) != errno.EAGAIN:
                raise
        except socket.error, e:
            if get_errno(e) == errno.EPIPE:
                return ""
            raise
Example #16
0
def write(fd, st):
    """write(fd, string) -> byteswritten
    
    Write a string to a file descriptor.
    """
    while True:
        try:
            return __original_write__(fd, st)
        except (OSError, IOError), e:
            if get_errno(e) != errno.EAGAIN:
                raise
        except socket.error, e:
            if get_errno(e) != errno.EPIPE:
                raise
Example #17
0
def read(fd, n):
    """read(fd, buffersize) -> string
    
    Read a file descriptor."""
    while True:
        try:
            return __original_read__(fd, n)
        except (OSError, IOError), e:
            if get_errno(e) != errno.EAGAIN:
                raise
        except socket.error, e:
            if get_errno(e) == errno.EPIPE:
                return ''
            raise
 def recv(self, buflen, flags=0):
     fd = self.fd
     if self.act_non_blocking:
         return fd.recv(buflen, flags)
     while True:
         try:
             return fd.recv(buflen, flags)
         except socket.error, e:
             if get_errno(e) in SOCKET_BLOCKING:
                 pass
             elif get_errno(e) in SOCKET_CLOSED:
                 return ""
             else:
                 raise
         trampoline(fd, read=True, timeout=self.gettimeout(), timeout_exc=socket.timeout("timed out"))
Example #19
0
def backdoor_server(sock, locals=None):
    """ Blocking function that runs a backdoor server on the socket *sock*,
    accepting connections and running backdoor consoles for each client that
    connects.

    The *locals* argument is a dictionary that will be included in the locals()
    of the interpreters.  It can be convenient to stick important application
    variables in here.
    """
    listeningOn = sock.getsockname()
    if sock.family == socket.AF_INET:
        #Expand result to IP + port
        listeningOn = '%s:%s' % listeningOn
    elif sock.family == socket.AF_INET6:
        ip, port, _, _ = listeningOn
        listeningOn = '%s:%s' % (ip, port,)
    #No action needed if sock.family == socket.AF_UNIX
    
    print "backdoor server listening on %s" % listeningOn
    try:
        try:
            while True:
                socketpair = sock.accept()
                backdoor(socketpair, locals)
        except socket.error, e:
            # Broken pipe means it was shutdown
            if get_errno(e) != errno.EPIPE:
                raise
    finally:
        sock.close()
Example #20
0
    def accept(self):
        """Accepts a new connection from a remote client, and returns
        a tuple containing that new connection wrapped with a server-side
        SSL channel, and the address of the remote client."""
        # RDW grr duplication of code from greenio
        if self.act_non_blocking:
            newsock, addr = socket.accept(self)
        else:
            while True:
                try:
                    newsock, addr = socket.accept(self)
                    set_nonblocking(newsock)
                    break
                except orig_socket.error as e:
                    if get_errno(e) != errno.EWOULDBLOCK:
                        raise
                    trampoline(self,
                               read=True,
                               timeout=self.gettimeout(),
                               timeout_exc=timeout_exc('timed out'))

        new_ssl = type(self)(
            newsock,
            keyfile=self.keyfile,
            certfile=self.certfile,
            server_side=True,
            cert_reqs=self.cert_reqs,
            ssl_version=self.ssl_version,
            ca_certs=self.ca_certs,
            do_handshake_on_connect=self.do_handshake_on_connect,
            suppress_ragged_eofs=self.suppress_ragged_eofs)
        return (new_ssl, addr)
Example #21
0
 def __call__(self, environ, start_response):
     if not (environ['HTTP_CONNECTION'] == 'Upgrade' and
         environ['HTTP_UPGRADE'] == 'WebSocket'):
         # need to check a few more things here for true compliance
         start_response('400 Bad Request', [('Connection','close')])
         return []
                 
     sock = environ['eventlet.input'].get_socket()
     ws = WebSocket(sock, 
         environ.get('HTTP_ORIGIN'),
         environ.get('HTTP_WEBSOCKET_PROTOCOL'),
         environ.get('PATH_INFO'))
     self.verify_client(ws)
     handshake_reply = ("HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
                "Upgrade: WebSocket\r\n"
                "Connection: Upgrade\r\n"
                "WebSocket-Origin: %s\r\n"
                "WebSocket-Location: ws://%s%s\r\n\r\n" % (
                     self.origin, 
                     environ.get('HTTP_HOST'), 
                     ws.path))                                       
     sock.sendall(handshake_reply)
     try:
         self.handler(ws)
     except socket.error, e:
         if get_errno(e) != errno.EPIPE:
             raise
Example #22
0
    def waiting_thread(self):
        poll = self.poll.poll
        fd_events = self.listeners_events
        add_event = self.listeners_events.append

        has = self.event_has.set
        want = self.event_want.wait
        want_clear = self.event_want.clear

        while not self.stopping:
            try:
                for f, ev in poll(DEFAULT_SLEEP):
                    if ev & EXC_MASK or ev & READ_MASK:
                        if (f, READ) not in fd_events:
                            add_event((f, READ))
                    if ev & EXC_MASK or ev & WRITE_MASK:
                        if (f, WRITE) not in fd_events:
                            add_event((f, WRITE))
                    if ev & POLLNVAL:
                        self.remove_descriptor(f)
                has()
                want(1)
                want_clear()
            except (IOError, select.error) as e:
                if get_errno(e) == errno.EINTR:
                    ev_sleep(1)
                    continue
                raise
            except SYSTEM_EXCEPTIONS:
                raise
Example #23
0
    def accept(self):
        """Accepts a new connection from a remote client, and returns
        a tuple containing that new connection wrapped with a server-side
        SSL channel, and the address of the remote client."""
        # RDW grr duplication of code from greenio
        if self.act_non_blocking:
            newsock, addr = socket.accept(self)
        else:
            while True:
                try:
                    newsock, addr = socket.accept(self)
                    break
                except orig_socket.error as e:
                    if get_errno(e) not in greenio.SOCKET_BLOCKING:
                        raise
                    trampoline(self,
                               read=True,
                               timeout=self.gettimeout(),
                               timeout_exc=timeout_exc('timed out'))

        new_ssl = type(self)(
            newsock,
            server_side=True,
            do_handshake_on_connect=False,
            suppress_ragged_eofs=self.suppress_ragged_eofs,
            _context=self._context,
        )
        return (new_ssl, addr)
Example #24
0
class TestGreenSocket(LimitedTestCase):
    def assertWriteToClosedFileRaises(self, fd):
        if sys.version_info[0]<3:
            # 2.x socket._fileobjects are odd: writes don't check
            # whether the socket is closed or not, and you get an
            # AttributeError during flush if it is closed
            fd.write('a')
            self.assertRaises(Exception, fd.flush)
        else:
            # 3.x io write to closed file-like pbject raises ValueError
            self.assertRaises(ValueError, fd.write, 'a')

    def test_connect_timeout(self):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(0.1)
        gs = greenio.GreenSocket(s)
        try:
            gs.connect(('192.0.2.1', 80))
            self.fail("socket.timeout not raised")
        except socket.timeout, e:
            self.assert_(hasattr(e, 'args'))
            self.assertEqual(e.args[0], 'timed out')
        except socket.error, e:
            # unreachable is also a valid outcome
            if not get_errno(e) in (errno.EHOSTUNREACH, errno.ENETUNREACH):
                raise
Example #25
0
 def finish(self):
     try:
         BaseHTTPServer.BaseHTTPRequestHandler.finish(self)
     except socket.error, e:
         # Broken pipe, connection reset by peer
         if get_errno(e) not in BROKEN_SOCK:
             raise
Example #26
0
    def _send_loop(self, send_method, data, *args):
        if self.act_non_blocking:
            return send_method(data, *args)

        # blocking socket behavior - sends all, blocks if the buffer is full
        total_sent = 0
        len_data = len(data)
        while 1:
            try:
                total_sent += send_method(data[total_sent:], *args)
            except socket.error as e:
                eno = get_errno(e)
                if eno == errno.ENOTCONN or eno not in SOCKET_BLOCKING:
                    raise

            if total_sent == len_data:
                break

            try:
                self._trampoline(self.fd,
                                 write=True,
                                 timeout=self.gettimeout(),
                                 timeout_exc=socket.timeout("timed out"))
            except IOClosed:
                raise socket.error(errno.ECONNRESET,
                                   'Connection closed by another thread')

        return total_sent
    def __call__(self, environ, start_response):
        http_connection_parts = [
            part.strip()
            for part in environ.get('HTTP_CONNECTION', '').lower().split(',')]
        if not ('upgrade' in http_connection_parts and
                environ.get('HTTP_UPGRADE', '').lower() == 'websocket'):
            # need to check a few more things here for true compliance
            start_response('400 Bad Request', [('Connection', 'close')])
            return []

        try:
            if 'HTTP_SEC_WEBSOCKET_VERSION' in environ:
                ws = self._handle_hybi_request(environ)
            elif self.support_legacy_versions:
                ws = self._handle_legacy_request(environ)
            else:
                raise BadRequest()
        except BadRequest as e:
            status = e.status
            body = e.body or b''
            headers = e.headers or []
            start_response(status,
                           [('Connection', 'close'), ] + headers)
            return [body]

        try:
            self.handler(ws)
        except socket.error as e:
            if get_errno(e) not in ACCEPTABLE_CLIENT_ERRORS:
                raise
        # Make sure we send the closing frame
        ws._send_closing_frame(True)
        # use this undocumented feature of eventlet.wsgi to ensure that it
        # doesn't barf on the fact that we didn't call start_response
        return wsgi.ALREADY_HANDLED
Example #28
0
 def finish(self):
     try:
         BaseHTTPServer.BaseHTTPRequestHandler.finish(self)
     except socket.error, e:
         # Broken pipe, connection reset by peer
         if get_errno(e) not in BROKEN_SOCK:
             raise
Example #29
0
    def add(self, *args):
        """ *args: evtype, fileno, cb, tb, mac """
        evtype, fileno = args[0:2]
        exists = (fileno in self.listeners_r or fileno in self.listeners_w)

        listener = self.lclass(*args)
        bucket = self.listeners[evtype]
        if exists and fileno in bucket:
            if self.g_prevent_multiple_readers:
                raise RuntimeError(
                    "Second simultaneous %s on fileno %s "
                    "detected.  Unless you really know what you're doing, "
                    "make sure that only one greenthread can %s any "
                    "particular socket.  Consider using a pools.Pool. "
                    "If you do know what you're doing and want to disable "
                    "this error, call "
                    "eventlet.debug.hub_prevent_multiple_readers(False) - MY THREAD=%s; "
                    "THAT THREAD=%s" %
                    (evtype, fileno, evtype, args[2], bucket[fileno]))
            # store off the second listener in another structure
            self.secondaries[evtype].setdefault(fileno, []).append(listener)
        else:
            bucket[fileno] = listener

        try:
            self.register(fileno, new=not exists)
        except IOError as ex:
            # ignore EEXIST, #80
            if get_errno(ex) != errno.EEXIST:
                raise
        return listener
Example #30
0
    def send(self, data, flags=0):
        fd = self.fd
        if self.act_non_blocking:
            return fd.send(data, flags)

        # blocking socket behavior - sends all, blocks if the buffer is full
        total_sent = 0
        len_data = len(data)
        while 1:
            try:
                total_sent += fd.send(data[total_sent:], flags)
            except socket.error as e:
                if get_errno(e) not in SOCKET_BLOCKING:
                    raise

            if total_sent == len_data:
                break

            try:
                self._trampoline(self.fd, write=True, timeout=self.gettimeout(),
                           timeout_exc=socket.timeout("timed out"))
            except IOClosed:
                raise socket.error(errno.ECONNRESET, 'Connection closed by another thread')

        return total_sent
Example #31
0
    def _send_loop(self, send_method, data, *args):
        if self.act_non_blocking:
            return send_method(data, *args)

        # blocking socket behavior - sends all, blocks if the buffer is full
        total_sent = 0
        len_data = len(data)
        while 1:
            try:
                total_sent += send_method(data[total_sent:], *args)
            except socket.error as e:
                eno = get_errno(e)
                if eno == errno.ENOTCONN or eno not in SOCKET_BLOCKING:
                    raise

            if total_sent == len_data:
                break

            try:
                self._trampoline(self.fd, write=True, timeout=self.gettimeout(),
                                 timeout_exc=socket.timeout("timed out"))
            except IOClosed:
                raise socket.error(errno.ECONNRESET, 'Connection closed by another thread')

        return total_sent
Example #32
0
 def sendall(self, data, flags=0):
     if self._sslobj:
         if flags != 0:
             raise ValueError(
                 "non-zero flags not allowed in calls to sendall() on %s" %
                 self.__class__)
         timeout = timeout_exc('timed out')
         send = super(GreenSSLSocket, self).send
         while data:
             offset = self._call_trampolining(send, data, flags)
             if offset > 0:
                 data = data[offset:]
             else:
                 trampoline(self, write=True, timeout_exc=timeout)
             # if data:
         return  # None for success
     else:
         while True:
             try:
                 return socket.sendall(self, data, flags)
             except orig_socket.error as e:
                 if self.act_non_blocking:
                     raise
                 erno = get_errno(e)
                 if erno in greenio.SOCKET_BLOCKING:
                     trampoline(self,
                                write=True,
                                timeout=self.gettimeout(),
                                timeout_exc=timeout_exc('timed out'))
                 elif erno in greenio.SOCKET_CLOSED:
                     return ''
                 raise
Example #33
0
    def wait(self, seconds=0):
        readers = list(self.listeners[self.READ])
        writers = list(self.listeners[self.WRITE])
        if not readers and not writers:
            ev_sleep(seconds)
            return

        try:
            rs, ws, es = select.select(readers, writers, readers + writers,
                                       seconds)
        except select.error as e:
            if support.get_errno(e) in BAD_SOCK:
                self._remove_bad_fds()
            return
        except self.SYSTEM_EXCEPTIONS:
            raise
        except:
            return

        for fileno in rs:
            self.add_listener_events((self.READ, fileno))
        for fileno in ws:
            self.add_listener_events((self.WRITE, fileno))
        for fileno in es:
            self.add_listener_events((self.READ, fileno))
            self.add_listener_events((self.WRITE, fileno))
Example #34
0
 def sendall(self, data, flags=0):
     # *NOTE: gross, copied code from ssl.py becase it's not factored well enough to be used as-is
     if self._sslobj:
         if flags != 0:
             raise ValueError(
                 "non-zero flags not allowed in calls to sendall() on %s" %
                 self.__class__)
         amount = len(data)
         count = 0
         data_to_send = data
         while (count < amount):
             v = self.send(data_to_send)
             count += v
             if v == 0:
                 trampoline(self, write=True, timeout_exc=timeout_exc('timed out'))
             else:
                 data_to_send = data[count:]
         return amount
     else:
         while True:
             try:
                 return socket.sendall(self, data, flags)
             except orig_socket.error as e:
                 if self.act_non_blocking:
                     raise
                 erno = get_errno(e)
                 if erno in greenio.SOCKET_BLOCKING:
                     trampoline(self, write=True,
                                timeout=self.gettimeout(), timeout_exc=timeout_exc('timed out'))
                 elif erno in greenio.SOCKET_CLOSED:
                     return ''
                 raise
Example #35
0
    def accept(self):
        """Accepts a new connection from a remote client, and returns
        a tuple containing that new connection wrapped with a server-side
        SSL channel, and the address of the remote client."""
        # RDW grr duplication of code from greenio
        if self.act_non_blocking:
            newsock, addr = socket.accept(self)
        else:
            while True:
                try:
                    newsock, addr = socket.accept(self)
                    set_nonblocking(newsock)
                    break
                except orig_socket.error as e:
                    if get_errno(e) not in greenio.SOCKET_BLOCKING:
                        raise
                    trampoline(self, read=True, timeout=self.gettimeout(),
                               timeout_exc=timeout_exc('timed out'))

        new_ssl = type(self)(
            newsock,
            keyfile=self.keyfile,
            certfile=self.certfile,
            server_side=True,
            cert_reqs=self.cert_reqs,
            ssl_version=self.ssl_version,
            ca_certs=self.ca_certs,
            do_handshake_on_connect=False,
            suppress_ragged_eofs=self.suppress_ragged_eofs)
        return (new_ssl, addr)
Example #36
0
def backdoor_server(sock, locals=None):
    """ Blocking function that runs a backdoor server on the socket *sock*,
    accepting connections and running backdoor consoles for each client that
    connects.

    The *locals* argument is a dictionary that will be included in the locals()
    of the interpreters.  It can be convenient to stick important application
    variables in here.
    """
    listening_on = sock.getsockname()
    if sock.family == socket.AF_INET:
        # Expand result to IP + port
        listening_on = '%s:%s' % listening_on
    elif sock.family == socket.AF_INET6:
        ip, port, _, _ = listening_on
        listening_on = '%s:%s' % (ip, port,)
    # No action needed if sock.family == socket.AF_UNIX

    print("backdoor server listening on %s" % (listening_on,))
    try:
        while True:
            socketpair = None
            try:
                socketpair = sock.accept()
                backdoor(socketpair, locals)
            except socket.error as e:
                # Broken pipe means it was shutdown
                if get_errno(e) != errno.EPIPE:
                    raise
            finally:
                if socketpair:
                    socketpair[0].close()
    finally:
        sock.close()
Example #37
0
    def send(self, data, flags=0):
        fd = self.fd
        if self.act_non_blocking:
            return fd.send(data, flags)

        # blocking socket behavior - sends all, blocks if the buffer is full
        total_sent = 0
        len_data = len(data)
        while 1:
            try:
                total_sent += fd.send(data[total_sent:], flags)
            except socket.error as e:
                if get_errno(e) not in SOCKET_BLOCKING:
                    raise

            if total_sent == len_data:
                break

            try:
                self._trampoline(self.fd,
                                 write=True,
                                 timeout=self.gettimeout(),
                                 timeout_exc=socket.timeout("timed out"))
            except IOClosed:
                raise socket.error(errno.ECONNRESET,
                                   'Connection closed by another thread')

        return total_sent
Example #38
0
 def write(self, data, *a, **kw):
     try:
         self.f.write(data, *a, **kw)
         self.f.flush()
     except socket.error as e:
         if get_errno(e) != errno.EPIPE:
             raise
Example #39
0
    def handle_one_request(self):
        if self.server.max_http_version:
            self.protocol_version = self.server.max_http_version

        self.raw_requestline = self._read_request_line()
        if not self.raw_requestline:
            self.close_connection = 1
            return
        if len(self.raw_requestline) >= self.server.url_length_limit:
            self.wfile.write(RESPONSE_414)
            self.close_connection = 1
            return

        orig_rfile = self.rfile
        try:
            self.rfile = FileObjectForHeaders(self.rfile)
            if not self.parse_request():
                return
        except HeaderLineTooLong:
            self.wfile.write(
                b"HTTP/1.0 400 Header Line Too Long\r\n"
                b"Connection: close\r\nContent-length: 0\r\n\r\n")
            self.close_connection = 1
            return
        except HeadersTooLarge:
            self.wfile.write(
                b"HTTP/1.0 400 Headers Too Large\r\n"
                b"Connection: close\r\nContent-length: 0\r\n\r\n")
            self.close_connection = 1
            return
        finally:
            self.rfile = orig_rfile

        content_length = self.headers.get('content-length')
        if content_length is not None:
            try:
                if int(content_length) < 0:
                    raise ValueError
            except ValueError:
                # Negative, or not an int at all
                self.wfile.write(
                    b"HTTP/1.0 400 Bad Request\r\n"
                    b"Connection: close\r\nContent-length: 0\r\n\r\n")
                self.close_connection = 1
                return

        headers_sent = []
        self.environ = self.get_environ(headers_sent)
        self.application = self.server.app
        try:
            self.server.outstanding_requests += 1
            try:
                self.handle_one_response(headers_sent)
            except socket.error as e:
                # Broken pipe, connection reset by peer
                if support.get_errno(e) not in BROKEN_SOCK:
                    raise
        finally:
            self.server.outstanding_requests -= 1
Example #40
0
 def read(self, buflen):
     while True:
         try:
             return _original_os.read(self._fileno, buflen)
         except OSError as e:
             if get_errno(e) not in SOCKET_BLOCKING:
                 raise IOError(*e.args)
         self._trampoline(self, read=True)
Example #41
0
 def sendall(self, data):
     len_data = len(data)
     os_write = os.write
     fileno = self._fileno
     try:
         total_sent = os_write(fileno, data)
     except OSError as e:
         if get_errno(e) != errno.EAGAIN:
             raise IOError(*e.args)
         total_sent = 0
     while total_sent < len_data:
         self._trampoline(self, write=True)
         try:
             total_sent += os_write(fileno, data[total_sent:])
         except OSError as e:
             if get_errno(e) != errno.EAGAIN:
                 raise IOError(*e.args)
Example #42
0
 def wait(self, seconds=None):
     readers = self.listeners[READ]
     writers = self.listeners[WRITE]
     if not readers and not writers:
         if seconds:
             time.sleep(seconds)
         return
     try:
         r, w, er = select.select(readers.keys(), writers.keys(), readers.keys() + writers.keys(), seconds)
     except select.error, e:
         if get_errno(e) == errno.EINTR:
             return
         elif get_errno(e) in BAD_SOCK:
             self._remove_bad_fds()
             return
         else:
             raise
Example #43
0
 def send(self, data):
     while True:
         try:
             os.write(self._fileno, data)
         except OSError as e:
             if get_errno(e) not in SOCKET_BLOCKING:
                 raise IOError(*e.args)
         trampoline(self, write=True)
Example #44
0
 def recv(self, buflen):
     trampoline(self, read=True, timeout=self._timeout)
     while True:
         try:
             return os.read(self._fileno, buflen)
         except OSError, e:
             if get_errno(e) != errno.EAGAIN:
                 raise IOError(*e.args)
Example #45
0
 def read(self, buflen):
     while True:
         try:
             return _original_os.read(self._fileno, buflen)
         except OSError as e:
             if get_errno(e) not in SOCKET_BLOCKING:
                 raise IOError(*e.args)
         self._trampoline(self, read=True)
Example #46
0
 def recv(self, buflen):
     trampoline(self, read=True, timeout=self._timeout)
     while True:
         try:
             return os.read(self._fileno, buflen)
         except OSError, e:
             if get_errno(e) != errno.EAGAIN:
                 raise IOError(*e.args)
Example #47
0
 def sendall(self, data):
     len_data = len(data)
     os_write = os.write
     fileno = self._fileno
     try:
         total_sent = os_write(fileno, data)
     except OSError as e:
         if get_errno(e) != errno.EAGAIN:
             raise IOError(*e.args)
         total_sent = 0
     while total_sent < len_data:
         self._trampoline(self, write=True)
         try:
             total_sent += os_write(fileno, data[total_sent:])
         except OSError as e:
             if get_errno(e) != errno. EAGAIN:
                 raise IOError(*e.args)
 def send(self, data, flags=0):
     # *NOTE: gross, copied code from ssl.py becase it's not factored well enough to be used as-is
     if self._sslobj:
         if flags != 0:
             raise ValueError("non-zero flags not allowed in calls to send() on %s" % self.__class__)
         while True:
             try:
                 v = self._sslobj.write(data)
             except SSLError, e:
                 if get_errno(e) == SSL_ERROR_WANT_READ:
                     return 0
                 elif get_errno(e) == SSL_ERROR_WANT_WRITE:
                     return 0
                 else:
                     raise
             else:
                 return v
Example #49
0
    def handle_one_request(self):
        if self.server.max_http_version:
            self.protocol_version = self.server.max_http_version

        self.raw_requestline = self._read_request_line()
        if not self.raw_requestline:
            self.close_connection = 1
            return
        if len(self.raw_requestline) >= self.server.url_length_limit:
            self.wfile.write(RESPONSE_414)
            self.close_connection = 1
            return

        orig_rfile = self.rfile
        try:
            self.rfile = FileObjectForHeaders(self.rfile)
            if not self.parse_request():
                return
        except HeaderLineTooLong:
            self.wfile.write(
                b"HTTP/1.0 400 Header Line Too Long\r\n"
                b"Connection: close\r\nContent-length: 0\r\n\r\n")
            self.close_connection = 1
            return
        except HeadersTooLarge:
            self.wfile.write(
                b"HTTP/1.0 400 Headers Too Large\r\n"
                b"Connection: close\r\nContent-length: 0\r\n\r\n")
            self.close_connection = 1
            return
        finally:
            self.rfile = orig_rfile

        content_length = self.headers.get('content-length')
        if content_length is not None:
            try:
                if int(content_length) < 0:
                    raise ValueError
            except ValueError:
                # Negative, or not an int at all
                self.wfile.write(
                    b"HTTP/1.0 400 Bad Request\r\n"
                    b"Connection: close\r\nContent-length: 0\r\n\r\n")
                self.close_connection = 1
                return

        self.environ = self.get_environ()
        self.application = self.server.app
        try:
            self.server.outstanding_requests += 1
            try:
                self.handle_one_response()
            except socket.error as e:
                # Broken pipe, connection reset by peer
                if support.get_errno(e) not in BROKEN_SOCK:
                    raise
        finally:
            self.server.outstanding_requests -= 1
Example #50
0
 def write(self, data):
     while True:
         try:
             return _original_os.write(self._fileno, data)
         except OSError as e:
             if get_errno(e) not in SOCKET_BLOCKING:
                 raise IOError(*e.args)
             else:
                 trampoline(self, write=True)
Example #51
0
def read(fd, n):
    """read(fd, buffersize) -> string

    Read a file descriptor."""
    while True:
        try:
            return __original_read__(fd, n)
        except (OSError, IOError) as e:
            if get_errno(e) != errno.EAGAIN:
                raise
        except socket.error as e:
            if get_errno(e) == errno.EPIPE:
                return ''
            raise
        try:
            hubs.trampoline(fd, read=True)
        except hubs.IOClosed:
            return ''
Example #52
0
 def write(self, data):
     while True:
         try:
             return _original_os.write(self._fileno, data)
         except OSError as e:
             if get_errno(e) not in SOCKET_BLOCKING:
                 raise IOError(*e.args)
             else:
                 trampoline(self, write=True)
Example #53
0
 def spam_to_me(address):
     sock = eventlet.connect(address)
     while True:
         try:
             sock.sendall(b'hello world')
         except socket.error as e:
             if get_errno(e) == errno.EPIPE:
                 return
             raise
Example #54
0
 def finish(self):
     try:
         BaseHTTPServer.BaseHTTPRequestHandler.finish(self)
     except socket.error as e:
         # Broken pipe, connection reset by peer
         if support.get_errno(e) not in BROKEN_SOCK:
             raise
     greenio.shutdown_safe(self.connection)
     self.connection.close()
Example #55
0
 def recv(self, buflen, flags=0):
     fd = self.fd
     if self.act_non_blocking:
         return fd.recv(buflen, flags)
     while True:
         try:
             return fd.recv(buflen, flags)
         except socket.error, e:
             if get_errno(e) in SOCKET_BLOCKING:
                 pass
             elif get_errno(e) in SOCKET_CLOSED:
                 return ''
             else:
                 raise
         trampoline(fd, 
             read=True, 
             timeout=self.gettimeout(), 
             timeout_exc=socket.timeout("timed out"))
Example #56
0
 def recv(self, buflen):
     while True:
         try:
             data = os.read(self._fileno, buflen)
             return data
         except OSError, e:
             if get_errno(e) != errno.EAGAIN:
                 raise IOError(*e.args)
         trampoline(self, read=True)