TorCtl.PathSupport
index
/crypto/home/potentiate/output/code/tor/SVN/torctl/python/TorCtl/PathSupport.py

Support classes for path construction
 
The PathSupport package builds on top of TorCtl.TorCtl. It provides a
number of interfaces that make path construction easier.
 
The inheritance diagram for event handling is as follows:
TorCtl.EventHandler <- PathBuilder <- CircuitHandler <- StreamHandler.
 
Basically, EventHandler is what gets all the control port events
packaged in nice clean classes (see help(TorCtl) for information on
those). 
 
PathBuilder inherits from EventHandler and is what builds all circuits
based on the requirements specified in the SelectionManager instance
passed to its constructor. It also handles attaching streams to
circuits. It only handles one building one circuit at a time.
 
CircuitHandler optionally inherits from PathBuilder, and overrides its
circuit event handling to manage building a pool of circuits as opposed
to just one. It still uses the SelectionManager for path selection.
 
StreamHandler inherits from CircuitHandler, and is what governs the
attachment of an incoming stream on to one of the multiple circuits of
the circuit handler. 
 
The SelectionManager is essentially a configuration wrapper around the
most elegant portions of TorFlow: NodeGenerators, NodeRestrictions, and
PathRestrictions. In the SelectionManager, a NodeGenerator is used to
choose the nodes probabilistically according to some distribution while
obeying the NodeRestrictions. These generators (one per hop) are handed
off to the PathSelector, which uses the generators to build a complete
path that satisfies the PathRestriction requirements.
 
Have a look at the class hierarchy directly below to get a feel for how
the restrictions fit together, and what options are available.

 
Modules
       
Queue
TorCtl.TorCtl
TorCtl.TorUtil
copy
random
re
socket
struct
time

 
Classes
       
NodeGenerator
BwWeightedGenerator
OrderedExitGenerator
UniformGenerator
NodeRestriction
ConserveExitsRestriction
CountryCodeRestriction
CountryRestriction
ExitPolicyRestriction
FlagsRestriction
IdHexRestriction
MetaNodeRestriction
AtLeastNNodeRestriction
NotNodeRestriction
OrNodeRestriction
MinBWRestriction
NickRestriction
OSRestriction
PercentileRestriction
VersionExcludeRestriction
VersionIncludeRestriction
NodeRestrictionList
PathRestriction
ContinentJumperRestriction
ContinentRestriction
SingleCountryRestriction
Subnet16Restriction
UniqueContinentRestriction
UniqueCountryRestriction
UniqueRestriction
PathRestrictionList
PathSelector
SelectionManager
TorCtl.TorCtl.Connection
Connection
TorCtl.TorCtl.EventHandler
PathBuilder
CircuitHandler
StreamHandler

 
class AtLeastNNodeRestriction(MetaNodeRestriction)
    MetaNodeRestriction that is true if at least n member 
restrictions are true.
 
 
Method resolution order:
AtLeastNNodeRestriction
MetaNodeRestriction
NodeRestriction

Methods defined here:
__init__(self, rstrs, n)
r_is_ok(self, r)

Methods inherited from MetaNodeRestriction:
del_restriction(self, RestrictionClass)
next_rstr(self)
# TODO: these should collapse the restriction and return a new
# instance for re-insertion (or None)

 
class BwWeightedGenerator(NodeGenerator)
    This is a generator designed to match the Tor Path Selection
algorithm.  It will generate nodes weighted by their bandwidth,
but take the appropriate weighting into account against guard
nodes and exit nodes when they are chosen for positions other
than guard/exit. For background see:
routerlist.c::smartlist_choose_by_bandwidth(),
http://archives.seul.org/or/dev/Jul-2007/msg00021.html,
http://archives.seul.org/or/dev/Jul-2007/msg00056.html, and
https://tor-svn.freehaven.net/svn/tor/trunk/doc/spec/path-spec.txt
The formulas used are from the first or-dev link, but are proven
optimal and equivalent to the ones now used in routerlist.c in the 
second or-dev link.
 
  Methods defined here:
__init__(self, sorted_r, rstr_list, pathlen, exit=False, guard=False)
Pass exit=True to create a generator for exit-nodes
generate(self)
rewind(self)

Methods inherited from NodeGenerator:
all_chosen(self)
Return true if all the routers have been marked as chosen
mark_chosen(self, r)
Mark a router as chosen: remove it from the list of routers 
that can be returned in the future
reset_restriction(self, rstr_list)
Reset the restriction list to a new list

 
class CircuitHandler(PathBuilder)
    CircuitHandler that extends from PathBuilder to handle multiple
circuits as opposed to just one.
 
 
Method resolution order:
CircuitHandler
PathBuilder
TorCtl.TorCtl.EventHandler

Methods defined here:
__init__(self, c, selmgr, num_circuits, RouterClass)
Constructor. 'c' is a Connection, 'selmgr' is a SelectionManager,
'num_circuits' is the number of circuits to keep in the pool,
and 'RouterClass' is a class that inherits from Router and is used
to create annotated Routers.
build_circuit(self, host, port)
Build a circuit
check_circuit_pool(self)
Init or check the status of the circuit-pool
circ_status_event(self, c)
Handle circuit status events
close_circuit(self, id)
Close a circuit with given id

Methods inherited from PathBuilder:
attach_stream_any(self, stream, badcircs)
Attach a stream to a valid circuit, avoiding any in 'badcircs'
bandwidth_event(self, b)
build_path(self)
Get a path from the SelectionManager's PathSelector, can be used 
e.g. for generating paths without actually creating any circuits
heartbeat_event(self, event)
This function handles dispatching scheduled jobs. If you 
extend PathBuilder and want to implement this function for 
some reason, be sure to call the parent class
new_desc_event(self, d)
ns_event(self, n)
read_routers(self, nslist)
schedule_immediate(self, job)
Schedules an immediate job to be run before the next event is
processed.
schedule_low_prio(self, job)
Schedules a job to be run when a non-time critical event arrives.
schedule_selmgr(self, job)
Schedules an immediate job to be run before the next event is
processed. Also notifies the selection manager that it needs
to update itself.
stream_bw_event(self, s)
stream_status_event(self, s)

Methods inherited from TorCtl.TorCtl.EventHandler:
address_mapped_event(self, event)
Called when Tor adds a mapping for an address if listening
to ADDRESSMAPPED events.
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.
or_conn_status_event(self, event)
Called when an OR connection's status changes if listening to
ORCONNSTATUS events.
unknown_event(self, event)
Called when we get an event type we don't recognize.  This
is almost alwyas an error.

 
class Connection(TorCtl.TorCtl.Connection)
    Extended Connection class that provides a method for building circuits
 
  Methods defined here:
__init__(self, sock)
build_circuit(self, pathlen, path_sel)
Tell Tor to build a circuit chosen by the PathSelector 'path_sel'

Methods inherited from TorCtl.TorCtl.Connection:
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='')
Send an authenticating secret to Tor.  You'll need to call this
method before Tor can start.
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, hops)
Tell Tor to extend the circuit identified by 'circid' through the
servers named in the list 'hops'.
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
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.

 
class ConserveExitsRestriction(NodeRestriction)
    Restriction to reject exits from selection
 
  Methods defined here:
r_is_ok(self, r)
# XXX: Make this adaptive by ip/port

 
class ContinentJumperRestriction(PathRestriction)
    Ensure continent crossings between all hops
 
  Methods defined here:
path_is_ok(self, path)

 
class ContinentRestriction(PathRestriction)
    Do not more than n continent crossings
 
  Methods defined here:
__init__(self, n, src=None, dest=None)
# TODO: Add src and dest
path_is_ok(self, path)

 
class CountryCodeRestriction(NodeRestriction)
    Ensure that the country_code is set
 
  Methods defined here:
r_is_ok(self, r)

 
class CountryRestriction(NodeRestriction)
    Only accept nodes that are in 'country_code'
 
  Methods defined here:
__init__(self, country_code)
r_is_ok(self, r)

 
class ExitPolicyRestriction(NodeRestriction)
    Require that a router exit to an ip+port
 
  Methods defined here:
__init__(self, to_ip, to_port)
r_is_ok(self, r)

 
class FlagsRestriction(NodeRestriction)
    Restriction for mandatory and forbidden router flags
 
  Methods defined here:
__init__(self, mandatory, forbidden=[])
Constructor. 'mandatory' and 'forbidden' are both lists of router 
flags as strings.
r_is_ok(self, router)

 
class IdHexRestriction(NodeRestriction)
    Require that the node idhash is as specified
 
  Methods defined here:
__init__(self, idhex)
r_is_ok(self, router)

 
class MetaNodeRestriction(NodeRestriction)
    Interface for a NodeRestriction that is an expression consisting of 
multiple other NodeRestrictions
 
  Methods defined here:
del_restriction(self, RestrictionClass)
next_rstr(self)
# TODO: these should collapse the restriction and return a new
# instance for re-insertion (or None)

Methods inherited from NodeRestriction:
r_is_ok(self, r)
Returns true if Router 'r' is acceptable for this restriction

 
class MinBWRestriction(NodeRestriction)
    Require a minimum bandwidth
 
  Methods defined here:
__init__(self, minbw)
r_is_ok(self, router)

 
class NickRestriction(NodeRestriction)
    Require that the node nickname is as specified
 
  Methods defined here:
__init__(self, nickname)
r_is_ok(self, router)

 
class NodeGenerator
    Interface for node generation
 
  Methods defined here:
__init__(self, sorted_r, rstr_list)
Constructor. Takes a bandwidth-sorted list of Routers 'sorted_r' 
and a NodeRestrictionList 'rstr_list'
all_chosen(self)
Return true if all the routers have been marked as chosen
generate(self)
Return a python generator that yields routers according to the policy
mark_chosen(self, r)
Mark a router as chosen: remove it from the list of routers 
that can be returned in the future
reset_restriction(self, rstr_list)
Reset the restriction list to a new list
rewind(self)
Rewind the generator to the 'beginning'

 
class NodeRestriction
    Interface for node restriction policies
 
  Methods defined here:
r_is_ok(self, r)
Returns true if Router 'r' is acceptable for this restriction

 
class NodeRestrictionList
    Class to manage a list of NodeRestrictions
 
  Methods defined here:
__init__(self, restrictions)
Constructor. 'restrictions' is a list of NodeRestriction instances
add_restriction(self, restr)
Add a NodeRestriction 'restr' to the list of restrictions
del_restriction(self, RestrictionClass)
Remove all restrictions of type RestrictionClass from the list.
Does NOT inspect or collapse MetaNode Restrictions (though 
MetaRestrictions can be removed if RestrictionClass is 
MetaNodeRestriction)
r_is_ok(self, r)
Returns true of Router 'r' passes all of the contained restrictions

 
class NotNodeRestriction(MetaNodeRestriction)
    Negates a single restriction
 
 
Method resolution order:
NotNodeRestriction
MetaNodeRestriction
NodeRestriction

Methods defined here:
__init__(self, a)
r_is_ok(self, r)

Methods inherited from MetaNodeRestriction:
del_restriction(self, RestrictionClass)
next_rstr(self)
# TODO: these should collapse the restriction and return a new
# instance for re-insertion (or None)

 
class OSRestriction(NodeRestriction)
    Restriction based on operating system
 
  Methods defined here:
__init__(self, ok, bad=[])
Constructor. Accept router OSes that match regexes in 'ok', 
rejects those that match regexes in 'bad'.
r_is_ok(self, r)
Returns true if r is in 'ok', false if 'r' is in 'bad'. If 'ok'

 
class OrNodeRestriction(MetaNodeRestriction)
    MetaNodeRestriction that is the boolean or of two or more
NodeRestrictions
 
 
Method resolution order:
OrNodeRestriction
MetaNodeRestriction
NodeRestriction

Methods defined here:
__init__(self, rs)
Constructor. 'rs' is a list of NodeRestrictions
r_is_ok(self, r)
Returns true if one of 'rs' is true for this router

Methods inherited from MetaNodeRestriction:
del_restriction(self, RestrictionClass)
next_rstr(self)
# TODO: these should collapse the restriction and return a new
# instance for re-insertion (or None)

 
class OrderedExitGenerator(NodeGenerator)
    NodeGenerator that produces exits in an ordered fashion for a 
specific port
 
  Methods defined here:
__init__(self, to_port, sorted_r, rstr_list)
all_chosen(self)
generate(self)
mark_chosen(self, r)
rewind(self)
set_port(self, port)

Methods inherited from NodeGenerator:
reset_restriction(self, rstr_list)
Reset the restriction list to a new list

 
class PathBuilder(TorCtl.TorCtl.EventHandler)
    PathBuilder implementation. Handles circuit construction, subject
to the constraints of the SelectionManager selmgr.
 
Do not access this object from other threads. Instead, use the 
schedule_* functions to schedule work to be done in the thread
of the EventHandler.
 
  Methods defined here:
__init__(self, c, selmgr, RouterClass)
Constructor. 'c' is a Connection, 'selmgr' is a SelectionManager,
and 'RouterClass' is a class that inherits from Router and is used
to create annotated Routers.
attach_stream_any(self, stream, badcircs)
Attach a stream to a valid circuit, avoiding any in 'badcircs'
bandwidth_event(self, b)
build_path(self)
Get a path from the SelectionManager's PathSelector, can be used 
e.g. for generating paths without actually creating any circuits
circ_status_event(self, c)
heartbeat_event(self, event)
This function handles dispatching scheduled jobs. If you 
extend PathBuilder and want to implement this function for 
some reason, be sure to call the parent class
new_desc_event(self, d)
ns_event(self, n)
read_routers(self, nslist)
schedule_immediate(self, job)
Schedules an immediate job to be run before the next event is
processed.
schedule_low_prio(self, job)
Schedules a job to be run when a non-time critical event arrives.
schedule_selmgr(self, job)
Schedules an immediate job to be run before the next event is
processed. Also notifies the selection manager that it needs
to update itself.
stream_bw_event(self, s)
stream_status_event(self, s)

Methods inherited from TorCtl.TorCtl.EventHandler:
address_mapped_event(self, event)
Called when Tor adds a mapping for an address if listening
to ADDRESSMAPPED events.
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.
or_conn_status_event(self, event)
Called when an OR connection's status changes if listening to
ORCONNSTATUS events.
unknown_event(self, event)
Called when we get an event type we don't recognize.  This
is almost alwyas an error.

 
class PathRestriction
    Interface for path restriction policies
 
  Methods defined here:
path_is_ok(self, path)
Return true if the list of Routers in path satisfies this restriction

 
class PathRestrictionList
    Class to manage a list of PathRestrictions
 
  Methods defined here:
__init__(self, restrictions)
Constructor. 'restrictions' is a list of PathRestriction instances
add_restriction(self, rstr)
Add a PathRestriction 'rstr' to the list
del_restriction(self, RestrictionClass)
Remove all PathRestrictions of type RestrictionClass from the list.
path_is_ok(self, path)
Given list if Routers in 'path', check it against each restriction.

 
class PathSelector
    Implementation of path selection policies. Builds a path according
to entry, middle, and exit generators that satisfies the path 
restrictions.
 
  Methods defined here:
__init__(self, entry_gen, mid_gen, exit_gen, path_restrict)
Constructor. The first three arguments are NodeGenerators with 
their appropriate restrictions. The 'path_restrict' is a
PathRestrictionList
build_path(self, pathlen)
Creates a path of 'pathlen' hops, and returns it as a list of
Router instances

 
class PercentileRestriction(NodeRestriction)
    Restriction to cut out a percentile slice of the network.
 
  Methods defined here:
__init__(self, pct_skip, pct_fast, r_list)
Constructor. Sets up the restriction such that routers in the 
'pct_skip' to 'pct_fast' percentile of bandwidth rankings are 
returned from the sorted list 'r_list'
r_is_ok(self, r)
Returns true if r is in the percentile boundaries (by rank)

 
class SelectionManager
    Helper class to handle configuration updates
 
The methods are NOT threadsafe. They may ONLY be called from
EventHandler's thread. This means that to update the selection 
manager, you must schedule a config update job using 
PathBuilder.schedule_selmgr() with a worker function to modify 
this object.
 
  Methods defined here:
__init__(self, pathlen, order_exits, percent_fast, percent_skip, min_bw, use_all_exits, uniform, use_exit, use_guards, geoip_config=None, restrict_guards=False)
reconfigure(self, sorted_r)
This function is called after a configuration change, 
to rebuild the RestrictionLists.
set_target(self, ip, port)
Called to update the ExitPolicyRestrictions with a new ip and port

 
class SingleCountryRestriction(PathRestriction)
    Ensure every router to have the same country_code
 
  Methods defined here:
path_is_ok(self, path)

 
class StreamHandler(CircuitHandler)
    StreamHandler that extends from the CircuitHandler 
to handle attaching streams to an appropriate circuit 
in the pool.
 
 
Method resolution order:
StreamHandler
CircuitHandler
PathBuilder
TorCtl.TorCtl.EventHandler

Methods defined here:
__init__(self, c, selmgr, num_circs, RouterClass)
address_mapped_event(self, event)
It is necessary to listen to ADDRMAP events to be able to 
perform DNS lookups using Tor
attach_stream_any(self, stream, badcircs)
Attach a regular user stream
clear_dns_cache(self)
Send signal CLEARDNSCACHE
close_stream(self, id, reason)
Close a stream with given id and reason
create_and_attach(self, stream, unattached_streams)
Create a new circuit and attach (stream + unattached_streams)
stream_status_event(self, s)
Catch user stream events
unknown_event(self, event)

Methods inherited from CircuitHandler:
build_circuit(self, host, port)
Build a circuit
check_circuit_pool(self)
Init or check the status of the circuit-pool
circ_status_event(self, c)
Handle circuit status events
close_circuit(self, id)
Close a circuit with given id

Methods inherited from PathBuilder:
bandwidth_event(self, b)
build_path(self)
Get a path from the SelectionManager's PathSelector, can be used 
e.g. for generating paths without actually creating any circuits
heartbeat_event(self, event)
This function handles dispatching scheduled jobs. If you 
extend PathBuilder and want to implement this function for 
some reason, be sure to call the parent class
new_desc_event(self, d)
ns_event(self, n)
read_routers(self, nslist)
schedule_immediate(self, job)
Schedules an immediate job to be run before the next event is
processed.
schedule_low_prio(self, job)
Schedules a job to be run when a non-time critical event arrives.
schedule_selmgr(self, job)
Schedules an immediate job to be run before the next event is
processed. Also notifies the selection manager that it needs
to update itself.
stream_bw_event(self, s)

Methods inherited from TorCtl.TorCtl.EventHandler:
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.
or_conn_status_event(self, event)
Called when an OR connection's status changes if listening to
ORCONNSTATUS events.

 
class Subnet16Restriction(PathRestriction)
    PathRestriction that mandates that no two nodes from the same 
/16 subnet be in the path
 
  Methods defined here:
path_is_ok(self, path)

 
class UniformGenerator(NodeGenerator)
    NodeGenerator that produces nodes in the uniform distribution
 
  Methods defined here:
generate(self)

Methods inherited from NodeGenerator:
__init__(self, sorted_r, rstr_list)
Constructor. Takes a bandwidth-sorted list of Routers 'sorted_r' 
and a NodeRestrictionList 'rstr_list'
all_chosen(self)
Return true if all the routers have been marked as chosen
mark_chosen(self, r)
Mark a router as chosen: remove it from the list of routers 
that can be returned in the future
reset_restriction(self, rstr_list)
Reset the restriction list to a new list
rewind(self)
Rewind the generator to the 'beginning'

 
class UniqueContinentRestriction(PathRestriction)
    Ensure every hop to be on a different continent
 
  Methods defined here:
path_is_ok(self, path)

 
class UniqueCountryRestriction(PathRestriction)
    Ensure every router to have a distinct country_code
 
  Methods defined here:
path_is_ok(self, path)

 
class UniqueRestriction(PathRestriction)
    Path restriction that mandates that the same router can't appear more
than once in a path
 
  Methods defined here:
path_is_ok(self, path)

 
class VersionExcludeRestriction(NodeRestriction)
    Require that the version not match one in the list
 
  Methods defined here:
__init__(self, exclude)
Constructor. 'exclude' is a list of versions as strings
r_is_ok(self, router)
Returns false if the version of 'router' matches one of the 
specified versions.

 
class VersionIncludeRestriction(NodeRestriction)
    Require that the version match one in the list
 
  Methods defined here:
__init__(self, eq)
Constructor. 'eq' is a list of versions as strings
r_is_ok(self, router)
Returns true if the version of 'router' matches one of the 
specified versions.

 
Data
        __all__ = ['NodeRestrictionList', 'PathRestrictionList', 'PercentileRestriction', 'OSRestriction', 'ConserveExitsRestriction', 'FlagsRestriction', 'MinBWRestriction', 'VersionIncludeRestriction', 'VersionExcludeRestriction', 'ExitPolicyRestriction', 'NodeRestriction', 'PathRestriction', 'OrNodeRestriction', 'MetaNodeRestriction', 'AtLeastNNodeRestriction', 'NotNodeRestriction', 'Subnet16Restriction', 'UniqueRestriction', 'NodeGenerator', 'UniformGenerator', ...]