[Pkg-privacy-commits] [obfsproxy] 80/353: Improve listener launching code.

Ximin Luo infinity0 at moszumanska.debian.org
Sat Aug 22 13:01:42 UTC 2015


This is an automated email from the git hooks/post-receive script.

infinity0 pushed a commit to branch master
in repository obfsproxy.

commit 2b43afcbfa53d00c1bb97e03071803dd57456c3b
Author: George Kadianakis <desnacked at riseup.net>
Date:   Fri Nov 2 04:31:18 2012 +0200

    Improve listener launching code.
---
 obfsproxy.py                          | 29 ++++--------
 obfsproxy/managed/client.py           | 74 ++++++++++++-----------------
 obfsproxy/managed/server.py           | 87 +++++++++++++++--------------------
 obfsproxy/network/launch_transport.py | 39 ++++++++++++++++
 obfsproxy/transports/transports.py    | 11 +++--
 5 files changed, 120 insertions(+), 120 deletions(-)

diff --git a/obfsproxy.py b/obfsproxy.py
index 43b4ad7..bc72e1e 100755
--- a/obfsproxy.py
+++ b/obfsproxy.py
@@ -11,11 +11,12 @@ import os
 import sys
 import argparse
 
+import obfsproxy.network.launch_transport as launch_transport
 import obfsproxy.transports.transports as transports
 import obfsproxy.common.log as log
 import obfsproxy.common.heartbeat as heartbeat
-from obfsproxy.managed.server import ManagedServer
-from obfsproxy.managed.client import ManagedClient
+import obfsproxy.managed.server as managed_server
+import obfsproxy.managed.client as managed_client
 
 from pyptlib.util import checkClientMode
 
@@ -61,10 +62,10 @@ def do_managed_mode(): # XXX bad code
     # XXX original code caught exceptions here!!!
     if checkClientMode():
         log.info('Entering client managed-mode.')
-        ManagedClient()
+        managed_client.do_managed_client()
     else:
         log.info('Entering server managed-mode.')
-        ManagedServer()
+        managed_server.do_managed_server()
 
 def do_external_mode(args):
     """This function starts obfsproxy's external-mode functionality."""
@@ -73,23 +74,11 @@ def do_external_mode(args):
     assert(args.name)
     assert(args.name in transports.transports)
 
-    transportClass = transports.get_transport_class_from_name_and_mode(args.name, args.mode)
-    if (transportClass is None):
-        log.error("Transport class was not found for '%s' in mode '%s'" % (args.name, args.mode))
-        sys.exit(1)
-
-    # XXX functionify
-    import obfsproxy.network.network as network
-    import obfsproxy.network.socks as socks
-    from twisted.internet import reactor, error, address, tcp
-
-    if (args.mode == 'client') or (args.mode == 'server'):
-        factory = network.StaticDestinationServerFactory(args.dest, args.mode, transportClass)
-    elif args.mode == 'socks':
-        factory = socks.SOCKSv4Factory(transportClass)
+    from twisted.internet import reactor
 
-    reactor.listenTCP(int(args.listen_addr[1]), factory)
-    log.info("Launching listener.")
+    addrport = launch_transport.launch_transport_listener(args.name, args.listen_addr, args.mode, args.dest)
+    log.info("Launched '%s' listener at '%s:%s' for transport '%s'." % \
+                 (args.mode, args.listen_addr[0], args.listen_addr[1], args.name))
     reactor.run()
 
 def consider_cli_args(args):
diff --git a/obfsproxy/managed/client.py b/obfsproxy/managed/client.py
index 6c49705..ec18e02 100644
--- a/obfsproxy/managed/client.py
+++ b/obfsproxy/managed/client.py
@@ -1,65 +1,49 @@
 #!/usr/bin/python
 # -*- coding: utf-8 -*-
 
-# XXX put listener/client-creation functions in their own file
 import obfsproxy.network.socks as socks
 from twisted.internet import reactor, error
 
+import obfsproxy.network.launch_transport as launch_transport
 import obfsproxy.transports.transports as transports
+import obfsproxy.common.log as log
 
 from pyptlib.client import init, reportSuccess, reportFailure, reportEnd
 from pyptlib.config import EnvError
 
-import obfsproxy.common.log as log
 import pprint
 
-class ManagedClient:
+def do_managed_client():
+    should_start_event_loop = False
 
-    def __init__(self):
-        try:
-            managedInfo = init(transports.transports.keys())
-        except EnvError:
-            log.warning("Client managed-proxy protocol failed.")
-            return
+    try:
+        managedInfo = init(transports.transports.keys())
+    except EnvError:
+        log.warning("Client managed-proxy protocol failed.")
+        return
 
-        log.debug("pyptlib gave us the following data:\n'%s'", pprint.pformat(managedInfo))
+    log.debug("pyptlib gave us the following data:\n'%s'", pprint.pformat(managedInfo))
 
-        for transport in managedInfo['transports']:
-            ok, addrport = self.launchClient(transport, managedInfo) # XXX start using exceptions
-            if ok:
-                log.debug("Successfully launched '%s' at '%s'" % (transport, str(addrport)))
-                reportSuccess(transport, 4, addrport, None, None) # XXX SOCKS v4 hardcoded
-            else:
-                log.info("Failed to launch '%s'" % transport)
-                reportFailure(transport, 'Failed to launch')
+    for transport in managedInfo['transports']:
+        try:
+            addrport = launch_transport.launch_transport_listener(transport, None, 'socks', None)
+        except transports.TransportNotFound:
+            log.warning("Could not find transport '%s'" % transport)
+            reportFailure(transport, "Could not find transport.")
+            continue
+        except error.CannotListenError:
+            log.warning("Could not set up listener for '%s'." % transport)
+            reportFailure(transport, "Could not set up listener.")
+            continue
+
+        should_start_event_loop = True
+        log.debug("Successfully launched '%s' at '%s'" % (transport, str(addrport)))
+        reportSuccess(transport, 4, addrport, None, None) # XXX SOCKS v4 hardcoded
 
-        reportEnd()
+    reportEnd()
 
+    if should_start_event_loop:
         log.info("Starting up the event loop.")
         reactor.run()
-
-    # XXX turn into a function to be used by exteral-mode code, etc.
-    def launchClient(self, name, managedInfo):
-        """
-        Launch a client of transport 'name' using the environment
-        information in 'managedInfo'.
-
-        Return a tuple (<ok>, (<addr>, <port>)), where <ok> is whether
-        the function was successful, and (<addr>, <port> is a tuple
-        representing where we managed to bind.
-        """
-
-        clientClass = transports.get_transport_class_from_name_and_mode(name, 'client')
-        if not clientClass:
-            log.error("Could not find transport class for '%s' (%s)." % (name, 'client'))
-            return False, None
-
-        factory = socks.SOCKSv4Factory(clientClass)
-
-        try:
-            addrport = reactor.listenTCP(0, factory, interface='localhost')
-        except error.CannotListenError:
-            log.error("Could not set up a client listener.")
-            return False, None
-
-        return True, (addrport.getHost().host, addrport.getHost().port)
+    else:
+        log.info("No transports launched. Nothing to do.")
diff --git a/obfsproxy/managed/server.py b/obfsproxy/managed/server.py
index 1dc0823..be8cc9d 100644
--- a/obfsproxy/managed/server.py
+++ b/obfsproxy/managed/server.py
@@ -1,67 +1,52 @@
 #!/usr/bin/python
 # -*- coding: utf-8 -*-
 
-# XXX put listener/client-creation functions in their own file
-import obfsproxy.network.network as network
 from twisted.internet import reactor, error, address, tcp
 
-import obfsproxy.transports.transports as transports
-
 from pyptlib.server import init, reportSuccess, reportFailure, reportEnd
 from pyptlib.config import EnvError
 
+import obfsproxy.network.network as network
+import obfsproxy.transports.transports as transports
+import obfsproxy.network.launch_transport as launch_transport
 import obfsproxy.common.log as log
-import pprint
-
-class ManagedServer:
 
-    def __init__(self):
-        try:
-            managedInfo = init(transports.transports.keys())
-        except EnvError:
-            log.warning("Server managed-proxy protocol failed.")
-            return
+import pprint
 
-        log.debug("pyptlib gave us the following data:\n'%s'", pprint.pformat(managedInfo))
+def do_managed_server():
+    should_start_event_loop = False
 
-        for transport, transport_bindaddr in managedInfo['transports'].items():
-            ok, addrport = self.launchServer(transport, transport_bindaddr, managedInfo)
-            if ok:
-                log.debug("Successfully launched '%s' at '%s'" % (transport, str(addrport)))
-                reportSuccess(transport, addrport, None)
-            else:
-                log.info("Failed to launch '%s' at '%s'" % (transport, str(addrport)))
-                reportFailure(transport, 'Failed to launch')
+    try:
+        managedInfo = init(transports.transports.keys())
+    except EnvError:
+        log.warning("Server managed-proxy protocol failed.")
+        return
 
-        reportEnd()
+    log.debug("pyptlib gave us the following data:\n'%s'", pprint.pformat(managedInfo))
 
+    for transport, transport_bindaddr in managedInfo['transports'].items():
+        try:
+            addrport = launch_transport.launch_transport_listener(transport,
+                                                                  transport_bindaddr,
+                                                                  'server',
+                                                                  managedInfo['orport'])
+        except transports.TransportNotFound:
+            log.warning("Could not find transport '%s'" % transport)
+            reportFailure(transport, "Could not find transport.")
+            continue
+        except error.CannotListenError:
+            log.warning("Could not set up listener for '%s'." % transport)
+            reportFailure(transport, "Could not set up listener.")
+            continue
+
+        should_start_event_loop = True
+        log.debug("Successfully launched '%s' at '%s'" % (transport, str(addrport)))
+        reportSuccess(transport, addrport, None)
+
+    reportEnd()
+
+    if should_start_event_loop:
         log.info("Starting up the event loop.")
         reactor.run()
-
-    def launchServer(self, name, bindaddr, managedInfo):
-        """
-        Launch a client of transport 'name' using the environment
-        information in 'managedInfo'.
-
-        Return a tuple (<ok>, (<addr>, <port>)), where <ok> is whether
-        the function was successful, and (<addr>, <port> is a tuple
-        representing where we managed to bind.
-        """
-
-        serverClass = transports.get_transport_class_from_name_and_mode(name, 'server')
-        if not serverClass:
-            log.error("Could not find transport class for '%s' (%s)." % (name, 'server'))
-            return False, None
-
-        factory = network.StaticDestinationServerFactory(managedInfo['orport'], 'server', serverClass)
-
-        try:
-            addrport = reactor.listenTCP(int(bindaddr[1]), factory)
-        except CannotListenError:
-            log.error("Could not set up a listener for TCP port '%s'." % bindaddr[1])
-            return False, None
-
-        return True, (addrport.getHost().host, addrport.getHost().port)
-
-if __name__ == '__main__':
-    server = ManagedServer()
+    else:
+        log.info("No transports launched. Nothing to do.")
diff --git a/obfsproxy/network/launch_transport.py b/obfsproxy/network/launch_transport.py
new file mode 100644
index 0000000..02a6f1b
--- /dev/null
+++ b/obfsproxy/network/launch_transport.py
@@ -0,0 +1,39 @@
+import obfsproxy.network.network as network
+import obfsproxy.transports.transports as transports
+import obfsproxy.network.socks as socks
+from twisted.internet import reactor
+
+def launch_transport_listener(transport, bindaddr, role, remote_addrport):
+    """
+    Launch a listener for 'transport' in role 'role' (socks/client/server).
+
+    If 'bindaddr' is set, then listen on bindaddr. Otherwise, listen
+    on an ephemeral port on localhost.
+    'remote_addrport' is the TCP/IP address of the other end of the
+    circuit. It's not used if we are in 'socks' role.
+
+    Return a tuple (addr, port) representing where we managed to bind.
+
+    Throws obfsproxy.transports.transports.TransportNotFound if the
+    transport could not be found.
+
+    Throws twisted.internet.error.CannotListenError if the listener
+    could not be set up.
+    """
+
+    transport_class = transports.get_transport_class(transport, role)
+    listen_host = bindaddr[0] if bindaddr else 'localhost'
+    listen_port = int(bindaddr[1]) if bindaddr else 0
+
+    if role == 'socks':
+        factory = socks.SOCKSv4Factory(transport_class)
+    else:
+        assert(remote_addrport)
+        factory = network.StaticDestinationServerFactory(remote_addrport, role, transport_class)
+
+    if role == 'server':
+        addrport = reactor.listenTCP(listen_port, factory)
+    else:
+        addrport = reactor.listenTCP(listen_port, factory, interface=listen_host)
+
+    return (addrport.getHost().host, addrport.getHost().port)
diff --git a/obfsproxy/transports/transports.py b/obfsproxy/transports/transports.py
index c74c54c..7de7c2c 100644
--- a/obfsproxy/transports/transports.py
+++ b/obfsproxy/transports/transports.py
@@ -12,8 +12,11 @@ transports = { 'dummy' : {'client' : dummy.DummyClient, 'socks' : dummy.DummyCli
                'obfs2' : {'client' : obfs2.Obfs2Client, 'socks' : obfs2.Obfs2Client,  'server' : obfs2.Obfs2Server } }
 #               'obfs3' : {'client' : obfs3.Obfs3Client, 'socks' : obfs3.Obfs3Client,  'server' : obfs3.Obfs3Server }
 
-def get_transport_class_from_name_and_mode(name, mode):
-    if (name in transports) and (mode in transports[name]):
-        return transports[name][mode]
+def get_transport_class(name, role):
+    if (name in transports) and (role in transports[name]):
+        return transports[name][role]
     else:
-        return None
+        raise TransportNotFound
+
+class TransportNotFound(Exception): pass
+

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-privacy/packages/obfsproxy.git



More information about the Pkg-privacy-commits mailing list