Commit b5acdf4a authored by Jason Madden's avatar Jason Madden

Avoid any Py3 or PYPY specific code in backdoor.py.

Don't attempt to subclass the internal socket._fileobject class, because using that takes special platform knowledge. Instead, proxy around it. This lets us drop a call to gc.collect() under PyPy because the refcounting is now correct. It also lets us clean up the implementation.

Update the docs.
parent e8f14c21
# Copyright (c) 2009-2014, gevent contributors
# Based on eventlet.backdoor Copyright (c) 2005-2006, Bob Ippolito
"""
Interactive greenlet-based network console that can be used in any process.
The :class:`BackdoorServer` provides a REPL inside a running process. As
long as the process is monkey-patched, the ``BackdoorServer`` can coexist
with other elements of the process.
.. seealso:: :class:`code.InteractiveConsole`
"""
from __future__ import print_function
import sys
from code import InteractiveConsole
from gevent import socket
from gevent.greenlet import Greenlet
from gevent.hub import PY3, PYPY, getcurrent
from gevent.hub import getcurrent
from gevent.server import StreamServer
if PYPY:
import gc
__all__ = ['BackdoorServer']
......@@ -25,6 +30,7 @@ except AttributeError:
class _Greenlet_stdreplace(Greenlet):
# A greenlet that replaces sys.std[in/out/err] while running.
_fileobj = None
def switch(self, *args, **kw):
......@@ -49,78 +55,114 @@ class _Greenlet_stdreplace(Greenlet):
class BackdoorServer(StreamServer):
"""Provide a backdoor to a program for debugging purposes.
"""
Provide a backdoor to a program for debugging purposes.
You may bind to any interface, but for security purposes it is recommended
that you bind to 127.0.0.1.
.. warning:: This backdoor provides no authentication and makes no
attempt to limit what remote users can do. Anyone that
can access the server can take any action that the running
python process can. Thus, while you may bind to any interface, for
security purposes it is recommended that you bind to one
only accessible to the local machine, e.g.,
127.0.0.1/localhost.
Basic usage:
Basic usage::
>> from gevent.backdoor import BackdoorServer
>> server = BackdoorServer(('127.0.0.1', 5001),
... locals={'foo': "From defined scope!"})
>> server.serve_forever()
from gevent.backdoor import BackdoorServer
server = BackdoorServer(('127.0.0.1', 5001),
banner="Hello from gevent backdoor!",
locals={'foo': "From defined scope!"})
server.serve_forever()
In a another terminal, connect with...
In a another terminal, connect with...::
$ telnet 127.0.0.1 5001
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
Python 2.7.5 (default, May 12 2013, 12:00:47)
[GCC 4.8.0 20130502 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>> print foo
Hello from gevent backdoor!
>> print(foo)
From defined scope!
"""
def __init__(self, listener, locals=None, banner=None, **server_args):
"""
:keyword locals: If given, a dictionary of "builtin" values that will be available
at the top-level.
:keyword banner: If geven, a string that will be printed to each connecting user.
"""
StreamServer.__init__(self, listener, spawn=_Greenlet_stdreplace.spawn, **server_args)
self.locals = locals
_locals = {'__doc__': None, '__name__': '__console__'}
if locals:
_locals.update(locals)
self.locals = _locals
self.banner = banner
self.stderr = sys.stderr
def handle(self, conn, address):
f = getcurrent()._fileobj = _fileobject(conn)
f.stderr = self.stderr
getcurrent().switch_in()
try:
console = InteractiveConsole(self.locals)
def _create_interactive_locals(self):
# Create and return a *new* locals dictionary based on self.locals,
# and set any new entries in it. (InteractiveConsole does not
# copy its locals value)
_locals = self.locals.copy()
# __builtins__ may either be the __builtin__ module or
# __builtin__.__dict__ in the latter case typing
# __builtin__.__dict__; in the latter case typing
# locals() at the backdoor prompt spews out lots of
# useless stuff
try:
import __builtin__
console.locals["__builtins__"] = __builtin__
_locals["__builtins__"] = __builtin__
except ImportError:
import builtins
console.locals["builtins"] = builtins
console.locals['__builtins__'] = builtins
_locals["builtins"] = builtins
_locals['__builtins__'] = builtins
return _locals
def handle(self, conn, address):
"""
Interact with one remote user.
.. versionchanged:: 1.1b2 Each connection gets its own
``locals`` dictionary. Previously they were shared in a
potentially unsafe manner.
"""
fobj = conn.makefile(mode="rw")
fobj = _fileobject(conn, fobj, self.stderr)
getcurrent()._fileobj = fobj
getcurrent().switch_in()
try:
console = InteractiveConsole(self._create_interactive_locals())
console.interact(banner=self.banner)
except SystemExit: # raised by quit()
if not PY3:
if hasattr(sys, 'exc_clear'): # py2
sys.exc_clear()
finally:
conn.close()
f.close()
if PYPY:
# The underlying socket somewhere has a reference
# that's not getting closed until finalizers run.
# Without running them, test__backdoor.Test.test_sys_exit
# hangs forever
gc.collect()
fobj.close()
class _fileobject(object):
"""
A file-like object that wraps the result of socket.makefile (composition
instead of inheritance lets us work identically under CPython and PyPy).
We write directly to the socket, avoiding the buffering that the text-oriented
makefile would want to do (otherwise we'd be at the mercy of waiting on a
flush() to get called for the remote user to see data); this beats putting
the file in binary mode and translating everywhere with a non-default
encoding.
"""
def __init__(self, sock, fobj, stderr):
self._sock = sock
self._fobj = fobj
self.stderr = stderr
class _fileobject(socket._fileobject):
def __getattr__(self, name):
return getattr(self._fobj, name)
if not PY3:
def write(self, data):
self._sock.sendall(data)
else:
def write(self, data):
if isinstance(data, str):
if not isinstance(data, bytes):
data = data.encode('utf-8')
self._sock.sendall(data)
......@@ -130,18 +172,18 @@ class _fileobject(socket._fileobject):
def flush(self):
pass
def _readline(self, *a):
return socket._fileobject.readline(self, *a).replace(b"\r\n", b"\n")
if not PY3:
readline = _readline
else:
def readline(self, *a):
line = self._readline(*a)
return line.decode('utf-8')
try:
return self._fobj.readline(*a).replace("\r\n", "\n")
except UnicodeError:
# Typically, under python 3, a ^C on the other end
return ''
if __name__ == '__main__':
if not sys.argv[1:]:
print('USAGE: %s PORT' % sys.argv[0])
print('USAGE: %s PORT [banner]' % sys.argv[0])
else:
BackdoorServer(('127.0.0.1', int(sys.argv[1])), locals={'hello': 'world'}).serve_forever()
BackdoorServer(('127.0.0.1', int(sys.argv[1])),
banner=(sys.argv[2] if len(sys.argv) > 2 else None),
locals={'hello': 'world'}).serve_forever()
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment