[Zope-CVS] CVS: Packages/tcpwatch - tcpwatch:1.3

Shane Hathaway shane@cvs.zope.org
Wed, 20 Feb 2002 16:43:46 -0500


Update of /cvs-repository/Packages/tcpwatch
In directory cvs.zope.org:/tmp/cvs-serv19181

Modified Files:
	tcpwatch 
Log Message:
Changed the word "proxy" to "forward" to avoid confusion with HTTP proxying.


=== Packages/tcpwatch/tcpwatch 1.2 => 1.3 ===
 
-"""TCPWatch, a transparent proxy for monitoring connections.
+"""TCPWatch, a connection forwarder for monitoring connections.
 
 Requires Python 2.1 or above.
 """
@@ -87,7 +87,7 @@
 
 #############################################################################
 #
-# Transparent proxy
+# Connection forwarder
 #
 #############################################################################
 
@@ -176,23 +176,24 @@
 
 
 
-class ProxyConnectionInfo:
+class ForwardedConnectionInfo:
 
     transaction = 1
 
     def __init__(self, connection_number, client_addr, server_addr):
+        self.opened = time()
         self.connection_number = connection_number
         self.client_addr = client_addr
         self.server_addr = server_addr
 
     def dup(self):
-        return ProxyConnectionInfo(self.connection_number,
-                                   self.client_addr,
-                                   self.server_addr)
+        return ForwardedConnectionInfo(self.connection_number,
+                                       self.client_addr,
+                                       self.server_addr)
 
 
 
-class ProxyService (asyncore.dispatcher):
+class ForwardingService (asyncore.dispatcher):
 
     _counter = 0
 
@@ -220,8 +221,8 @@
             self._counter = counter
             factory = self._obs_factory
             if factory is not None:
-                pci = ProxyConnectionInfo(counter, addr, self._dest)
-                obs = factory(pci)
+                fci = ForwardedConnectionInfo(counter, addr, self._dest)
+                obs = factory(fci)
                 dests1 = (ep2, EndpointObserver(obs, 1))
                 dests2 = (ep1, EndpointObserver(obs, 0))
             else:
@@ -294,17 +295,16 @@
 
         t = time() - self._start
         min, sec = divmod(int(t), 60)
-        ms = int((t - int(t)) * 1000)
-        self.write('[%02d:%02d.%03d - %s %s]\n' % (min, sec, ms, who, m))
+        self.write('[%02d:%06.3f - %s %s]\n' % (min, sec, who, m))
         self.flush()
 
-    def connection_from(self, pci):
+    def connection_from(self, fci):
         self._output_message(
             '%s:%s forwarded to %s:%s' %
-            (tuple(pci.client_addr) + tuple(pci.server_addr)), 1)
-        if pci.transaction > 1:
+            (tuple(fci.client_addr) + tuple(fci.server_addr)), 1)
+        if fci.transaction > 1:
             self._output_message(
-                ('HTTP transaction #%d' % pci.transaction), 1)
+                ('HTTP transaction #%d' % fci.transaction), 1)
 
     def connected(self, from_client):
         self._output_message('connected', from_client)
@@ -355,9 +355,9 @@
 
     # __implements__ = IConnectionObserver
 
-    def __init__(self, pci):
+    def __init__(self, fci):
         BasicObserver.__init__(self)
-        self.connection_from(pci)
+        self.connection_from(fci)
 
     def write(self, s):
         sys.stdout.write(s)
@@ -373,7 +373,7 @@
 #############################################################################
 
 
-def setupTk(proxy_params, split_http=0, colorized=1):
+def setupTk(fwd_params, config_info, colorized=1):
     """Starts the Tk application and returns an observer factory.
     """
 
@@ -386,12 +386,6 @@
     except ImportError:
         from StringIO import StringIO
 
-    config_info = '\n'.join(map(
-        lambda args: 'Forwarding %s:%d -> %s:%d' % args, proxy_params))
-
-    if split_http:
-        config_info += '\n\n*** HTTP connection splitting enabled. ***'
-
     startup_text = COPYRIGHT + ("""
 
 Use your client to connect to the proxied port(s) then click
@@ -461,26 +455,26 @@
 
 
     class TkConnectionObserver (BasicObserver):
-        '''A connection observer which forwards captured data to a TCPWatch
+        '''A connection observer which shows captured data in a TCPWatch
         frame.  The data is mangled for presentation.
         '''
         # __implements__ = IConnectionObserver
 
-        def __init__(self, frame, pci, colorized=1):
+        def __init__(self, frame, fci, colorized=1):
             BasicObserver.__init__(self)
             self._output = []  # list of tuples containing (text, style)
             self._frame = frame
             self._colorized = colorized
-            t = localtime(self._start)
-            if pci.transaction > 1:
+            t = localtime(fci.opened)
+            if fci.transaction > 1:
                 base_id = '%03d-%02d' % (
-                    pci.connection_number, pci.transaction)
+                    fci.connection_number, fci.transaction)
             else:
-                base_id = '%03d' % pci.connection_number
+                base_id = '%03d' % fci.connection_number
             id = '%s (%02d:%02d:%02d)' % (base_id, t[3], t[4], t[5])
             self._id = id
             frame.addConnection(id, self)
-            self.connection_from(pci)
+            self.connection_from(fci)
 
         def write(self, s):
             output = (s, "message")
@@ -530,7 +524,7 @@
 
 
 
-    def createApp(proxy_params):
+    def createApp(fwd_params):
         app = TkTCPWatch()
         try:
             wm_title = app.master.wm_title
@@ -538,14 +532,14 @@
             pass  # No wm_title method available.
         else:
             titlepart = ', '.join(map(
-                lambda args: '%s:%d -> %s:%d' % args, proxy_params))
+                lambda args: '%s:%d -> %s:%d' % args, fwd_params))
             wm_title('TCPWatch [%s]' % titlepart)
         return app
 
-    app = createApp(proxy_params)
+    app = createApp(fwd_params)
 
-    def tkObserverFactory(pci, app=app, colorized=colorized):
-        return TkConnectionObserver(app, pci, colorized)
+    def tkObserverFactory(fci, app=app, colorized=colorized):
+        return TkConnectionObserver(app, fci, colorized)
 
     def window_loop(app):
         app.mainloop()
@@ -838,16 +832,16 @@
     req_index = 0
     resp_index = 0
 
-    def __init__(self, sub_factory, pci):
+    def __init__(self, sub_factory, fci):
         self.sub_factory = sub_factory
         self.transactions = []  # (observer, request_data, response_data)
-        self.pci = pci
+        self.fci = fci
         self._newTransaction()
 
     def _newTransaction(self):
-        pci = self.pci.dup()
-        pci.transaction = len(self.transactions) + 1
-        obs = self.sub_factory(pci)
+        fci = self.fci.dup()
+        fci.transaction = len(self.transactions) + 1
+        obs = self.sub_factory(fci)
         req = HTTPStreamParser(1)
         resp = HTTPStreamParser(0)
         self.transactions.append((obs, req, resp))
@@ -903,11 +897,11 @@
     print 'Simple usage: tcpwatch -L listen_port:dest_hostname:dest_port'
     print """
   -L <listen_port>:<dest_port>
-     Set up a local transparent proxy
+     Set up a local forwarded connection
   -L <listen_port>:<dest_host>:<dest_port>
-     Set up a transparent proxy to a specified host
+     Set up a forwarded connection to a specified host
   -L <listen_host>:<listen_port>:<dest_host>:<dest_port>
-     Set up a transparent proxy to a specified host and bound to an interface
+     Set up a forwarded connection to a specified host, bound to an interface
 
   -h (or --http) Parse as HTTP, splitting up multi-transaction connections
   -s Output to stdout instead of a Tkinter window
@@ -923,9 +917,9 @@
 
 def main(args):
 
-    optlist, extra = getopt.getopt(args, 'hnsL:', ['help', 'http'])
+    optlist, extra = getopt.getopt(args, 'hL:np:s', ['help', 'http'])
 
-    proxy_params = []
+    fwd_params = []
     obs_factory = None
     show_config = 0
     split_http = 0
@@ -941,6 +935,20 @@
         elif option == '-s':
             show_config = 1
             obs_factory = StdoutObserver
+##        elif option == '-p':
+##            # HTTP proxy (also turns on -h)
+##            info = value.split(':')
+##            listen_host = ''
+##            if len(info) == 1:
+##                listen_port = int(info[0])
+##            elif len(info) == 2:
+##                listen_host = info[0]
+##                listen_port = int(info[1])
+##            else:
+##                usageError('-p requires a port or a host:port parameter')
+##            proxy_params.append(
+##                (listen_host, listen_port, '(HTTP)', 0))
+##            split_http = 1
         elif option == '-L':
             info = value.split(':')
             listen_host = ''
@@ -959,31 +967,40 @@
                 dest_port = int(info[3])
             else:
                 usageError('-L requires 2, 3, or 4 colon-separated parameters')
-            proxy_params.append(
+            fwd_params.append(
                 (listen_host, listen_port, dest_host, dest_port))
 
-    if not proxy_params:
+    if not fwd_params:
         usage()
 
+    config_info = '\n'.join(map(
+        lambda args: 'Forwarding %s:%d -> %s:%d' % args, fwd_params))
+    if split_http:
+        config_info += '\n\n*** HTTP connection splitting enabled. ***'
+
     if obs_factory is None:
         # Use Tk by default.
-        obs_factory = setupTk(proxy_params, split_http, colorized)
+        obs_factory = setupTk(fwd_params, config_info, colorized)
 
     if split_http:
-        def _factory(pci, sub_factory=obs_factory):
-            return HTTPConnectionSplitter(sub_factory, pci)
+        def _factory(fci, sub_factory=obs_factory):
+            return HTTPConnectionSplitter(sub_factory, fci)
         obs_factory = _factory
     
     services = []
     try:
-        for params in proxy_params:
+        for params in fwd_params:
             args = params + (obs_factory,)
-            s = ProxyService(*args)
-            if show_config:
-                print 'Proxy %s:%d is forwarding to %s:%d' % params
+            s = ForwardingService(*args)
             services.append(s)
 
-        asyncore.loop(timeout=1.0)
+        if show_config:
+            print config_info
+
+        try:
+            asyncore.loop(timeout=1.0)
+        except KeyboardInterrupt:
+            print >> sys.stderr, 'tcpwatch finished.'
     finally:
         for s in services:
             s.close()