Example #1
0
    def test_pause_pipe_writer(self):
        """Test pausing and resuming writing to a socketpair"""

        data = 4 * 1024 * 1024 * "*"

        rsock1, wsock1 = socket.socketpair()
        rsock2, wsock2 = socket.socketpair()

        reader1, writer1 = yield from asyncio.open_unix_connection(sock=rsock1)
        reader2, writer2 = yield from asyncio.open_unix_connection(sock=rsock2)

        with (yield from self.connect()) as conn:
            process = yield from conn.create_process(input=data)

            yield from asyncio.sleep(1)

            yield from process.redirect_stdout(wsock1)
            yield from process.redirect_stderr(wsock2)

            stdout_data, stderr_data = yield from asyncio.gather(reader1.read(), reader2.read())

            writer1.close()
            writer2.close()

            yield from process.wait()

        self.assertEqual(stdout_data.decode(), data)
        self.assertEqual(stderr_data.decode(), data)
Example #2
0
 def __init__(self, pcapfile, connection, ssfile):
     self.ssfile = ssfile
     self.pcapfile = pcapfile
     self.connection = connection
     self.inbound = dict()
     self.outbound = dict()
     self.in_rsocket, self.in_wsocket = socket.socketpair()
     self.out_rsocket, self.out_wsocket = socket.socketpair()
Example #3
0
    def test_remove_handler_from_handler(self):
        # Create two sockets with simultaneous read events.
        client, server = socket.socketpair()
        try:
            client.send(b"abc")
            server.send(b"abc")

            # After reading from one fd, remove the other from the IOLoop.
            chunks = []

            def handle_read(fd, events):
                chunks.append(fd.recv(1024))
                if fd is client:
                    self.io_loop.remove_handler(server)
                else:
                    self.io_loop.remove_handler(client)

            self.io_loop.add_handler(client, handle_read, self.io_loop.READ)
            self.io_loop.add_handler(server, handle_read, self.io_loop.READ)
            self.io_loop.call_later(0.1, self.stop)
            self.wait()

            # Only one fd was read; the other was cleanly removed.
            self.assertEqual(chunks, [b"abc"])
        finally:
            client.close()
            server.close()
Example #4
0
def start_worker_process(cf, id=-1):
    global tasks, processes, processes_hash, num_processes, prepare_processes, poll
    ctx = cf.conf["ctx"]
    if id < 0:
        s = 0
        while s < ctx["maxworkers"]:
            if processes[s]["pid"] == -1:
                break
            s += 1
    else:
        s = id
    process = processes[s]
    pid = os.getpid()
    p = socket.socketpair()
    pfd = [p[0].fileno(), p[1].fileno()]
    flags = fcntl.fcntl(pfd[0], fcntl.F_GETFD)
    fcntl.fcntl(pfd[0], fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)
    flags = fcntl.fcntl(pfd[1], fcntl.F_GETFD)
    fcntl.fcntl(pfd[1], fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)
    fcntl.fcntl(pfd[1], fcntl.F_SETOWN, pid)
    process["id"] = s
    process["channel"] = p
    try:
        pid = os.fork()
    except OSError, e:
        cf.log.error("Can't fork")
        return None
Example #5
0
    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 #6
0
    def test_pair_makefile(self):
        """Test makefile() with socketpair()
        which behave differently than a plain socket() in python 2.X

        These must behave like a socket._fileobject wrapping a raw
        _socket.socket.  Closing a _socket.socket is immediate, and necessary
        to terminate readlines()
        """

        sA, sB = socket.socketpair()

        A, B = sA.makefile("w"), sB.makefile("r")
        self.assertNotEqual(A._sock.fileno(), -1)
        self.assertNotEqual(B._sock.fileno(), -1)

        def tx2():
            for i in range(10):
                print(i, file=A)
            A.close()  # flush...
            sA.close()  # Actually close the socket, completes readlines()

        tx2 = cothread.Spawn(tx2, raise_on_wait=True)

        Ls = B.readlines()
        B.close()

        tx2.Wait(1.0)

        sB.close()

        self.assertEqual(Ls, ["0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "9\n"])
Example #7
0
def main():
    socks = []

    for i in xrange(6):
        sock_send, sock_recv = socket.socketpair()
        child_pid = os.fork()
        if not child_pid:
            socks = None
            child_init(i, sock_recv)
            return
        children[child_pid] = i
        socks.append(sock_send)

    ioloop = IOLoop.instance()
    cb = stack_context.wrap(partial(master_check_send, socks))
    ioloop.add_handler(sys.stdin.fileno(), cb, ioloop.READ)

    PeriodicCallback(check_childs, 5000).start()

    def stop(sig, frame):
        ioloop.add_callback(ioloop.stop)
        for pid in children.keys():
            try:
                os.kill(pid, signal.SIGINT)
            except:
                pass

    signal.signal(signal.SIGINT, stop)
    signal.signal(signal.SIGTERM, stop)
    ioloop.start()

    sys.exit()
Example #8
0
def live_profile(script, timer, interval, pickle_protocol, mono):
    """Profile a Python script continuously."""
    filename, code, globals_ = script
    sys.argv[:] = [filename]
    parent_sock, child_sock = socket.socketpair()
    pid = os.fork()
    if pid == 0:
        # child
        devnull = os.open(os.devnull, os.O_RDWR)
        for f in [sys.stdin, sys.stdout, sys.stderr]:
            os.dup2(devnull, f.fileno())
        frame = sys._getframe()
        profiler = BackgroundProfiler(timer, frame, code)
        profiler.prepare()
        server_args = (noop, interval, pickle_protocol)
        server = SelectProfilingServer(None, profiler, *server_args)
        server.clients.add(child_sock)
        spawn_thread(server.connected, child_sock)
        try:
            exec_(code, globals_)
        finally:
            child_sock.close()
    else:
        # parent
        viewer, loop = make_viewer(mono)
        title = get_title(filename)
        client = ProfilingClient(viewer, loop.event_loop, parent_sock, title)
        client.start()
        try:
            loop.run()
        except KeyboardInterrupt:
            pass
        finally:
            parent_sock.close()
            os.kill(pid, signal.SIGINT)
Example #9
0
        def forkrun(self):
            self.fd, w = socket.socketpair()
            self.pid = os.fork()
            if self.pid == 0:
                # child
                progress.disable()
                self.fd.close()

                class Redir:
                    def __init__(self, fd):
                        self.fd = fd

                    def write(self, s):
                        self.fd.sendall(s)

                sys.stdout = Redir(w)
                try:
                    rv = self.fn()
                except Exception, e:
                    # import traceback
                    # traceback.print_exc()
                    print "Exception:", e
                    rv = False
                print exitval
                if rv:
                    sys.exit(0)
                else:
                    sys.exit(1)
Example #10
0
 def test_simple(self):
     # Make asm
     asm = async.AsyncMgr()
     # Make room for 40 cakes
     tid = "".join(chr(random.randint(0, 255)) for _ in range(20))
     db1 = dbconn.DbConn(":memory:")
     ss1 = store.SyncStore(tid, db1, 41 * (len("text/plain") + store.RECORD_OVERHEAD))
     # Insert some records
     all_data = []
     for i in range(20):
         TestSync.add_data(all_data, ss1, i)
     # Make something to sync it to
     db2 = dbconn.DbConn(":memory:")
     ss2 = store.SyncStore(tid, db2, 41 * (len("text/plain") + store.RECORD_OVERHEAD))
     # Make some fake socket action
     for i in range(20, 40):
         TestSync.add_data(all_data, ss2, i)
     # Make the connections
     (sock1, sock2) = socket.socketpair()
     node1 = SyncConnection(asm, sock1)
     node2 = SyncConnection(asm, sock2)
     node1.start_sync(ss1, 0, lambda seq: None)
     node2.start_sync(ss2, 0, lambda seq: None)
     # Kick off some async action
     asm.run(1.0)
     # Check the client has records
     for i in range(40):
         self.assertTrue(ss1.get_data(record.RT_WORKTOKEN, all_data[i])[0] is not None)
         self.assertTrue(ss2.get_data(record.RT_WORKTOKEN, all_data[i])[0] is not None)
def test_parse_from_real_socket():
    # would fail on python2.6 before the recv_into hack
    sock, sink = socket.socketpair()
    sink.send(complete_request)
    reader = SocketReader(sock)
    stream = HttpStream(reader)
    assert stream.headers()
    def rpc_run(self, pcode, user, visitor):
        uid = 61020

        userdir = "/tmp/" + hashlib.md5(user).hexdigest()

        if not os.path.exists(userdir):
            os.makedirs(userdir)
            os.chown(userdir, uid, uid)
            os.chmod(userdir, 0700)

        db = cred_setup()
        person = db.query(Cred).get(user)
        token = person.token

        (sa, sb) = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM, 0)
        pid = os.fork()
        if pid == 0:
            if os.fork() <= 0:
                sa.close()
                ProfileAPIServer(user, visitor, token).run_sock(sb)
                sys.exit(0)
            else:
                sys.exit(0)
        sb.close()
        os.waitpid(pid, 0)

        sandbox = sandboxlib.Sandbox(userdir, uid, "/profilesvc/lockfile")
        with rpclib.RpcClient(sa) as profile_api_client:
            return sandbox.run(lambda: run_profile(pcode, profile_api_client))
Example #13
0
    def run(self):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.connect(("localhost", 1234))

        try:
            recvbuf = ""

            while True:
                if self.sad_mode:
                    self.sad_keep_alive()
                    continue

                data = self.socket.recv(8192)
                recvbuf += data

                if recvbuf.endswith("SAD?"):
                    print ""

                    client, server = socket.socketpair()

                    recvbuf = ""
                    self.sad_mode = True
                    self.client = client

                    SimpleAmigaDebuggerThread(server).start()

                sys.stdout.write(data)
                sys.stdout.flush()

                recvbuf = recvbuf[-4:]
        except KeyboardInterrupt:
            pass

        self.socket.close()
Example #14
0
    def setUp(self):
        self.mod = self.modules["mpd_server"]
        config.init()
        init_fake_app()

        MPDServerPlugin = self.mod.MPDServerPlugin
        MPDConnection = self.mod.main.MPDConnection
        MPDService = self.mod.main.MPDService

        class Server(object):
            service = MPDService(app, MPDServerPlugin())

            def _remove_connection(self, conn):
                pass

        server = Server()
        s, c = socket.socketpair()
        self.s = s
        c.setblocking(False)
        s.settimeout(1)
        self.conn = MPDConnection(server, c)
        self.conn.handle_init(server)
        while Gtk.events_pending():
            Gtk.main_iteration_do(True)
        self.s.recv(9999)
def main():
    foo, bar = socketpair()
    sent = send1msg(foo.fileno(), "Hello, world")
    print "Sent", sent, "bytes"
    (received, flags, ancillary) = recv1msg(bar.fileno(), 1024)
    print "Received", repr(received)
    print "Extra stuff, boring in this case", flags, ancillary
Example #16
0
    def test__copy_to_each(self):
        """Test the normal data case on both master_fd and stdin."""
        read_from_stdout_fd, mock_stdout_fd = self._pipe()
        pty.STDOUT_FILENO = mock_stdout_fd
        mock_stdin_fd, write_to_stdin_fd = self._pipe()
        pty.STDIN_FILENO = mock_stdin_fd
        socketpair = socket.socketpair()
        masters = [s.fileno() for s in socketpair]
        self.fds.extend(masters)

        # Feed data.  Smaller than PIPEBUF.  These writes will not block.
        os.write(masters[1], b"from master")
        os.write(write_to_stdin_fd, b"from stdin")

        # Expect two select calls, the last one will cause IndexError
        pty.select = self._mock_select
        self.select_rfds_lengths.append(2)
        self.select_rfds_results.append([mock_stdin_fd, masters[0]])
        self.select_rfds_lengths.append(2)

        with self.assertRaises(IndexError):
            pty._copy(masters[0])

        # Test that the right data went to the right places.
        rfds = select.select([read_from_stdout_fd, masters[1]], [], [], 0)[0]
        self.assertEqual([read_from_stdout_fd, masters[1]], rfds)
        self.assertEqual(os.read(read_from_stdout_fd, 20), b"from master")
        self.assertEqual(os.read(masters[1], 20), b"from stdin")
Example #17
0
def test_using_threads():
    capnp.remove_event_loop(True)
    capnp.create_event_loop(True)

    read, write = socket.socketpair(socket.AF_UNIX)

    def run_server():
        restorer = SimpleRestorer()
        server = capnp.TwoPartyServer(write, restorer)
        capnp.wait_forever()

    server_thread = threading.Thread(target=run_server)
    server_thread.daemon = True
    server_thread.start()

    client = capnp.TwoPartyClient(read)

    ref = test_capability_capnp.TestSturdyRefObjectId.new_message(tag="testInterface")
    cap = client.restore(ref)
    cap = cap.cast_as(test_capability_capnp.TestInterface)

    remote = cap.foo(i=5)
    response = remote.wait()

    assert response.x == "125"
Example #18
0
    def check_sendall_interrupted(self, with_timeout):
        # socketpair() is not stricly required, but it makes things easier.
        if not hasattr(signal, "alarm") or not hasattr(socket, "socketpair"):
            self.skipTest("signal.alarm and socket.socketpair required for this test")
        # Our signal handlers clobber the C errno by calling a math function
        # with an invalid domain value.
        def ok_handler(*args):
            self.assertRaises(ValueError, math.acosh, 0)

        def raising_handler(*args):
            self.assertRaises(ValueError, math.acosh, 0)
            1 // 0

        c, s = socket.socketpair()
        old_alarm = signal.signal(signal.SIGALRM, raising_handler)
        try:
            if with_timeout:
                # Just above the one second minimum for signal.alarm
                c.settimeout(1.5)
            with self.assertRaises(ZeroDivisionError):
                signal.alarm(1)
                c.sendall(b"x" * (1024 ** 2))
            if with_timeout:
                signal.signal(signal.SIGALRM, ok_handler)
                signal.alarm(1)
                self.assertRaises(socket.timeout, c.sendall, b"x" * (1024 ** 2))
        finally:
            signal.signal(signal.SIGALRM, old_alarm)
            c.close()
            s.close()
Example #19
0
 def test(self):
     msg = "hello world"
     x, y = socket.socketpair()
     x.sendall(msg)
     x.close()
     read = y.makefile().read()
     self.assertEqual(msg, read)
def main():
    if len(sys.argv) < 2:
        print "usage: python %s port" % sys.argv[0]
        return
    FORMAT = "%(asctime)-15s %(levelname)s %(message)s"
    logging.basicConfig(level=logging.DEBUG, format=FORMAT)
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(("0.0.0.0", int(sys.argv[1])))
    s.listen(1)
    logging.info("listening on 0.0.0.0:%s", sys.argv[1])

    pipes = []
    for i in range(4):
        pipe = socket.socketpair(socket.AF_UNIX)
        loop = Loop(pipe[1], "loop" + str(i))
        pipes.append(pipe[0])
        thread = threading.Thread(target=loop.loop)
        thread.setDaemon(True)
        thread.start()

    i = 0
    while True:
        conn, addr = s.accept()
        pipe = pipes[i]
        i = (i + 1) % len(pipes)
        sfd = "%04d" % (os.dup(conn.fileno()))
        pipe.send(sfd)
        conn.close()
        conn = None
Example #21
0
 def test_echo(self, concurrency):
     msg = b"ping"
     sockets = []
     try:
         for i in range(concurrency):
             sock1, sock2 = socket.socketpair()
             self.loop.create_dispatcher(Echo, sock2)
             sockets.append(sock1)
         t = concurrent.thread(self.loop.run_forever)
         t.start()
         try:
             start = time.time()
             for sock in sockets:
                 osutils.uninterruptible(sock.send, msg)
             for sock in sockets:
                 data = osutils.uninterruptible(sock.recv, len(msg))
                 self.assertEqual(data, msg)
             elapsed = time.time() - start
             print("%7d echos: %f seconds" % (concurrency, elapsed))
         finally:
             self.loop.call_soon_threadsafe(self.loop.stop)
             t.join()
     finally:
         for sock in sockets:
             sock.close()
Example #22
0
    def __init__(self, fd):
        (self._rsock, wsock) = socket.socketpair(socket.AF_UNIX, socket.SOCK_DGRAM)
        child = os.fork()
        if child != 0:
            wsock.close()
            self._child = child
            return

        self._rsock.close()

        # This is the read loop in the forked process and it won't quit until either the process
        # gets killed or there is a read error.
        try:
            while True:
                packet = os.read(fd, MAX_PACKET_SIZE)
                wsock.send(pickle.dumps((0, packet)))
                if len(packet) == 0:
                    break
        except KeyboardInterrupt:
            pass
        except OSError as e:
            wsock.send(pickle.dumps((e.errno, "")))
        finally:
            os.close(fd)
            wsock.close()
            os._exit(os.EX_OK)
Example #23
0
    def test_timeout(self):
        A, B = socket.socketpair()

        # specific user timeout
        A.settimeout(0.1)

        # some games so that the test won't hang if recv() never times out
        def op(sock):
            try:
                sock.recv(10)
                assert False, "Missed expected Timeout"
            except socket.error:
                return sock

        opA = cothread.Spawn(op, A, raise_on_wait=True)

        try:
            V = opA.Wait(1.0)
        except:
            opA.AbortWait()
            raise
        self.assertTrue(V is A)

        opB = cothread.Spawn(op, B, raise_on_wait=True)

        try:
            V = opB.Wait(2.0)
        except:
            opB.AbortWait()
            raise
        self.assertTrue(V is B)

        A.close()
        B.close()
Example #24
0
def main():
    # создаем пару связанных сокетов
    read_sock, write_sock = socketpair()
    print(str.format("[~] Create socket descriptors with ids: {} and {}", read_sock.fileno(), write_sock.fileno()))

    loop = asyncio.get_event_loop()

    # регистрируем дескриптор ресурсов инспектировать доступность на чтение
    # дескриптор сокета read_sock
    loop.add_reader(read_sock, reader, loop, read_sock)

    # эмулируем прием данных из сети; по сути передаем бинарную строку 'abc'
    # в метод send() объекта сокета
    loop.call_soon(write_sock.send, "abc".encode("utf-8"))

    try:
        # блокирующий вызов
        loop.run_forever()
    except KeyboardInterrupt:
        print("[x] Event loop interrupted by Ctrl + C")
    finally:
        # закрывает дескриторы сокетов
        read_sock.close()
        write_sock.close()
        print("[x] Socket descriptors are closed()")

        # закрываем событийный цикл
        loop.close()
Example #25
0
    def rpc_run(self, pcode, user, visitor):
        uid = 61018

        # localtime = time.asctime(time.localtime(time.time()))
        # userdir = '/tmp/' + (localtime[8]+localtime[17]+localtime[18]+localtime[14]+localtime[15])
        userdir = "/tmp" + "/" + user.replace("/", "9")
        if not os.path.exists(userdir):
            os.mkdir(userdir)
            os.chmod(userdir, 0770)
        # print "Directory created " + userdir

        db = zoodb.cred_setup()
        person = db.query(zoodb.Cred).get(user)
        if not person:
            return None
        token = person.token

        (sa, sb) = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM, 0)
        pid = os.fork()
        if pid == 0:
            if os.fork() <= 0:
                sa.close()
                ProfileAPIServer(user, visitor, token).run_sock(sb)
                sys.exit(0)
            else:
                sys.exit(0)
        sb.close()
        os.waitpid(pid, 0)

        sandbox = sandboxlib.Sandbox(userdir, uid, "/profilesvc/lockfile")
        with rpclib.RpcClient(sa) as profile_api_client:
            return sandbox.run(lambda: run_profile(pcode, profile_api_client))
Example #26
0
    def makeSockets(cls):
        """Make socket(s) to communicate with remote process.
        Returns string to send to remote process
        """

        if hasattr(socket, "AF_UNIX") and hasattr(socket, "socketpair"):
            # convenient interface
            cls.sockfamily = socket.AF_UNIX
            sock, socket2 = socket.socketpair(cls.sockfamily, socket.SOCK_STREAM)
            sendtext = "unix %i\n" % socket2.fileno()
            cls.socket2 = socket2
            waitaccept = False

        else:
            # otherwise mess around with internet sockets
            # * This is required for windows, which doesn't have AF_UNIX
            # * It is required where socketpair is not supported
            cls.sockfamily = socket.AF_INET
            sock = socket.socket(cls.sockfamily, socket.SOCK_STREAM)
            sock.bind(("localhost", 0))
            interface, port = sock.getsockname()
            sock.listen(1)
            sendtext = "internet %s %i\n" % (interface, port)
            waitaccept = True

        return (sock, sendtext, waitaccept)
Example #27
0
    def __init__(self, port_v6, port_v4, subnets_include, subnets_exclude, dnsport_v6, dnsport_v4, method, udp):
        self.auto_nets = []
        self.subnets_include = subnets_include
        self.subnets_exclude = subnets_exclude
        argvbase = (
            [sys.argv[1], sys.argv[0], sys.argv[1]]
            + ["-v"] * (helpers.verbose or 0)
            + ["--firewall", str(port_v6), str(port_v4), str(dnsport_v6), str(dnsport_v4), method, str(int(udp))]
        )
        if ssyslog._p:
            argvbase += ["--syslog"]
        argv_tries = [["sudo", "-p", "[local sudo] Password: "] + argvbase, ["su", "-c", " ".join(argvbase)], argvbase]

        # we can't use stdin/stdout=subprocess.PIPE here, as we normally would,
        # because stupid Linux 'su' requires that stdin be attached to a tty.
        # Instead, attach a *bidirectional* socket to its stdout, and use
        # that for talking in both directions.
        (s1, s2) = socket.socketpair()

        def setup():
            # run in the child process
            s2.close()

        e = None
        if os.getuid() == 0:
            argv_tries = argv_tries[-1:]  # last entry only
        for argv in argv_tries:
            try:
                if argv[0] == "su":
                    sys.stderr.write("[local su] ")
                self.p = ssubprocess.Popen(argv, stdout=s1, preexec_fn=setup)
                e = None
                break
            except OSError, e:
                pass
Example #28
0
    def test_select1(self):
        import select
        import socket

        s1, s2 = socket.socketpair()
        with hub.Timeout(1, MyException):
            select.select([s2.fileno()], [], [])
Example #29
0
    def setUp(self):
        (self.c, self.s) = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)

        self.client = TransPort(self.c)

        self.server = threading.Thread(target=_server, args=(self.s,))
        self.server.start()
Example #30
0
    def test__copy_eof_on_all(self):
        """Test the empty read EOF case on both master_fd and stdin."""
        read_from_stdout_fd, mock_stdout_fd = self._pipe()
        pty.STDOUT_FILENO = mock_stdout_fd
        mock_stdin_fd, write_to_stdin_fd = self._pipe()
        pty.STDIN_FILENO = mock_stdin_fd
        socketpair = socket.socketpair()
        for s in socketpair:
            self.addCleanup(s.close)
        masters = [s.fileno() for s in socketpair]

        os.close(masters[1])
        socketpair[1].close()
        os.close(write_to_stdin_fd)

        # Expect two select calls, the last one will cause IndexError
        pty.select = self._mock_select
        self.select_rfds_lengths.append(2)
        self.select_rfds_results.append([mock_stdin_fd, masters[0]])
        # We expect that both fds were removed from the fds list as they
        # both encountered an EOF before the second select call.
        self.select_rfds_lengths.append(0)

        with self.assertRaises(IndexError):
            pty._copy(masters[0])