[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

[or-cvs] Tweak python control lib interface: make names consistant, ...



Update of /home/or/cvsroot/control/python
In directory moria:/tmp/cvs-serv8213/python

Modified Files:
	TorCtl.py TorCtl0.py TorCtl1.py TorExample.py 
Log Message:
Tweak python control lib interface: make names consistant, make thread launch automatic

Index: TorCtl.py
===================================================================
RCS file: /home/or/cvsroot/control/python/TorCtl.py,v
retrieving revision 1.4
retrieving revision 1.5
diff -u -d -r1.4 -r1.5
--- TorCtl.py	24 Jun 2005 18:03:27 -0000	1.4
+++ TorCtl.py	11 Jul 2005 19:16:40 -0000	1.5
@@ -28,28 +28,28 @@
         """Create a new EventHandler."""
         from TorCtl0 import EVENT_TYPE
         self._map0 = {
-            EVENT_TYPE.CIRCSTATUS : self.circStatus,
-            EVENT_TYPE.STREAMSTATUS : self.streamStatus,
-            EVENT_TYPE.ORCONNSTATUS : self.orConnStatus,
+            EVENT_TYPE.CIRCSTATUS : self.circ_status,
+            EVENT_TYPE.STREAMSTATUS : self.stream_status,
+            EVENT_TYPE.ORCONNSTATUS : self.or_conn_status,
             EVENT_TYPE.BANDWIDTH : self.bandwidth,
-            EVENT_TYPE.NEWDESC : self.newDesc,
+            EVENT_TYPE.NEWDESC : self.new_desc,
             EVENT_TYPE.INFO_MSG : self.msg,
             EVENT_TYPE.NOTICE_MSG : self.msg,
             EVENT_TYPE.WARN_MSG : self.msg,
             EVENT_TYPE.ERR_MSG : self.msg,
             }
         self._map1 = {
-            "CIRC" : self.circStatus,
-            "STREAM" : self.streamStatus,
-            "ORCONN" : self.orConnStatus,
+            "CIRC" : self.circ_status,
+            "STREAM" : self.stream_status,
+            "ORCONN" : self.or_conn_status,
             "BW" : self.bandwidth,
             "DEBUG" : self.msg,
             "INFO" : self.msg,
             "NOTICE" : self.msg,
             "WARN" : self.msg,
             "ERR" : self.msg,
-            "NEWDESC" : self.newDesc,
-            "ADDRMAP" : self.addressMapped
+            "NEWDESC" : self.new_desc,
+            "ADDRMAP" : self.address_mapped
             },
 
     def handle0(self, evbody):
@@ -158,7 +158,7 @@
 
         return evtype, args
 
-    def circStatus(self, status, circID, path):
+    def circ_status(self, status, circID, path):
         """Called when a circuit status changes if listening to CIRCSTATUS
            events.  'status' is a member of CIRC_STATUS; circID is a numeric
            circuit ID, and 'path' is the circuit's path so far as a list of
@@ -166,14 +166,14 @@
         """
         raise NotImplemented
 
-    def streamStatus(self, status, streamID, target, circID="0"):
+    def stream_status(self, status, streamID, target, circID="0"):
         """Called when a stream status changes if listening to STREAMSTATUS
            events.  'status' is a member of STREAM_STATUS; streamID is a
            numeric stream ID, and 'target' is the destination of the stream.
         """
         raise NotImplemented
 
-    def orConnStatus(self, status, target):
+    def or_conn_status(self, status, target):
         """Called when an OR connection's status changes if listening to
            ORCONNSTATUS events. 'status' is a member of OR_CONN_STATUS; target
            is the OR in question.
@@ -186,7 +186,7 @@
         """
         raise NotImplemented
 
-    def newDesc(self, identities):
+    def new_desc(self, identities):
         """Called when Tor learns a new server descriptor if listenting to
            NEWDESC events.
         """
@@ -197,8 +197,10 @@
            to INFO_MSG, NOTICE_MSG, WARN_MSG, or ERR_MSG events."""
         raise NotImplemented
 
-    def addressMapped(self, fromAddr, toAddr, expiry=None):
-        """DOCDOC"""
+    def address_mapped(self, fromAddr, toAddr, expiry=None):
+        """Called when Tor adds a mapping for an address if listening
+           to ADDRESSMAPPED events.
+        """
         raise NotImplemented
 
 class DebugEventHandler(EventHandler):
@@ -217,6 +219,9 @@
             print >>self._out, msg
 
 def detectVersion(s):
+    """Helper: sends a trial command to Tor to tell whether it's running
+       the first or second version of the control protocol.
+    """
     s.sendall("\x00\x00\r\n")
     m = s.recv(4)
     v0len, v0type = struct.unpack("!HH", m)
@@ -252,6 +257,8 @@
     return host, port
 
 def get_connection(sock):
+    """Given a socket attached to a Tor control port, detect the version of Tor
+       and return an appropriate 'Connection' object."""
     v = detectVersion(sock)
     if v == 0:
         import TorCtl0
@@ -261,6 +268,7 @@
         return TorCtl1.Connection(sock)
 
 def secret_to_key(secret, s2k_specifier):
+    """Used to generate a hashed password string. DOCDOC."""
     c = ord(s2k_specifier[8])
     EXPBIAS = 6
     count = (16+(c&15)) << ((c>>4) + EXPBIAS)
@@ -278,6 +286,7 @@
     return d.digest()
 
 def urandom_rng(n):
+    """Try to read some entropy from the platform entropy source."""
     f = open('/dev/urandom', 'rb')
     try:
         return f.read(n)
@@ -285,11 +294,13 @@
         f.close()
 
 def s2k_gen(secret, rng):
+    """DOCDOC"""
     spec = "%s%s"%(rng(8), chr(96))
     return "16:%s"%(
         binascii.b2a_hex(spec + secret_to_key(secret, spec)))
 
 def s2k_check(secret, k):
+    """DOCDOC"""
     assert k[:3] == "16:"
 
     k =  binascii.a2b_hex(k[3:])
@@ -300,7 +311,7 @@
     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     s.connect((host,port))
     c = Connection(s)
-    c.setEventHandler(DebugEventHandler())
+    c.set_event_handler(DebugEventHandler())
     th = c.launchThread()
     c.authenticate()
     print "nick",`c.get_option("nickname")`

Index: TorCtl0.py
===================================================================
RCS file: /home/or/cvsroot/control/python/TorCtl0.py,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -d -r1.2 -r1.3
--- TorCtl0.py	24 Jun 2005 18:03:27 -0000	1.2
+++ TorCtl0.py	11 Jul 2005 19:16:40 -0000	1.3
@@ -277,12 +277,12 @@
         self._queue = Queue.Queue()
         self._thread = None
 
-    def setEventHandler(self, handler):
+    def set_event_handler(self, handler):
         """Cause future events from the Tor process to be sent to 'handler'.
         """
         self._handler = handler
 
-    def launchThread(self, daemon=1):
+    def launch_thread(self, daemon=1):
         """Launch a background thread to handle messages from the Tor process."""
         assert self._thread is None
         t = threading.Thread(target=self._loop)
@@ -320,6 +320,8 @@
            in expectedTypes, return a (tp,body) tuple.  If it is an error,
            raise ErrorReply.  Otherwise, raise ProtocolError.
         """
+        if self._thread is None:
+            self.launch_thread(1)
         # This condition will get notified when we've got a result...
         condition = threading.Condition()
         # Here's where the result goes...
@@ -374,13 +376,16 @@
             self._sendLock.release()
 
     def authenticate(self, secret=""):
-        """Send an authenticating secret to Tor.  You'll need to call this
-           method before Tor can start.
+        """Send an authenticating secret to Tor.  You'll need to call
+           this method before other commands.  You need to use a
+           password if Tor expects one.
         """
         self._sendAndRecv(MSG_TYPE.AUTH,secret)
 
     def get_option(self,name):
-        """Return the value of the configuration option named 'name'.
+        """Get the value of the configuration option named 'name'.  To
+           retrieve multiple values, pass a list for 'name' instead of
+           a string.  Returns a list of (key,value) pairs.
         """
         if not isinstance(name, str):
             name = "".join(["%s\n"%s for s in name])
@@ -388,7 +393,8 @@
         return _parseKV(body)
 
     def set_option(self,key,value):
-        """Set the value of the configuration option 'key' to the value 'value'.
+        """Set the value of the configuration option 'key' to the
+           value 'value'.
         """
         self.set_options([key, value])
 
@@ -400,7 +406,10 @@
         self._sendAndRecv(MSG_TYPE.SETCONF,msg)
 
     def get_info(self,name):
-        """Return the value of the internal information field named 'named'.
+        """Return the value of the internal information field named
+           'name'.  To retrieve multiple values, pass a list for
+           'name' instead of a string.  Returns a dictionary of
+           key->value mappings.
         """
         if not isinstance(name, str):
             name = "".join(["%s\n"%s for s in name])
@@ -414,8 +423,14 @@
     def set_events(self,events):
         """Change the list of events that the event handler is interested
            in to those in 'events', which is a list of EVENT_TYPE members
-           or corresponding strings.
+           or their corresponding strings.
         """
+        evs = []
+        for ev in events:
+            if isinstance(ev, types.StringType):
+                evs.append(getattr(EVENT_TYPE, ev.upper()))
+            else:
+                evs.append(ev)
         self._sendAndRecv(MSG_TYPE.SETEVENTS,
                      "".join([struct.pack("!H", event) for event in events]))
 
@@ -426,7 +441,7 @@
 
     def send_signal(self, sig):
         """Send the signal 'sig' to the Tor process; 'sig' must be a member of
-           SIGNAL.
+           SIGNAL or a corresponding string.
         """
         try:
             sig = sig.upper()
@@ -453,7 +468,7 @@
         """Tell Tor to extend the circuit identified by 'circid' through the
            servers named in the list "hops".
         """
-        msg = struct.pack("!L",circid) + ",".join(hops) + "\0"
+        msg = struct.pack("!L",long(circid)) + ",".join(hops) + "\0"
         tp, body = self._sendAndRecv(MSG_TYPE.EXTENDCIRCUIT,msg)
         if len(body) != 4:
             raise ProtocolError("Extendcircuit reply too short or long")
@@ -462,17 +477,17 @@
     def redirect_stream(self, streamid, newtarget):
         """Tell Tor to change the target address of the stream identified by
            'streamid' from its old value to 'newtarget'."""
-        msg = struct.pack("!L",streamid) + newtarget + "\0"
+        msg = struct.pack("!L",long(streamid)) + newtarget + "\0"
         self._sendAndRecv(MSG_TYPE.REDIRECTSTREAM,msg)
 
     def attach_stream(self, streamid, circid):
         """Tell Tor To attach stream 'streamid' to circuit 'circid'."""
-        msg = struct.pack("!LL",streamid, circid)
+        msg = struct.pack("!LL",long(streamid), long(circid))
         self._sendAndRecv(MSG_TYPE.ATTACHSTREAM,msg)
 
     def close_stream(self, streamid, reason=0, flags=()):
         """Close the stream 'streamid'. """
-        msg = struct.pack("!LBB",streamid,reason,flags)
+        msg = struct.pack("!LBB",long(streamid),reason,flags)
         self._sendAndRecv(MSG_TYPE.CLOSESTREAM,msg)
 
     def close_circuit(self, circid, flags=()):
@@ -481,7 +496,7 @@
             flags=1
         else:
             flags=0
-        msg = struct.pack("!LB",circid,flags)
+        msg = struct.pack("!LB",long(circid),flags)
         self._sendAndRecv(MSG_TYPE.CLOSECIRCUIT,msg)
 
     def post_descriptor(self, descriptor):

Index: TorCtl1.py
===================================================================
RCS file: /home/or/cvsroot/control/python/TorCtl1.py,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -d -r1.2 -r1.3
--- TorCtl1.py	24 Jun 2005 18:03:27 -0000	1.2
+++ TorCtl1.py	11 Jul 2005 19:16:40 -0000	1.3
@@ -94,12 +94,12 @@
         """DOCDOC"""
         self._debugFile = f
 
-    def setEventHandler(self, handler):
+    def set_event_handler(self, handler):
         """Cause future events from the Tor process to be sent to 'handler'.
         """
         self._handler = handler
 
-    def launchThread(self, daemon=1):
+    def launch_thread(self, daemon=1):
         """Launch a background thread to handle messages from the Tor process."""
         assert self._thread is None
         t = threading.Thread(target=self._loop)
@@ -142,6 +142,8 @@
            return a list of (tp,body,extra) tuples.  If it is an
            error, raise ErrorReply.  Otherwise, raise TorCtl.ProtocolError.
         """
+        if self._thread is None:
+            self.launch_thread(1)
         # This condition will get notified when we've got a result...
         condition = threading.Condition()
         # Here's where the result goes...

Index: TorExample.py
===================================================================
RCS file: /home/or/cvsroot/control/python/TorExample.py,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -d -r1.3 -r1.4
--- TorExample.py	24 Jun 2005 18:03:27 -0000	1.3
+++ TorExample.py	11 Jul 2005 19:16:40 -0000	1.4
@@ -27,7 +27,7 @@
     conn = get_connection(s)
     if verbose and hasattr(conn, "debug"):
         conn.debug(sys.stdout)
-    th = conn.launchThread(daemon)
+    th = conn.launch_thread(daemon)
     conn.authenticate("")
     return conn