Stem Docs

Controller

Controller

Classes for interacting with the tor control socket.

Controllers are a wrapper around a ControlSocket, retaining many of its methods (connect, close, is_alive, etc) in addition to providing its own for interacting at a higher level.

Module Overview:

Controller - General controller class intended for direct use
  | |- from_port - Provides a Controller based on a port connection.
  | +- from_socket_file - Provides a Controller based on a socket file connection.
  |
  |- authenticate - authenticates this controller with tor
  |
  |- get_info - issues a GETINFO query for a parameter
  |- get_version - provides our tor version
  |- get_exit_policy - provides our exit policy
  |- get_socks_listeners - provides where tor is listening for SOCKS connections
  |- get_protocolinfo - information about the controller interface
  |- get_user - provides the user tor is running as
  |- get_pid - provides the pid of our tor process
  |
  |- get_microdescriptor - querying the microdescriptor for a relay
  |- get_microdescriptors - provides all presently available microdescriptors
  |- get_server_descriptor - querying the server descriptor for a relay
  |- get_server_descriptors - provides all presently available server descriptors
  |- get_network_status - querying the router status entry for a relay
  |- get_network_statuses - provides all preently available router status entries
  |
  |- get_conf - gets the value of a configuration option
  |- get_conf_map - gets the values of multiple configuration options
  |- set_conf - sets the value of a configuration option
  |- reset_conf - reverts configuration options to their default values
  |- set_options - sets or resets the values of multiple configuration options
  |
  |- add_event_listener - attaches an event listener to be notified of tor events
  |- remove_event_listener - removes a listener so it isn't notified of further events
  |
  |- is_caching_enabled - true if the controller has enabled caching
  |- set_caching - enables or disables caching
  |- clear_cache - clears any cached results
  |
  |- load_conf - loads configuration information as if it was in the torrc
  |- save_conf - saves configuration information to the torrc
  |
  |- is_feature_enabled - checks if a given controller feature is enabled
  |- enable_feature - enables a controller feature that has been disabled by default
  |
  |- get_circuit - provides an active circuit
  |- get_circuits - provides a list of active circuits
  |- new_circuit - create new circuits
  |- extend_circuit - create new circuits and extend existing ones
  |- repurpose_circuit - change a circuit's purpose
  |- close_circuit - close a circuit
  |
  |- get_streams - provides a list of active streams
  |- attach_stream - attach a stream to a circuit
  |- close_stream - close a stream
  |
  |- signal - sends a signal to the tor client
  |- is_geoip_unavailable - true if we've discovered our geoip db to be unavailable
  +- map_address - maps one address to another such that connections to the original are replaced with the other

BaseController - Base controller class asynchronous message handling
  |- msg - communicates with the tor process
  |- is_alive - reports if our connection to tor is open or closed
  |- is_authenticated - checks if we're authenticated to tor
  |- connect - connects or reconnects to tor
  |- close - shuts down our connection to the tor process
  |- get_socket - provides the socket used for control communication
  |- get_latest_heartbeat - timestamp for when we last heard from tor
  |- add_status_listener - notifies a callback of changes in our status
  |- remove_status_listener - prevents further notification of status changes
  +- __enter__ / __exit__ - manages socket connection
stem.control.State(enum)

Enumeration for states that a controller can have.

State Description
INIT new control connection
RESET received a reset/sighup signal
CLOSED control connection closed
stem.control.EventType(enum)

Known types of events that the add_event_listener() method of the Controller can listen for.

The most frequently listened for event types tend to be the logging events (DEBUG, INFO, NOTICE, WARN, and ERR), bandwidth usage (BW), and circuit or stream changes (CIRC and STREAM).

Enums are mapped to Event subclasses as follows...

EventType Event Class
ADDRMAP stem.response.events.AddrMapEvent
AUTHDIR_NEWDESCS stem.response.events.AuthDirNewDescEvent
BUILDTIMEOUT_SET stem.response.events.BuildTimeoutSetEvent
BW stem.response.events.BandwidthEvent
CIRC stem.response.events.CircuitEvent
CIRC_MINOR stem.response.events.CircMinorEvent
CLIENTS_SEEN stem.response.events.ClientsSeenEvent
CONF_CHANGED stem.response.events.ConfChangedEvent
DEBUG stem.response.events.LogEvent
DESCCHANGED stem.response.events.DescChangedEvent
ERR stem.response.events.LogEvent
GUARD stem.response.events.GuardEvent
INFO stem.response.events.LogEvent
NEWCONSENSUS stem.response.events.NewConsensusEvent
NEWDESC stem.response.events.NewDescEvent
NOTICE stem.response.events.LogEvent
NS stem.response.events.NetworkStatusEvent
ORCONN stem.response.events.ORConnEvent
SIGNAL stem.response.events.SignalEvent
STATUS_CLIENT stem.response.events.StatusEvent
STATUS_GENERAL stem.response.events.StatusEvent
STATUS_SERVER stem.response.events.StatusEvent
STREAM stem.response.events.StreamEvent
STREAM_BW stem.response.events.StreamBwEvent
WARN stem.response.events.LogEvent
class stem.control.BaseController(control_socket)[source]

Bases: object

Controller for the tor process. This is a minimal base class for other controllers, providing basic process communication and event listing. Don’t use this directly - subclasses like the Controller provide higher level functionality.

It’s highly suggested that you don’t interact directly with the ControlSocket that we’re constructed from - use our wrapper methods instead.

msg(message)[source]

Sends a message to our control socket and provides back its reply.

Parameters:

message (str) – message to be formatted and sent to tor

Returns:

ControlMessage with the response

Raises :
is_alive()[source]

Checks if our socket is currently connected. This is a pass-through for our socket’s is_alive() method.

Returns:bool that’s True if our socket is connected and False otherwise
is_authenticated()[source]

Checks if our socket is both connected and authenticated.

Returns:bool that’s True if our socket is authenticated to tor and False otherwise
connect()[source]

Reconnects our control socket. This is a pass-through for our socket’s connect() method.

Raises :stem.SocketError if unable to make a socket
close()[source]

Closes our socket connection. This is a pass-through for our socket’s close() method.

get_socket()[source]

Provides the socket used to speak with the tor process. Communicating with the socket directly isn’t advised since it may confuse this controller.

Returns:ControlSocket we’re communicating with
get_latest_heartbeat()[source]

Provides the unix timestamp for when we last heard from tor. This is zero if we’ve never received a message.

Returns:float for the unix timestamp of when we last heard from tor
add_status_listener(callback, spawn=True)[source]

Notifies a given function when the state of our socket changes. Functions are expected to be of the form...

my_function(controller, state, timestamp)

The state is a value from the stem.control.State enum. Functions must allow for new values. The timestamp is a float for the unix time when the change occurred.

This class only provides State.INIT and State.CLOSED notifications. Subclasses may provide others.

If spawn is True then the callback is notified via a new daemon thread. If False then the notice is under our locks, within the thread where the change occurred. In general this isn’t advised, especially if your callback could block for a while.

Parameters:
  • callback (function) – function to be notified when our state changes
  • spawn (bool) – calls function via a new thread if True, otherwise it’s part of the connect/close method call
remove_status_listener(callback)[source]

Stops listener from being notified of further events.

Parameters:callback (function) – function to be removed from our listeners
Returns:bool that’s True if we removed one or more occurrences of the callback, False otherwise
class stem.control.Controller(control_socket)[source]

Bases: stem.control.BaseController

Communicates with a control socket. This is built on top of the BaseController and provides a more user friendly API for library users.

static from_port(address='127.0.0.1', port=9051)[source]

Constructs a ControlPort based Controller.

Parameters:
  • address (str) – ip address of the controller
  • port (int) – port number of the controller
Returns:

Controller attached to the given port

Raises :

stem.SocketError if we’re unable to establish a connection

static from_socket_file(path='/var/run/tor/control')[source]

Constructs a ControlSocketFile based Controller.

Parameters:path (str) – path where the control socket is located
Returns:Controller attached to the given socket file
Raises :stem.SocketError if we’re unable to establish a connection
connect()[source]
close()[source]
authenticate(*args, **kwargs)[source]

A convenience method to authenticate the controller. This is just a pass-through to stem.connection.authenticate().

get_info(params, default='<Undefined_ >', get_bytes=False)[source]

Queries the control socket for the given GETINFO option. If provided a default then that’s returned if the GETINFO option is undefined or the call fails for any reason (error response, control port closed, initiated, etc).

Parameters:
  • params (str,list) – GETINFO option or options to be queried
  • default (object) – response if the query fails
  • get_bytes (bool) – provides bytes values rather than a str under python 3.x
Returns:

Response depends upon how we were called as follows...

  • str with the response if our param was a str
  • dict with the ‘param => response’ mapping if our param was a list
  • default if one was provided and our call failed

Raises :
get_version(default='<Undefined_ >')[source]

A convenience method to get tor version that current controller is connected to.

Parameters:

default (object) – response if the query fails

Returns:

Version of the tor instance that we’re connected to

Raises :

An exception is only raised if we weren’t provided a default response.

get_exit_policy(default='<Undefined_ >')[source]

Effective ExitPolicy for our relay. This accounts for ExitPolicyRejectPrivate and default policies.

Parameters:

default (object) – response if the query fails

Returns:

ExitPolicy of the tor instance that we’re connected to

Raises :

An exception is only raised if we weren’t provided a default response.

get_socks_listeners(default='<Undefined_ >')[source]

Provides the SOCKS (address, port) tuples that tor has open.

Parameters:default (object) – response if the query fails
Returns:list of (address, port) tuples for the available SOCKS listeners
Raises :stem.ControllerError if unable to determine the listeners and no default was provided
get_protocolinfo(default='<Undefined_ >')[source]

A convenience method to get the protocol info of the controller.

Parameters:

default (object) – response if the query fails

Returns:

ProtocolInfoResponse provided by tor

Raises :

An exception is only raised if we weren’t provided a default response.

get_user(default='<Undefined_ >')[source]

Provides the user tor is running as. This often only works if tor is running locally. Also, most of its checks are platform dependent, and hence are not entirely reliable.

Parameters:default (object) – response if the query fails
Returns:str with the username tor is running as
get_pid(default='<Undefined_ >')[source]

Provides the process id of tor. This often only works if tor is running locally. Also, most of its checks are platform dependent, and hence are not entirely reliable.

Parameters:default (object) – response if the query fails
Returns:int with our process’ pid
Raises :ValueError if unable to determine the pid and no default was provided
get_microdescriptor(relay, default='<Undefined_ >')[source]

Provides the microdescriptor for the relay with the given fingerprint or nickname. If the relay identifier could be either a fingerprint or nickname then it’s queried as a fingerprint.

Parameters:
  • relay (str) – fingerprint or nickname of the relay to be queried
  • default (object) – response if the query fails
Returns:

Microdescriptor for the given relay

Raises :
  • stem.ControllerError if unable to query the descriptor
  • ValueError if relay doesn’t conform with the pattern for being a fingerprint or nickname

An exception is only raised if we weren’t provided a default response.

get_microdescriptors(default='<Undefined_ >')[source]

Provides an iterator for all of the microdescriptors that tor presently knows about.

Tor does not expose this information via the control protocol (ticket 8323). Until it does this reads the microdescriptors from disk, and hence won’t work remotely or if we lack read permissions.

Parameters:default (list) – items to provide if the query fails
Returns:iterates over Microdescriptor for relays in the tor network
Raises :stem.ControllerError if unable to query tor and no default was provided
get_server_descriptor(relay, default='<Undefined_ >')[source]

Provides the server descriptor for the relay with the given fingerprint or nickname. If the relay identifier could be either a fingerprint or nickname then it’s queried as a fingerprint.

As of Tor version 0.2.3.25 relays no longer get server descriptors by default. It’s advised that you use microdescriptors instead, but if you really need server descriptors then you can get them by setting ‘UseMicrodescriptors 0’.

Parameters:
  • relay (str) – fingerprint or nickname of the relay to be queried
  • default (object) – response if the query fails
Returns:

RelayDescriptor for the given relay

Raises :
  • stem.ControllerError if unable to query the descriptor
  • ValueError if relay doesn’t conform with the pattern for being a fingerprint or nickname

An exception is only raised if we weren’t provided a default response.

get_server_descriptors(default='<Undefined_ >')[source]

Provides an iterator for all of the server descriptors that tor presently knows about.

As of Tor version 0.2.3.25 relays no longer get server descriptors by default. It’s advised that you use microdescriptors instead, but if you really need server descriptors then you can get them by setting ‘UseMicrodescriptors 0’.

Parameters:default (list) – items to provide if the query fails
Returns:iterates over RelayDescriptor for relays in the tor network
Raises :stem.ControllerError if unable to query tor and no default was provided
get_network_status(relay, default='<Undefined_ >')[source]

Provides the router status entry for the relay with the given fingerprint or nickname. If the relay identifier could be either a fingerprint or nickname then it’s queried as a fingerprint.

Parameters:
  • relay (str) – fingerprint or nickname of the relay to be queried
  • default (object) – response if the query fails
Returns:

RouterStatusEntryV3 for the given relay

Raises :
  • stem.ControllerError if unable to query the descriptor
  • ValueError if relay doesn’t conform with the pattern for being a fingerprint or nickname

An exception is only raised if we weren’t provided a default response.

get_network_statuses(default='<Undefined_ >')[source]

Provides an iterator for all of the router status entries that tor presently knows about.

Parameters:default (list) – items to provide if the query fails
Returns:iterates over RouterStatusEntryV3 for relays in the tor network
Raises :stem.ControllerError if unable to query tor and no default was provided
get_conf(param, default='<Undefined_ >', multiple=False)[source]

Queries the current value for a configuration option. Some configuration options (like the ExitPolicy) can have multiple values. This provides a list with all of the values if multiple is True. Otherwise this will be a str with the first value.

If provided with a default then that is provided if the configuration option was unset or the query fails (invalid configuration option, error response, control port closed, initiated, etc).

If the configuration value is unset and no default was given then this provides None if multiple was False and an empty list if it was True.

Parameters:
  • param (str) – configuration option to be queried
  • default (object) – response if the option is unset or the query fails
  • multiple (bool) – if True then provides a list with all of the present values (this is an empty list if the config option is unset)
Returns:

Response depends upon how we were called as follows...

  • str with the configuration value if multiple was False, None if it was unset
  • list with the response strings if multiple was True
  • default if one was provided and the configuration option was either unset or our call failed

Raises :
get_conf_map(params, default='<Undefined_ >', multiple=True)[source]

Similar to get_conf() but queries multiple configuration options, providing back a mapping of those options to their values.

There are three use cases for GETCONF:

  1. a single value is provided (e.g. ControlPort)
  2. multiple values are provided for the option (e.g. ExitPolicy)
  3. a set of options that weren’t necessarily requested are returned (for instance querying HiddenServiceOptions gives HiddenServiceDir, HiddenServicePort, etc)

The vast majority of the options fall into the first two categories, in which case calling get_conf() is sufficient. However, for batch queries or the special options that give a set of values this provides back the full response. As of tor version 0.2.1.25 HiddenServiceOptions was the only option that falls into the third category.

Parameters:
  • params (str,list) – configuration option(s) to be queried
  • default (object) – value for the mappings if the configuration option is either undefined or the query fails
  • multiple (bool) – if True then the values provided are lists with all of the present values
Returns:

dict of the ‘config key => value’ mappings. The value is a...

  • str if multiple is False, None if the configuration option is unset
  • list if multiple is True
  • the default if it was set and the value was either undefined or our lookup failed

Raises :
set_conf(param, value)[source]

Changes the value of a tor configuration option. Our value can be any of the following...

  • a string to set a single value
  • a list of strings to set a series of values (for instance the ExitPolicy)
  • None to either set the value to 0/NULL
Parameters:
  • param (str) – configuration option to be set
  • value (str,list) – value to set the parameter to
Raises :
reset_conf(*params)[source]

Reverts one or more parameters to their default values.

Parameters:

params (str) – configuration option to be reset

Raises :
set_options(params, reset=False)[source]

Changes multiple tor configuration options via either a SETCONF or RESETCONF query. Both behave identically unless our value is None, in which case SETCONF sets the value to 0 or NULL, and RESETCONF returns it to its default value. This accepts str, list, or None values in a similar fashion to set_conf(). For example...

my_controller.set_options({
  "Nickname": "caerSidi",
  "ExitPolicy": ["accept *:80", "accept *:443", "reject *:*"],
  "ContactInfo": "caerSidi-exit@someplace.com",
  "Log": None,
})

The params can optionally be a list of key/value tuples, though the only reason this type of argument would be useful is for hidden service configuration (those options are order dependent).

Parameters:
  • params (dict,list) – mapping of configuration options to the values we’re setting it to
  • reset (bool) – issues a RESETCONF, returning None values to their defaults if True
Raises :
add_event_listener(listener, *events)[source]

Directs further tor controller events to a given function. The function is expected to take a single argument, which is a Event subclass. For instance the following would print the bytes sent and received by tor over five seconds...

import time
from stem.control import Controller, EventType

def print_bw(event):
  print "sent: %i, received: %i" % (event.written, event.read)

with Controller.from_port(port = 9051) as controller:
  controller.authenticate()
  controller.add_event_listener(print_bw, EventType.BW)
  time.sleep(5)

If a new control connection is initialized then this listener will be reattached.

Parameters:
  • listener (functor) – function to be called when an event is received
  • events (stem.control.EventType) – event types to be listened for
Raises :

stem.ProtocolError if unable to set the events

remove_event_listener(listener)[source]

Stops a listener from being notified of further tor events.

Parameters:listener (stem.control.EventListener) – listener to be removed
Raises :stem.ProtocolError if unable to set the events
is_caching_enabled()[source]

True if caching has been enabled, False otherwise.

Returns:bool to indicate if caching is enabled
set_caching(enabled)[source]

Enables or disables caching of information retrieved from tor.

Parameters:enabled (bool) – True to enable caching, False to disable it
clear_cache()[source]

Drops any cached results.

load_conf(configtext)[source]

Sends the configuration text to Tor and loads it as if it has been read from the torrc.

Parameters:configtext (str) – the configuration text
Raises :stem.ControllerError if the call fails
save_conf()[source]

Saves the current configuration options into the active torrc file.

Raises :
is_feature_enabled(feature)[source]

Checks if a control connection feature is enabled. These features can be enabled using enable_feature().

Parameters:feature (str) – feature to be checked
Returns:True if feature is enabled, False otherwise
enable_feature(features)[source]

Enables features that are disabled by default to maintain backward compatibility. Once enabled, a feature cannot be disabled and a new control connection must be opened to get a connection with the feature disabled. Feature names are case-insensitive.

The following features are currently accepted:

  • EXTENDED_EVENTS - Requests the extended event syntax
  • VERBOSE_NAMES - Replaces ServerID with LongName in events and GETINFO results
Parameters:

features (str,list) – a single feature or a list of features to be enabled

Raises :
get_circuit(circuit_id, default='<Undefined_ >')[source]

Provides a circuit presently available from tor.

Parameters:
  • circuit_id (int) – circuit to be fetched
  • default (object) – response if the query fails
Returns:

stem.response.events.CircuitEvent for the given circuit

Raises :

An exception is only raised if we weren’t provided a default response.

get_circuits(default='<Undefined_ >')[source]

Provides tor’s currently available circuits.

Parameters:default (object) – response if the query fails
Returns:list of stem.response.events.CircuitEvent for our circuits
Raises :stem.ControllerError if the call fails and no default was provided
new_circuit(path=None, purpose='general', await_build=False)[source]

Requests a new circuit. If the path isn’t provided, one is automatically selected.

Parameters:
  • path (list,str) – one or more relays to make a circuit through
  • purpose (str) – “general” or “controller”
  • await_build (bool) – blocks until the circuit is built if True
Returns:

str of the circuit id of the newly created circuit

Raises :

stem.ControllerError if the call fails

extend_circuit(circuit_id='0', path=None, purpose='general', await_build=False)[source]

Either requests the creation of a new circuit or extends an existing one.

When called with a circuit value of zero (the default) a new circuit is created, and when non-zero the circuit with that id is extended. If the path isn’t provided, one is automatically selected.

A python interpreter session used to create circuits could look like this...

>>> control.extend_circuit('0', ["718BCEA286B531757ACAFF93AE04910EA73DE617", "30BAB8EE7606CBD12F3CC269AE976E0153E7A58D", "2765D8A8C4BBA3F89585A9FFE0E8575615880BEB"])
19
>>> control.extend_circuit('0')
20
>>> print control.get_info('circuit-status')
20 EXTENDED $718BCEA286B531757ACAFF93AE04910EA73DE617=KsmoinOK,$649F2D0ACF418F7CFC6539AB2257EB2D5297BAFA=Eskimo BUILD_FLAGS=NEED_CAPACITY PURPOSE=GENERAL TIME_CREATED=2012-12-06T13:51:11.433755
19 BUILT $718BCEA286B531757ACAFF93AE04910EA73DE617=KsmoinOK,$30BAB8EE7606CBD12F3CC269AE976E0153E7A58D=Pascal1,$2765D8A8C4BBA3F89585A9FFE0E8575615880BEB=Anthracite PURPOSE=GENERAL TIME_CREATED=2012-12-06T13:50:56.969938
Parameters:
  • circuit_id (str) – id of a circuit to be extended
  • path (list,str) – one or more relays to make a circuit through, this is required if the circuit id is non-zero
  • purpose (str) – “general” or “controller”
  • await_build (bool) – blocks until the circuit is built if True
Returns:

str of the circuit id of the created or extended circuit

Raises :
repurpose_circuit(circuit_id, purpose)[source]
Changes a circuit’s purpose. Currently, two purposes are recognized...
  • general
  • controller
Parameters:
  • circuit_id (str) – id of the circuit whose purpose is to be changed
  • purpose (str) – purpose (either “general” or “controller”)
Raises :

stem.InvalidArguments if the circuit doesn’t exist or if the purpose was invalid

close_circuit(circuit_id, flag='')[source]

Closes the specified circuit.

Parameters:
  • circuit_id (str) – id of the circuit to be closed
  • flag (str) – optional value to modify closing, the only flag available is “IfUnused” which will not close the circuit unless it is unused
Raises :

stem.InvalidArguments if the circuit is unknown

Raises :

stem.InvalidRequest if not enough information is provided

get_streams(default='<Undefined_ >')[source]

Provides the list of streams tor is currently handling.

Parameters:default (object) – response if the query fails
Returns:list of stem.response.events.StreamEvent objects
Raises :stem.ControllerError if the call fails and no default was provided
attach_stream(stream_id, circuit_id, exiting_hop=None)[source]

Attaches a stream to a circuit.

Note: Tor attaches streams to circuits automatically unless the __LeaveStreamsUnattached configuration variable is set to “1”

Parameters:
  • stream_id (str) – id of the stream that must be attached
  • circuit_id (str) – id of the circuit to which it must be attached
  • exiting_hop (int) – hop in the circuit where traffic should exit
Raises :
close_stream(stream_id, reason='MISC', flag='')[source]

Closes the specified stream.

Parameters:
  • stream_id (str) – id of the stream to be closed
  • reason (stem.RelayEndReason) – reason the stream is closing
  • flag (str) – not currently used
Raises :

stem.InvalidArguments if the stream or reason are not recognized

Raises :

stem.InvalidRequest if the stream and/or reason are missing

signal(signal)[source]

Sends a signal to the Tor client.

Parameters:signal (stem.Signal) – type of signal to be sent
Raises :stem.InvalidArguments if signal provided wasn’t recognized
is_geoip_unavailable()[source]

Provides True if we’ve concluded hat our geoip database is unavailable, False otherwise. This is determined by having our ‘GETINFO ip-to-country/*’ lookups fail so this will default to False if we aren’t making those queries.

Geoip failures will be untracked if caching is disabled.

Returns:bool to indicate if we’ve concluded our geoip database to be unavailable or not
map_address(mapping)[source]

Map addresses to replacement addresses. Tor replaces subseqent connections to the original addresses with the replacement addresses.

If the original address is a null address, i.e., one of “0.0.0.0”, ”::0”, or ”.” Tor picks an original address itself and returns it in the reply. If the original address is already mapped to a different address the mapping is removed.

Parameters:

mapping (dict) – mapping of original addresses to replacement addresses

Raises :
Returns:

dict with ‘original -> replacement’ address mappings

Exceptions and Attribute Enums

Library for working with the tor process.

Module Overview:

ControllerError - Base exception raised when using the controller.
  |- ProtocolError - Malformed socket data.
  |- OperationFailed - Tor was unable to successfully complete the operation.
  |  |- UnsatisfiableRequest - Tor was unable to satisfy a valid request.
  |  |  +- CircuitExtensionFailed - Attempt to make or extend a circuit failed.
  |  +- InvalidRequest - Invalid request.
  |     +- InvalidArguments - Invalid request parameters.
  +- SocketError - Communication with the socket failed.
     +- SocketClosed - Socket has been shut down.
stem.Runlevel(enum)

Rating of importance used for event logging.

Runlevel Description
ERR critical issues that impair tor’s ability to function
WARN non-critical issues the user should be aware of
NOTICE information that may be helpful to the user
INFO high level runtime information
DEBUG low level runtime information
stem.Signal(enum)

Signals that the tor process will accept.

Signal Description
RELOAD or HUP reloads our torrc
SHUTDOWN or INT shut down, waiting ShutdownWaitLength first if we’re a relay
DUMP or USR1 dumps information about open connections and circuits to our log
DEBUG or USR2 switch our logging to the DEBUG runlevel
HALT or TERM exit tor immediately
NEWNYM switch to new circuits, so new application requests don’t share any circuits with old ones (this also clears our DNS cache)
CLEARDNSCACHE clears cached DNS results
stem.Flag(enum)

Flag assigned to tor relays by the authorities to indicate various characteristics.

Flag Description
AUTHORITY relay is a directory authority
BADEXIT relay shouldn’t be used as an exit due to being either problematic or malicious (wiki)
BADDIRECTORY relay shouldn’t be used for directory information
EXIT relay’s exit policy makes it more useful as an exit rather than middle hop
FAST relay’s suitable for high-bandwidth circuits
GUARD relay’s suitable for being an entry guard (first hop)
HSDIR relay is being used as a v2 hidden service directory
NAMED relay can be referred to by its nickname
RUNNING relay is currently usable
STABLE relay’s suitable for long-lived circuits
UNNAMED relay isn’t presently bound to a nickname
V2DIR relay supports the v2 directory protocol
VALID relay has been validated
stem.CircStatus(enum)

Statuses that a circuit can be in. Tor may provide statuses not in this enum.

CircStatus Description
LAUNCHED new circuit was created
BUILT circuit finished being created and can accept traffic
EXTENDED circuit has been extended by a hop
FAILED circuit construction failed
CLOSED circuit has been closed
stem.CircBuildFlag(enum)

Attributes about how a circuit is built. These were introduced in tor version 0.2.3.11. Tor may provide flags not in this enum.

CircBuildFlag Description
ONEHOP_TUNNEL single hop circuit to fetch directory information
IS_INTERNAL circuit that won’t be used for client traffic
NEED_CAPACITY circuit only includes high capacity relays
NEED_UPTIME circuit only includes relays with a high uptime
stem.CircPurpose(enum)

Description of what a circuit is intended for. These were introduced in tor version 0.2.1.6. Tor may provide purposes not in this enum.

CircPurpose Description
GENERAL client traffic or fetching directory information
HS_CLIENT_INTRO client side introduction point for a hidden service circuit
HS_CLIENT_REND client side hidden service rendezvous circuit
HS_SERVICE_INTRO server side introduction point for a hidden service circuit
HS_SERVICE_REND server side hidden service rendezvous circuit
TESTING testing to see if we’re reachable, so we can be used as a relay
CONTROLLER circuit that was built by a controller
MEASURE_TIMEOUT circuit being kept around to see how long it takes
stem.CircClosureReason(enum)

Reason that a circuit is being closed or failed to be established. Tor may provide reasons not in this enum.

CircClosureReason Description
NONE no reason given
TORPROTOCOL violation in the tor protocol
INTERNAL internal error
REQUESTED requested by the client via a TRUNCATE command
HIBERNATING relay is presently hibernating
RESOURCELIMIT relay is out of memory, sockets, or circuit IDs
CONNECTFAILED unable to contact the relay
OR_IDENTITY relay had the wrong OR identification
OR_CONN_CLOSED connection failed after being established
FINISHED circuit has expired (see tor’s MaxCircuitDirtiness config option)
TIMEOUT circuit construction timed out
DESTROYED circuit unexpectedly closed
NOPATH not enough relays to make a circuit
NOSUCHSERVICE requested hidden service does not exist
MEASUREMENT_EXPIRED same as TIMEOUT except that it was left open for measurement purposes
stem.CircEvent(enum)

Type of change reflected in a circuit by a CIRC_MINOR event. Tor may provide event types not in this enum.

CircEvent Description
PURPOSE_CHANGED circuit purpose or hidden service state has changed
CANNIBALIZED circuit connections are being reused for a different circuit
stem.HiddenServiceState(enum)

State that a hidden service circuit can have. These were introduced in tor version 0.2.3.11. Tor may provide states not in this enum.

Enumerations fall into four groups based on their prefix...

Prefix Description
HSCI_* client-side introduction-point
HSCR_* client-side rendezvous-point
HSSI_* service-side introduction-point
HSSR_* service-side rendezvous-point
HiddenServiceState Description
HSCI_CONNECTING connecting to the introductory point
HSCI_INTRO_SENT sent INTRODUCE1 and awaiting a reply
HSCI_DONE received a reply, circuit is closing
HSCR_CONNECTING connecting to the introductory point
HSCR_ESTABLISHED_IDLE rendezvous-point established, awaiting an introduction
HSCR_ESTABLISHED_WAITING introduction received, awaiting a rend
HSCR_JOINED connected to the hidden service
HSSI_CONNECTING connecting to the introductory point
HSSI_ESTABLISHED established introductory point
HSSR_CONNECTING connecting to the introductory point
HSSR_JOINED connected to the rendezvous-point
stem.RelayEndReason(enum)

Reasons why the stream is to be closed.

RelayEndReason Description
MISC none of the following reasons
RESOLVEFAILED unable to resolve the hostname
CONNECTREFUSED remote host refused the connection
EXITPOLICY OR refuses to connect to the destination
DESTROY circuit is being shut down
DONE connection has been closed
TIMEOUT connection timed out
NOROUTE routing error while contacting the destination
HIBERNATING relay is temporarily hibernating
INTERNAL internal error at the relay
RESOURCELIMIT relay has insufficient resources to service the request
CONNRESET connection was unexpectedly reset
TORPROTOCOL violation in the tor protocol
NOTDIRECTORY directory information requested from a relay that isn’t mirroring it
stem.StreamStatus(enum)

State that a stream going through tor can have. Tor may provide states not in this enum.

StreamStatus Description
NEW request for a new connection
NEWRESOLVE request to resolve an address
REMAP address is being re-mapped to another
SENTCONNECT sent a connect cell along a circuit
SENTRESOLVE sent a resolve cell along a circuit
SUCCEEDED stream has been established
FAILED stream is detached, and won’t be re-established
DETACHED stream is detached, but might be re-established
CLOSED stream has closed
stem.StreamClosureReason(enum)

Reason that a stream is being closed or failed to be established. This includes all values in the RelayEndReason enumeration as well as the following. Tor may provide reasons not in this enum.

StreamClosureReason Description
END endpoint has sent a RELAY_END cell
PRIVATE_ADDR endpoint was a private address (127.0.0.1, 10.0.0.1, etc)
stem.StreamSource(enum)

Cause of a stream being remapped to another address. Tor may provide sources not in this enum.

StreamSource Description
CACHE tor is remapping because of a cached answer
EXIT exit relay requested the remap
stem.StreamPurpose(enum)

Purpsoe of the stream. This is only provided with new streams and tor may provide purposes not in this enum.

StreamPurpose Description
DIR_FETCH fetching directory information (descriptors, consensus, etc)
DIR_UPLOAD uploading our descriptor to an authority
DNS_REQUEST user initiated DNS request
DIRPORT_TEST checking that our directory port is reachable externally
USER either relaying user traffic or not one of the above categories
stem.ORStatus(enum)

State that an OR connection can have. Tor may provide states not in this enum.

ORStatus Description
NEW received OR connection, starting server-side handshake
LAUNCHED launched outbound OR connection, starting client-side handshake
CONNECTED OR connection has been established
FAILED attempt to establish OR connection failed
CLOSED OR connection has been closed
stem.ORClosureReason(enum)

Reason that an OR connection is being closed or failed to be established. Tor may provide reasons not in this enum.

ORClosureReason Description
DONE OR connection shut down cleanly
CONNECTREFUSED got a ECONNREFUSED when connecting to the relay
IDENTITY identity of the relay wasn’t what we expected
CONNECTRESET got a ECONNRESET or similar error from relay
TIMEOUT got a ETIMEOUT or similar error from relay
NOROUTE got a ENOTCONN, ENETUNREACH, ENETDOWN, EHOSTUNREACH, or similar error from relay
IOERROR got a different kind of error from relay
RESOURCELIMIT relay has insufficient resources to service the request
MISC connection refused for another reason
stem.AuthDescriptorAction(enum)

Actions that directory authorities might take with relay descriptors. Tor may provide reasons not in this enum.

AuthDescriptorAction Description
ACCEPTED accepting the descriptor as the newest version
DROPPED descriptor rejected without notifying the relay
REJECTED relay notified that its descriptor has been rejected
stem.StatusType(enum)

Sources for tor status events. Tor may provide types not in this enum.

StatusType Description
GENERAL general tor activity, not specifically as a client or relay
CLIENT related to our activity as a tor client
SERVER related to our activity as a tor relay
stem.GuardType(enum)

Use a guard relay can be for. Tor may provide types not in this enum.

GuardType Description
ENTRY used to connect to the tor network
stem.GuardStatus(enum)

Status a guard relay can have. Tor may provide types not in this enum.

GuardStatus Description
NEW new guard that we weren’t previously using
DROPPED removed from use as one of our guards
UP guard is now reachable
DOWN guard is now unreachable
BAD consensus or relay considers this relay to be unusable as a guard
GOOD consensus or relay considers this relay to be usable as a guard
stem.TimeoutSetType(enum)

Way in which the timeout value of a circuit is changing. Tor may provide types not in this enum.

TimeoutSetType Description
COMPUTED tor has computed a new timeout based on prior circuits
RESET timeout reverted to its default
SUSPENDED timeout reverted to its default until network connectivity has recovered
DISCARD throwing out timeout value from when the network was down
RESUME resumed calculations to determine the proper timeout
exception stem.ControllerError[source]

Bases: exceptions.Exception

Base error for controller communication issues.

exception stem.ProtocolError[source]

Bases: stem.ControllerError

Malformed content from the control socket.

exception stem.OperationFailed(code=None, message=None)[source]

Bases: stem.ControllerError

Base exception class for failed operations that return an error code

Variables:
  • code (str) – error code returned by Tor
  • message (str) – error message returned by Tor or a human readable error message
exception stem.UnsatisfiableRequest(code=None, message=None)[source]

Bases: stem.OperationFailed

Exception raised if Tor was unable to process our request.

exception stem.CircuitExtensionFailed(message, circ=None)[source]

Bases: stem.UnsatisfiableRequest

An attempt to create or extend a circuit failed.

Variables:circ (stem.response.CircuitEvent) – response notifying us of the failure
exception stem.InvalidRequest(code=None, message=None)[source]

Bases: stem.OperationFailed

Exception raised when the request was invalid or malformed.

exception stem.InvalidArguments(code=None, message=None, arguments=None)[source]

Bases: stem.InvalidRequest

Exception class for requests which had invalid arguments.

Variables:
  • code (str) – error code returned by Tor
  • message (str) – error message returned by Tor or a human readable error message
  • arguments (list) – a list of arguments which were invalid
exception stem.SocketError[source]

Bases: stem.ControllerError

Error arose while communicating with the control socket.

exception stem.SocketClosed[source]

Bases: stem.SocketError

Control socket was closed before completing the message.