TorCtl.TorCtl
index
/data/users/mikeperry/code/SOAT/torflow-trunk-clean/TorCtl/TorCtl.py

Library to control Tor processes.
 
This library handles sending commands, parsing responses, and delivering
events to and from the control port. The basic usage is to create a
socket, wrap that in a TorCtl.Connection, and then add an EventHandler
to that connection. A simple example with a DebugEventHandler (that just
echoes the events back to stdout) is present in run_example().
 
Note that the TorCtl.Connection is fully compatible with the more
advanced EventHandlers in TorCtl.PathSupport (and of course any other
custom event handlers that you may extend off of those).
 
This package also contains a helper class for representing Routers, and
classes and constants for each event.

 
Modules
       
Queue
binascii
copy
datetime
os
re
socket
struct
sys
threading
time
traceback
types

 
Classes
       
Connection
Event
AddrMapEvent
BWEvent
BuildTimeoutSetEvent
CircuitEvent
LogEvent
NetworkStatusEvent
NewDescEvent
ORConnEvent
StreamBwEvent
StreamEvent
UnknownEvent
EventSink
EventHandler
ConsensusTracker
DebugEventHandler
EventListener
ExitPolicyLine
NetworkStatus
Router
RouterVersion
exceptions.Exception(exceptions.BaseException)
TorCtlError
ErrorReply
ProtocolError
TorCtlClosed

 
class AddrMapEvent(Event)
     Methods defined here:
__init__(self, event_name, from_addr, to_addr, when)

 
class BWEvent(Event)
     Methods defined here:
__init__(self, event_name, read, written)

 
class BuildTimeoutSetEvent(Event)
     Methods defined here:
__init__(self, event_name, set_type, total_times, timeout_ms, xm, alpha, quantile)

 
class CircuitEvent(Event)
     Methods defined here:
__init__(self, event_name, circ_id, status, path, purpose, reason, remote_reason)

 
class Connection
    Connection represents a connection to the Tor process via the 
control port.
 
  Methods defined here:
__init__(self, sock)
Create a Connection to communicate with the Tor process over the
socket 'sock'.
add_event_listener(self, listener)
attach_stream(self, streamid, circid, hop=None)
Attach a stream to a circuit, specify both by IDs. If hop is given, 
try to use the specified hop in the circuit as the exit node for 
this stream.
authenticate(self, secret='')
Sends an authenticating secret (password) to Tor.  You'll need to call 
this method (or authenticate_cookie) before Tor can start.
authenticate_cookie(self, cookie)
Sends an authentication cookie to Tor. This may either be a file or 
its contents.
close(self)
Shut down this controller connection
close_circuit(self, circid, reason=0, flags=())
DOCDOC
close_stream(self, streamid, reason=0, flags=())
DOCDOC
debug(self, f)
DOCDOC
extend_circuit(self, circid=None, hops=None)
Tell Tor to extend the circuit identified by 'circid' through the
servers named in the list 'hops'.
get_address_mappings(self, type='all')
get_info(self, name)
Return the value of the internal information field named 'name'.
Refer to section 3.9 of control-spec.txt for a list of valid names.
DOCDOC
get_network_status(self, who='all')
Get the entire network status list. Returns a list of
TorCtl.NetworkStatus instances.
get_option(self, 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.
Refer to section 3.3 of control-spec.txt for a list of valid names.
get_router(self, ns)
Fill in a Router class corresponding to a given NS class
is_live(self)
Returns true iff the connection is alive and healthy
launch_thread(self, daemon=1)
Launch a background thread to handle messages from the Tor process.
map_address(self, kvList)
Sends the MAPADDRESS command for each of the tuples in kvList
post_descriptor(self, desc)
read_routers(self, nslist)
Given a list a NetworkStatuses in 'nslist', this function will 
return a list of new Router instances.
redirect_stream(self, streamid, newaddr, newport='')
DOCDOC
reset_options(self, keylist)
Reset the options listed in 'keylist' to their default values.
 
Tor started implementing this command in version 0.1.1.7-alpha;
previous versions wanted you to set configuration keys to "".
That no longer works.
resolve(self, host)
Launch a remote hostname lookup request:
'host' may be a hostname or IPv4 address
save_conf(self)
Flush all configuration changes to disk.
sendAndRecv(self, msg='', expectedTypes=('250', '251'))
Helper: Send a command 'msg' to Tor, and wait for a command
in response.  If the response type is in expectedTypes,
return a list of (tp,body,extra) tuples.  If it is an
error, raise ErrorReply.  Otherwise, raise ProtocolError.
send_signal(self, sig)
Send the signal 'sig' to the Tor process; The allowed values for
'sig' are listed in section 3.6 of control-spec.
set_close_handler(self, handler)
Call 'handler' when the Tor process has closed its connection or
given us an exception.  If we close normally, no arguments are
provided; otherwise, it will be called with an exception as its
argument.
set_event_handler(self, handler)
Cause future events from the Tor process to be sent to 'handler'.
set_events(self, events, extended=False)
Change the list of events that the event handler is interested
in to those in 'events', which is a list of event names.
Recognized event names are listed in section 3.3 of the control-spec
set_option(self, key, value)
Set the value of the configuration option 'key' to the value 'value'.
set_options(self, kvlist)
Given a list of (key,value) pairs, set them as configuration
options.
set_periodic_timer(self, every_seconds, type=None)
set_timer(self, in_seconds, type=None)

 
class ConsensusTracker(EventHandler)
    ConsensusTracker is an EventHandler that tracks the current
consensus of Tor in self.ns_map, self.routers and self.sorted_r
 
 
Method resolution order:
ConsensusTracker
EventHandler
EventSink

Methods defined here:
__init__(self, c, RouterClass=<class TorCtl.TorCtl.Router at 0xa6a745cc>)
current_consensus(self)
new_consensus_event(self, n)
new_desc_event(self, d)
update_consensus(self)

Methods inherited from EventHandler:
add_event_listener(self, evlistener)
address_mapped_event(self, event)
Called when Tor adds a mapping for an address if listening
to ADDRESSMAPPED events.
bandwidth_event(self, event)
Called once a second if listening to BANDWIDTH events.
buildtimeout_set_event(self, event)
circ_status_event(self, event)
Called when a circuit status changes if listening to CIRCSTATUS
events.
guard_event(self, event)
heartbeat_event(self, event)
Called before any event is received. Convenience function
for any cleanup/setup/reconfiguration you may need to do.
msg_event(self, event)
Called when a log message of a given severity arrives if listening
to INFO_MSG, NOTICE_MSG, WARN_MSG, or ERR_MSG events.
ns_event(self, event)
or_conn_status_event(self, event)
Called when an OR connection's status changes if listening to
ORCONNSTATUS events.
stream_bw_event(self, event)
stream_status_event(self, event)
Called when a stream status changes if listening to STREAMSTATUS
events.
timer_event(self, event)
unknown_event(self, event)
Called when we get an event type we don't recognize.  This
is almost alwyas an error.

 
class DebugEventHandler(EventHandler)
    Trivial debug event handler: reassembles all parsed events to stdout.
 
 
Method resolution order:
DebugEventHandler
EventHandler
EventSink

Methods defined here:
bandwidth_event(self, bw_event)
circ_status_event(self, circ_event)
msg_event(self, log_event)
new_consensus_event(self, nc_event)
new_desc_event(self, newdesc_event)
ns_event(self, ns_event)
or_conn_status_event(self, orconn_event)
stream_status_event(self, strm_event)

Methods inherited from EventHandler:
__init__(self)
Create a new EventHandler.
add_event_listener(self, evlistener)
address_mapped_event(self, event)
Called when Tor adds a mapping for an address if listening
to ADDRESSMAPPED events.
buildtimeout_set_event(self, event)
guard_event(self, event)
heartbeat_event(self, event)
Called before any event is received. Convenience function
for any cleanup/setup/reconfiguration you may need to do.
stream_bw_event(self, event)
timer_event(self, event)
unknown_event(self, event)
Called when we get an event type we don't recognize.  This
is almost alwyas an error.

 
class ErrorReply(TorCtlError)
    Raised when Tor controller returns an error
 
 
Method resolution order:
ErrorReply
TorCtlError
exceptions.Exception
exceptions.BaseException
__builtin__.object

Data descriptors inherited from TorCtlError:
__weakref__
list of weak references to the object (if defined)

Methods inherited from exceptions.Exception:
__init__(...)
x.__init__(...) initializes x; see x.__class__.__doc__ for signature

Data and other attributes inherited from exceptions.Exception:
__new__ = <built-in method __new__ of type object at 0x813b120>
T.__new__(S, ...) -> a new object with type S, a subtype of T

Methods inherited from exceptions.BaseException:
__delattr__(...)
x.__delattr__('name') <==> del x.name
__getattribute__(...)
x.__getattribute__('name') <==> x.name
__getitem__(...)
x.__getitem__(y) <==> x[y]
__getslice__(...)
x.__getslice__(i, j) <==> x[i:j]
 
Use of negative indices is not supported.
__reduce__(...)
__repr__(...)
x.__repr__() <==> repr(x)
__setattr__(...)
x.__setattr__('name', value) <==> x.name = value
__setstate__(...)
__str__(...)
x.__str__() <==> str(x)

Data descriptors inherited from exceptions.BaseException:
__dict__
args
message
exception message

 
class EventHandler(EventSink)
    An 'EventHandler' wraps callbacks for the events Tor can return. 
Each event argument is an instance of the corresponding event
class.
 
  Methods defined here:
__init__(self)
Create a new EventHandler.
add_event_listener(self, evlistener)
address_mapped_event(self, event)
Called when Tor adds a mapping for an address if listening
to ADDRESSMAPPED events.
bandwidth_event(self, event)
Called once a second if listening to BANDWIDTH events.
buildtimeout_set_event(self, event)
circ_status_event(self, event)
Called when a circuit status changes if listening to CIRCSTATUS
events.
guard_event(self, event)
heartbeat_event(self, event)
Called before any event is received. Convenience function
for any cleanup/setup/reconfiguration you may need to do.
msg_event(self, event)
Called when a log message of a given severity arrives if listening
to INFO_MSG, NOTICE_MSG, WARN_MSG, or ERR_MSG events.
new_consensus_event(self, event)
new_desc_event(self, event)
Called when Tor learns a new server descriptor if listenting to
NEWDESC events.
ns_event(self, event)
or_conn_status_event(self, event)
Called when an OR connection's status changes if listening to
ORCONNSTATUS events.
stream_bw_event(self, event)
stream_status_event(self, event)
Called when a stream status changes if listening to STREAMSTATUS
events.
timer_event(self, event)
unknown_event(self, event)
Called when we get an event type we don't recognize.  This
is almost alwyas an error.

 
class EventListener(EventSink)
    An 'EventListener' is a passive sink for parsed Tor events. It 
implements the same interface as EventHandler, but it should
not alter Tor's behavior as a result of these events.
 
Do not extend from this class. Instead, extend from one of 
Pre, Post, or Dual event listener, to get events 
before, after, or before and after the EventHandler handles them.
 
  Methods defined here:
__init__(self)
Create a new EventHandler.
listen(self, event)
set_parent(self, parent_handler)

Methods inherited from EventSink:
address_mapped_event(self, event)
bandwidth_event(self, event)
buildtimeout_set_event(self, event)
circ_status_event(self, event)
guard_event(self, event)
heartbeat_event(self, event)
msg_event(self, event)
new_consensus_event(self, event)
new_desc_event(self, event)
ns_event(self, event)
or_conn_status_event(self, event)
stream_bw_event(self, event)
stream_status_event(self, event)
timer_event(self, event)
unknown_event(self, event)

 
class ExitPolicyLine
    Class to represent a line in a Router's exit policy in a way 
that can be easily checked.
 
  Methods defined here:
__init__(self, match, ip_mask, port_low, port_high)
__str__(self)
check(self, ip, port)
Check to see if an ip and port is matched by this line. 
Returns true if the line is an Accept, and False if it is a Reject.

 
class LogEvent(Event)
     Methods defined here:
__init__(self, level, msg)

 
class NetworkStatus
    Filled in during NS events
 
  Methods defined here:
__init__(self, nickname, idhash, orhash, updated, ip, orport, dirport, flags, bandwidth=None)

 
class NetworkStatusEvent(Event)
     Methods defined here:
__init__(self, event_name, nslist)

 
class NewDescEvent(Event)
     Methods defined here:
__init__(self, event_name, idlist)

 
class ORConnEvent(Event)
     Methods defined here:
__init__(self, event_name, status, endpoint, age, read_bytes, wrote_bytes, reason, ncircs)

 
class ProtocolError(TorCtlError)
    Raised on violations in Tor controller protocol
 
 
Method resolution order:
ProtocolError
TorCtlError
exceptions.Exception
exceptions.BaseException
__builtin__.object

Data descriptors inherited from TorCtlError:
__weakref__
list of weak references to the object (if defined)

Methods inherited from exceptions.Exception:
__init__(...)
x.__init__(...) initializes x; see x.__class__.__doc__ for signature

Data and other attributes inherited from exceptions.Exception:
__new__ = <built-in method __new__ of type object at 0x813b120>
T.__new__(S, ...) -> a new object with type S, a subtype of T

Methods inherited from exceptions.BaseException:
__delattr__(...)
x.__delattr__('name') <==> del x.name
__getattribute__(...)
x.__getattribute__('name') <==> x.name
__getitem__(...)
x.__getitem__(y) <==> x[y]
__getslice__(...)
x.__getslice__(i, j) <==> x[i:j]
 
Use of negative indices is not supported.
__reduce__(...)
__repr__(...)
x.__repr__() <==> repr(x)
__setattr__(...)
x.__setattr__('name', value) <==> x.name = value
__setstate__(...)
__str__(...)
x.__str__() <==> str(x)

Data descriptors inherited from exceptions.BaseException:
__dict__
args
message
exception message

 
class Router
    Class to represent a router from a descriptor. Can either be
created from the parsed fields, or can be built from a
descriptor+NetworkStatus
 
  Methods defined here:
__init__(self, *args)
__str__(self)
update_to(self, new)
Somewhat hackish method to update this router to be a copy of
'new'
will_exit_to(self, ip, port)
Check the entire exitpolicy to see if the router will allow
connections to 'ip':'port'

Data and other attributes defined here:
build_from_desc = <TorCtl.TorUtil.Callable instance at 0xa6a6f70c>

 
class RouterVersion
    Represents a Router's version. Overloads all comparison operators
to check for newer, older, or equivalent versions.
 
  Methods defined here:
__eq__(self, other)
__ge__(self, other)
__gt__(self, other)
__init__(self, version)
__le__(self, other)
__lt__(self, other)
__ne__(self, other)
__str__(self)

 
class StreamBwEvent(Event)
     Methods defined here:
__init__(self, event_name, strm_id, written, read)

 
class StreamEvent(Event)
     Methods defined here:
__init__(self, event_name, strm_id, status, circ_id, target_host, target_port, reason, remote_reason, source, source_addr, purpose)

 
class TorCtlClosed(TorCtlError)
    Raised when the controller connection is closed by Tor (not by us.)
 
 
Method resolution order:
TorCtlClosed
TorCtlError
exceptions.Exception
exceptions.BaseException
__builtin__.object

Data descriptors inherited from TorCtlError:
__weakref__
list of weak references to the object (if defined)

Methods inherited from exceptions.Exception:
__init__(...)
x.__init__(...) initializes x; see x.__class__.__doc__ for signature

Data and other attributes inherited from exceptions.Exception:
__new__ = <built-in method __new__ of type object at 0x813b120>
T.__new__(S, ...) -> a new object with type S, a subtype of T

Methods inherited from exceptions.BaseException:
__delattr__(...)
x.__delattr__('name') <==> del x.name
__getattribute__(...)
x.__getattribute__('name') <==> x.name
__getitem__(...)
x.__getitem__(y) <==> x[y]
__getslice__(...)
x.__getslice__(i, j) <==> x[i:j]
 
Use of negative indices is not supported.
__reduce__(...)
__repr__(...)
x.__repr__() <==> repr(x)
__setattr__(...)
x.__setattr__('name', value) <==> x.name = value
__setstate__(...)
__str__(...)
x.__str__() <==> str(x)

Data descriptors inherited from exceptions.BaseException:
__dict__
args
message
exception message

 
class TorCtlError(exceptions.Exception)
    Generic error raised by TorControl code.
 
 
Method resolution order:
TorCtlError
exceptions.Exception
exceptions.BaseException
__builtin__.object

Data descriptors defined here:
__weakref__
list of weak references to the object (if defined)

Methods inherited from exceptions.Exception:
__init__(...)
x.__init__(...) initializes x; see x.__class__.__doc__ for signature

Data and other attributes inherited from exceptions.Exception:
__new__ = <built-in method __new__ of type object at 0x813b120>
T.__new__(S, ...) -> a new object with type S, a subtype of T

Methods inherited from exceptions.BaseException:
__delattr__(...)
x.__delattr__('name') <==> del x.name
__getattribute__(...)
x.__getattribute__('name') <==> x.name
__getitem__(...)
x.__getitem__(y) <==> x[y]
__getslice__(...)
x.__getslice__(i, j) <==> x[i:j]
 
Use of negative indices is not supported.
__reduce__(...)
__repr__(...)
x.__repr__() <==> repr(x)
__setattr__(...)
x.__setattr__('name', value) <==> x.name = value
__setstate__(...)
__str__(...)
x.__str__() <==> str(x)

Data descriptors inherited from exceptions.BaseException:
__dict__
args
message
exception message

 
class UnknownEvent(Event)
     Methods defined here:
__init__(self, event_name, event_string)

 
Functions
       
parse_ns_body(data)
Parse the body of an NS event or command into a list of
NetworkStatus instances

 
Data
        EVENT_STATE = <TorCtl.TorUtil.Enum2 instance at 0xa6a6336c>
EVENT_TYPE = <TorCtl.TorUtil.Enum2 instance at 0xa6a63c0c>
__all__ = ['EVENT_TYPE', 'TorCtlError', 'TorCtlClosed', 'ProtocolError', 'ErrorReply', 'NetworkStatus', 'ExitPolicyLine', 'Router', 'RouterVersion', 'Connection', 'parse_ns_body', 'EventHandler', 'DebugEventHandler', 'NetworkStatusEvent', 'NewDescEvent', 'CircuitEvent', 'StreamEvent', 'ORConnEvent', 'StreamBwEvent', 'LogEvent', ...]