Stem Docs

Controller

Controller

Module for interacting with the Tor control socket. The Controller is a wrapper around a ControlSocket, retaining many of its methods (connect, close, is_alive, etc) in addition to providing its own for working with the socket at a higher level.

Stem has several ways of getting a Controller, but the most flexible are from_port() and from_socket_file(). These static Controller methods give you an unauthenticated Controller you can then authenticate yourself using its authenticate() method. For example…

import getpass
import sys

import stem
import stem.connection

from stem.control import Controller

if __name__ == '__main__':
  try:
    controller = Controller.from_port()
  except stem.SocketError as exc:
    print("Unable to connect to tor on port 9051: %s" % exc)
    sys.exit(1)

  try:
    controller.authenticate()
  except stem.connection.MissingPassword:
    pw = getpass.getpass("Controller password: ")

    try:
      controller.authenticate(password = pw)
    except stem.connection.PasswordAuthFailed:
      print("Unable to authenticate, password is incorrect")
      sys.exit(1)
  except stem.connection.AuthenticationFailure as exc:
    print("Unable to authenticate: %s" % exc)
    sys.exit(1)

  print("Tor is running version %s" % controller.get_version())
  controller.close()

If you’re fine with allowing your script to raise exceptions then this can be more nicely done as…

from stem.control import Controller

if __name__ == '__main__':
  with Controller.from_port() as controller:
    controller.authenticate()

    print("Tor is running version %s" % controller.get_version())

Module Overview:

event_description - brief description of a tor event type

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
  |- reconnect - reconnects and authenticates to socket
  |
  |- get_info - issues a GETINFO query for a parameter
  |- get_version - provides our tor version
  |- get_exit_policy - provides our exit policy
  |- get_ports - provides the local ports where tor is listening for connections
  |- get_listeners - provides the addresses and ports where tor is listening for connections
  |- get_accounting_stats - provides stats related to relaying limits
  |- 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
  |- is_user_traffic_allowed - checks if we send or receive direct user traffic
  |
  |- get_microdescriptor - querying the microdescriptor for a relay
  |- get_microdescriptors - provides all currently available microdescriptors
  |- get_server_descriptor - querying the server descriptor for a relay
  |- get_server_descriptors - provides all currently available server descriptors
  |- get_network_status - querying the router status entry for a relay
  |- get_network_statuses - provides all presently available router status entries
  |- get_hidden_service_descriptor - queries the given hidden service descriptor
  |
  |- get_conf - gets the value of a configuration option
  |- get_conf_map - gets the values of multiple configuration options
  |- is_set - determines if an option differs from its default
  |- 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
  |
  |- get_hidden_service_conf - provides our hidden service configuration
  |- set_hidden_service_conf - sets our hidden service configuration
  |- create_hidden_service - creates a new hidden service or adds a new port
  |- remove_hidden_service - removes a hidden service or drops a port
  |
  |- list_ephemeral_hidden_services - list ephemeral hidden serivces
  |- create_ephemeral_hidden_service - create a new ephemeral hidden service
  |- remove_ephemeral_hidden_service - removes an ephemeral hidden service
  |
  |- 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_newnym_available - true if tor would currently accept a NEWNYM signal
  |- get_newnym_wait - seconds until tor would accept a NEWNYM signal
  |- get_effective_rate - provides our effective relaying rate limit
  |- 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
  +- drop_guards - drops our set of guard relays and picks a new set

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_localhost - returns if the connection is for the local system or not
  |- connection_time - time when we last connected or disconnected
  |- 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
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…

Deprecated since version 1.6.0: Tor dropped EventType.AUTHDIR_NEWDESCS as of version 0.3.2.1. (spec)

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

CELL_STATS

stem.response.events.CellStatsEvent

CIRC

stem.response.events.CircuitEvent

CIRC_BW

stem.response.events.CircuitBandwidthEvent

CIRC_MINOR

stem.response.events.CircMinorEvent

CLIENTS_SEEN

stem.response.events.ClientsSeenEvent

CONF_CHANGED

stem.response.events.ConfChangedEvent

CONN_BW

stem.response.events.ConnectionBandwidthEvent

DEBUG

stem.response.events.LogEvent

DESCCHANGED

stem.response.events.DescChangedEvent

ERR

stem.response.events.LogEvent

GUARD

stem.response.events.GuardEvent

HS_DESC

stem.response.events.HSDescEvent

HS_DESC_CONTENT

stem.response.events.HSDescContentEvent

INFO

stem.response.events.LogEvent

NETWORK_LIVENESS

stem.response.events.NetworkLivenessEvent

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

TB_EMPTY

stem.response.events.TokenBucketEmptyEvent

TRANSPORT_LAUNCHED

stem.response.events.TransportLaunchedEvent

WARN

stem.response.events.LogEvent

stem.control.Listener(enum)

Purposes for inbound connections that Tor handles.

Listener

Description

OR

traffic we’re relaying as a member of the network (torrc’s ORPort and ORListenAddress)

DIR

mirroring for tor descriptor content (torrc’s DirPort and DirListenAddress)

SOCKS

client traffic we’re sending over Tor (torrc’s SocksPort and SocksListenAddress)

TRANS

transparent proxy handling (torrc’s TransPort and TransListenAddress)

NATD

forwarding for ipfw NATD connections (torrc’s NatdPort and NatdListenAddress)

DNS

DNS lookups for our traffic (torrc’s DNSPort and DNSListenAddress)

CONTROL

controller applications (torrc’s ControlPort and ControlListenAddress)

class stem.control.AccountingStats[source]

Bases: stem.control.AccountingStats

Accounting information, determining the limits where our relay suspends itself.

Variables
  • retrieved (float) – unix timestamp for when this was fetched

  • status (str) – hibernation status of ‘awake’, ‘soft’, or ‘hard’

  • interval_end (datetime) – time when our limits reset

  • time_until_reset (int) – seconds until our limits reset

  • read_bytes (int) – number of bytes we’ve read relaying

  • read_bytes_left (int) – number of bytes we can read until we suspend

  • read_limit (int) – reading threshold where we suspend

  • written_bytes (int) – number of bytes we’ve written relaying

  • write_bytes_left (int) – number of bytes we can write until we suspend

  • write_limit (int) – writing threshold where we suspend

class stem.control.UserTrafficAllowed[source]

Bases: stem.control.UserTrafficAllowed

Indicates if we’re likely to be servicing direct user traffic or not.

Variables
  • inbound (bool) – if True we’re likely providing guard or bridge connnections

  • outbound (bool) – if True we’re likely providng exit connections

class stem.control.CreateHiddenServiceOutput[source]

Bases: stem.control.CreateHiddenServiceOutput

Attributes of a hidden service we’ve created.

Both the hostnames and hostname_for_client attributes can only be provided if we’re able to read the hidden service directory. If the method was called with client_names then we may provide the hostname_for_client, and otherwise can provide the hostnames.

Variables
  • path (str) – hidden service directory

  • hostname (str) – content of the hostname file if available

  • hostname_for_client (dict) – mapping of client names to their onion address if available

  • config (dict) – tor’s new hidden service configuration

stem.control.with_default(yields=False)[source]

Provides a decorator to support having a default value. This should be treated as private.

stem.control.event_description(event)[source]

Provides a description for Tor events.

Parameters

event (str) – the event for which a description is needed

Returns

str The event description or None if this is an event name we don’t have a description for

class stem.control.BaseController(control_socket, is_authenticated=False)[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.

If the control_socket is already authenticated to Tor then the caller should provide the is_authenticated flag. Otherwise, we will treat the socket as though it hasn’t yet been authenticated.

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_localhost()[source]

Returns if the connection is for the local system or not.

New in version 1.3.0.

Returns

bool that’s True if the connection is for the local host and False otherwise

connection_time()[source]

Provides the unix timestamp for when our socket was either connected or disconnected. That is to say, the time we connected if we’re currently connected and the time we disconnected if we’re not connected.

New in version 1.3.0.

Returns

float for when we last connected or disconnected, zero if we’ve never connected

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. If still outstanding these threads are joined on as part of closing this controller.

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, is_authenticated=False)[source]

Bases: stem.control.BaseController

Connection with Tor’s 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='default')[source]

Constructs a ControlPort based Controller.

If the port is ‘default’ then this checks on both 9051 (default for relays) and 9151 (default for the Tor Browser). This default may change in the future.

Changed in version 1.5.0: Use both port 9051 and 9151 by default.

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

close()[source]

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

authenticate(*args, **kwargs)[source]

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

reconnect(*args, **kwargs)[source]

Reconnects and authenticates to our control socket.

New in version 1.5.0.

Raises
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).

Changed in version 1.1.0: Added the get_bytes argument.

Changed in version 1.7.0: Errors commonly provided a stem.ProtocolError when we should raise a stem.OperationFailed.

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.

Changed in version 1.7.0: Policies retrieved through ‘GETINFO exit-policy/full’ rather than parsing the user’s torrc entries. This should be more reliable for some edge cases. (ticket 25739)

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_ports(listener_type, default = UNDEFINED)[source]

Provides the local ports where tor is listening for the given type of connections. This is similar to get_listeners(), but doesn’t provide addresses nor include non-local endpoints.

New in version 1.2.0.

Parameters
  • listener_type (stem.control.Listener) – connection type being handled by the ports we return

  • default (object) – response if the query fails

Returns

list of ints for the local ports where tor handles connections of the given type

Raises

stem.ControllerError if unable to determine the ports and no default was provided

get_listeners(listener_type, default = UNDEFINED)[source]

Provides the addresses and ports where tor is listening for connections of the given type. This is similar to get_ports() but includes listener addresses and non-local endpoints.

New in version 1.2.0.

Changed in version 1.5.0: Recognize listeners with IPv6 addresses.

Parameters
  • listener_type (stem.control.Listener) – connection type being handled by the listeners we return

  • default (object) – response if the query fails

Returns

list of (address, port) tuples for the available listeners

Raises

stem.ControllerError if unable to determine the listeners and no default was provided

get_accounting_stats(default = UNDEFINED)[source]

Provides stats related to our relaying limitations if AccountingMax was set in our torrc.

New in version 1.3.0.

Parameters

default (object) – response if the query fails

Returns

AccountingStats with our accounting stats

Raises

stem.ControllerError if unable to determine the listeners and no default was provided

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

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

Deprecated since version 1.2.0: Use get_listeners() with Listener.SOCKS instead.

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.

New in version 1.1.0.

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.

New in version 1.1.0.

Parameters

default (object) – response if the query fails

Returns

int for tor’s pid

Raises

ValueError if unable to determine the pid and no default was provided

is_user_traffic_allowed()[source]

Checks if we’re likely to service direct user traffic. This essentially boils down to…

  • If we’re a bridge or guard relay, inbound connections are possibly from users.

  • If our exit policy allows traffic then output connections are possibly from users.

Note the word ‘likely’. These is a decent guess in practice, but not always correct. For instance, information about which flags we have are only fetched periodically.

This method is intended to help you avoid eavesdropping on user traffic. Monitoring user connections is not only unethical, but likely a violation of wiretapping laws.

New in version 1.5.0.

Returns

UserTrafficAllowed with inbound and outbound boolean attributes to indicate if we’re likely servicing direct user traffic

get_microdescriptor(relay = None, 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.

If no relay is provided then this defaults to ourselves. Remember that this requires that we’ve retrieved our own descriptor from remote authorities so this both won’t be available for newly started relays and may be up to around an hour out of date.

Changed in version 1.3.0: Changed so we’d fetch our own descriptor if no ‘relay’ is provided.

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

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 currently knows about.

Prior to Tor 0.3.5.1 this information was not available via the control protocol. When connected to prior versions we read the microdescriptors directly from disk instead, which will not work remotely or if our process lacks 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 = None, 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.

If no relay is provided then this defaults to ourselves. Remember that this requires that we’ve retrieved our own descriptor from remote authorities so this both won’t be available for newly started relays and may be up to around an hour out of date.

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’.

Changed in version 1.3.0: Changed so we’d fetch our own descriptor if no ‘relay’ is provided.

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

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 currently 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 = None, 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.

If no relay is provided then this defaults to ourselves. Remember that this requires that we’ve retrieved our own descriptor from remote authorities so this both won’t be available for newly started relays and may be up to around an hour out of date.

Changed in version 1.3.0: Changed so we’d fetch our own descriptor if no ‘relay’ is provided.

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

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 currently 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_hidden_service_descriptor(address, default = UNDEFINED, servers = None, await_result = True)[source]

Provides the descriptor for a hidden service. The address is the ‘.onion’ address of the hidden service (for instance 3g2upl4pq6kufc4m.onion for DuckDuckGo).

If await_result is True then this blocks until we either receive the descriptor or the request fails. If False this returns right away.

This method only supports v2 hidden services, not v3. (ticket 25417)

New in version 1.4.0.

Changed in version 1.7.0: Added the timeout argument.

Parameters
  • address (str) – address of the hidden service descriptor, the ‘.onion’ suffix is optional

  • default (object) – response if the query fails

  • servers (list) – requrest the descriptor from these specific servers

  • timeout (float) – seconds to wait when await_result is True

Returns

HiddenServiceDescriptor for the given service if await_result is True, or None otherwise

Raises

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

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.

Note: HiddenServiceOptions are best retrieved via the get_hidden_service_conf() method instead.

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
is_set(param, default = UNDEFINED)[source]

Checks if a configuration option differs from its default or not.

New in version 1.5.0.

Parameters
  • param (str) – configuration option to check

  • default (object) – response if the query fails

Returns

True if option differs from its default and False otherwise

Raises

stem.ControllerError if the call fails and we weren’t provided a default response

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
get_hidden_service_conf(default = UNDEFINED)[source]

This provides a mapping of hidden service directories to their attribute’s key/value pairs. All hidden services are assured to have a ‘HiddenServicePort’, but other entries may or may not exist.

{
  "/var/lib/tor/hidden_service_empty/": {
    "HiddenServicePort": [
    ]
  },
  "/var/lib/tor/hidden_service_with_two_ports/": {
    "HiddenServiceAuthorizeClient": "stealth a, b",
    "HiddenServicePort": [
      (8020, "127.0.0.1", 8020),  # the ports order is kept
      (8021, "127.0.0.1", 8021)
    ],
    "HiddenServiceVersion": "2"
  },
}

New in version 1.3.0.

Parameters

default (object) – response if the query fails

Returns

dict with the hidden service configuration

Raises

stem.ControllerError if the call fails and we weren’t provided a default response

set_hidden_service_conf(conf)[source]

Update all the configured hidden services from a dictionary having the same format as get_hidden_service_conf().

For convenience the HiddenServicePort entries can be an integer, string, or tuple. If an int then we treat it as just a port. If a str we pass that directly as the HiddenServicePort. And finally, if a tuple then it’s expected to be the (port, target_address, target_port) as provided by get_hidden_service_conf().

This is to say the following three are equivalent…

"HiddenServicePort": [
  80,
  '80 127.0.0.1:80',
  (80, '127.0.0.1', 80),
]

New in version 1.3.0.

Parameters

conf (dict) – configuration dictionary

Raises
create_hidden_service(path, port, target_address=None, target_port=None, auth_type=None, client_names=None)[source]

Create a new hidden service. If the directory is already present, a new port is added.

Our .onion address is fetched by reading the hidden service directory. However, this directory is only readable by the tor user, so if unavailable the **hostname* will be None.

As of Tor 0.2.7.1 there’s two ways for creating hidden services, and this method is no longer recommended. Rather, try using create_ephemeral_hidden_service() instead.

New in version 1.3.0.

Changed in version 1.4.0: Added the auth_type and client_names arguments.

Parameters
  • path (str) – path for the hidden service’s data directory

  • port (int) – hidden service port

  • target_address (str) – address of the service, by default 127.0.0.1

  • target_port (int) – port of the service, by default this is the same as port

  • auth_type (str) – authentication type: basic, stealth or None to disable auth

  • client_names (list) – client names (1-16 characters “A-Za-z0-9+-_”)

Returns

CreateHiddenServiceOutput if we create or update a hidden service, None otherwise

Raises

stem.ControllerError if the call fails

remove_hidden_service(path, port=None)[source]

Discontinues a given hidden service.

New in version 1.3.0.

Parameters
  • path (str) – path for the hidden service’s data directory

  • port (int) – hidden service port

Returns

True if the hidden service is discontinued, False if it wasn’t running in the first place

Raises

stem.ControllerError if the call fails

list_ephemeral_hidden_services(default = UNDEFINED, our_services = True, detached = False)[source]

Lists hidden service addresses created by create_ephemeral_hidden_service().

New in version 1.4.0.

Changed in version 1.6.0: Tor change caused this to start providing empty strings if unset (ticket 21329).

Parameters
  • default (object) – response if the query fails

  • our_services (bool) – include services created with this controller that weren’t flagged as ‘detached’

  • detached (bool) – include services whos contiuation isn’t tied to a controller

Returns

list of hidden service addresses without their ‘.onion’ suffix

Raises

stem.ControllerError if the call fails and we weren’t provided a default response

create_ephemeral_hidden_service(ports, key_type='NEW', key_content='BEST', discard_key=False, detached=False, await_publication=False, timeout=None, basic_auth=None, max_streams=None)[source]

Creates a new hidden service. Unlike create_hidden_service() this style of hidden service doesn’t touch disk, carrying with it a lot of advantages. This is the suggested method for making hidden services.

Our ports argument can be a single port…

create_ephemeral_hidden_service(80)

… list of ports the service is available on…

create_ephemeral_hidden_service([80, 443])

… or a mapping of hidden service ports to their targets…

create_ephemeral_hidden_service({80: 80, 443: '173.194.33.133:443'})

If basic_auth is provided this service will require basic authentication to access. This means users must set HidServAuth in their torrc with credentials to access it.

basic_auth is a mapping of usernames to their credentials. If the credential is None one is generated and returned as part of the response. For instance, only bob can access using the given newly generated credentials…

>>> response = controller.create_ephemeral_hidden_service(80, basic_auth = {'bob': None})
>>> print(response.client_auth)
{'bob': 'nKwfvVPmTNr2k2pG0pzV4g'}

… while both alice and bob can access with existing credentials in the following…

controller.create_ephemeral_hidden_service(80, basic_auth = {
  'alice': 'l4BT016McqV2Oail+Bwe6w',
  'bob': 'vGnNRpWYiMBFTWD2gbBlcA',
})

To create a version 3 service simply specify ED25519-V3 as the our key type, and to create a version 2 service use RSA1024. The default version of newly created hidden services is based on the HiddenServiceVersion value in your torrc…

response = controller.create_ephemeral_hidden_service(
  80,
  key_content = 'ED25519-V3',
  await_publication = True,
)

print('service established at %s.onion' % response.service_id)

New in version 1.4.0.

Changed in version 1.5.0: Added the basic_auth argument.

Changed in version 1.5.0: Added support for non-anonymous services. To do so set ‘HiddenServiceSingleHopMode 1’ and ‘HiddenServiceNonAnonymousMode 1’ in your torrc.

Changed in version 1.7.0: Added the timeout and max_streams arguments.

Parameters
  • ports (int,list,dict) – hidden service port(s) or mapping of hidden service ports to their targets

  • key_type (str) – type of key being provided, generates a new key if ‘NEW’ (options are: NEW, RSA1024, and ED25519-V3)

  • key_content (str) – key for the service to use or type of key to be generated (options when key_type is NEW are BEST, RSA1024, and ED25519-V3)

  • discard_key (bool) – avoid providing the key back in our response

  • detached (bool) – continue this hidden service even after this control connection is closed if True

  • await_publication (bool) – blocks until our descriptor is successfully published if True

  • timeout (float) – seconds to wait when await_result is True

  • basic_auth (dict) – required user credentials to access this service

  • max_streams (int) – maximum number of streams the hidden service will accept, unlimited if zero or not set

Returns

AddOnionResponse with the response

Raises
remove_ephemeral_hidden_service(service_id)[source]

Discontinues a given hidden service that was created with create_ephemeral_hidden_service().

New in version 1.4.0.

Parameters

service_id (str) – hidden service address without the ‘.onion’ suffix

Returns

True if the hidden service is discontinued, False if it wasn’t running in the first place

Raises

stem.ControllerError if the call fails

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.

If tor emits a malformed event it can be received by listening for the stem.control.MALFORMED_EVENTS constant.

Changed in version 1.7.0: Listener exceptions and malformed events no longer break further event processing. Added the MALFORMED_EVENTS constant.

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(force=False)[source]

Saves the current configuration options into the active torrc file.

Changed in version 1.6.0: Added the force argument.

Parameters

force (bool) – overwrite the configuration even if it includes a ‘%include’ clause, this is ignored if tor doesn’t support it

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 currently 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, timeout=None)[source]

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

Changed in version 1.7.0: Added the timeout argument.

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

  • timeout (float) – seconds to wait when await_build is True

Returns

str of the circuit id of the newly created circuit

Raises
extend_circuit(circuit_id='0', path=None, purpose='general', await_build=False, timeout=None)[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…

>>> controller.extend_circuit('0', ['718BCEA286B531757ACAFF93AE04910EA73DE617', '30BAB8EE7606CBD12F3CC269AE976E0153E7A58D', '2765D8A8C4BBA3F89585A9FFE0E8575615880BEB'])
19
>>> controller.extend_circuit('0')
20
>>> print(controller.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

Changed in version 1.7.0: Added the timeout argument.

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

  • timeout (float) – seconds to wait when await_build is 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
signal(signal)[source]

Sends a signal to the Tor client.

Parameters

signal (stem.Signal) – type of signal to be sent

Raises
is_newnym_available()[source]

Indicates if tor would currently accept a NEWNYM signal. This can only account for signals sent via this controller.

New in version 1.2.0.

Returns

True if tor would currently accept a NEWNYM signal, False otherwise

get_newnym_wait()[source]

Provides the number of seconds until a NEWNYM signal would be respected. This can only account for signals sent via this controller.

New in version 1.2.0.

Returns

float for the number of seconds until tor would respect another NEWNYM signal

get_effective_rate(default = UNDEFINED, burst = False)[source]

Provides the maximum rate this relay is configured to relay in bytes per second. This is based on multiple torrc parameters if they’re set…

  • Effective Rate = min(BandwidthRate, RelayBandwidthRate, MaxAdvertisedBandwidth)

  • Effective Burst = min(BandwidthBurst, RelayBandwidthBurst)

New in version 1.3.0.

Parameters
  • default (object) – response if the query fails

  • burst (bool) – provides the burst bandwidth, otherwise this provides the standard rate

Returns

int with the effective bandwidth rate in bytes per second

Raises

stem.ControllerError if the call fails and no default was provided

is_geoip_unavailable()[source]

Provides True if tor’s geoip database is unavailable, False otherwise.

Changed in version 1.6.0: No longer requires previously failed GETINFO requests to determine this.

Deprecated since version 1.6.0: This is available as of Tor 0.3.2.1 through the following instead…

controller.get_info('ip-to-country/ipv4-available', 0) == '1'
Returns

bool indicating if we’ve determined tor’s 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

drop_guards()[source]

Drops our present guard nodes and picks a new set.

New in version 1.2.0.

Raises

stem.ControllerError if Tor couldn’t fulfill the request

Exceptions and Attribute Enums

Library for working with the tor process.

Module Overview:

Endpoint - Networking endpoint.
  |- ORPort - Tor relay endpoint.
  +- DirPort - Descriptor mirror.

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.
  |  |  |- DescriptorUnavailable - The given relay descriptor is unavailable.
  |  |  +- Timeout - Caller requested timeout was reached.
  |  |
  |  |
  |  +- 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.

Changed in version 1.3.0: Added the HEARTBEAT signal.

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

HEARTBEAT

trigger a heartbeat log message

stem.Flag(enum)

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

Note: The BADDIRECTORY flag was removed from tor.

Changed in version 1.5.0: Added the NO_ED_CONSENSUS flag.

Flag

Description

AUTHORITY

relay is a directory authority

BADEXIT

relay shouldn’t be used as an exit due to being either problematic or malicious

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

NO_ED_CONSENSUS

relay’s Ed25519 doesn’t reflrect the consensus

RUNNING

relay is currently usable

STABLE

relay’s suitable for long-lived circuits

UNNAMED

relay isn’t currently 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.

Changed in version 1.6.0: Added the GUARD_WAIT signal.

CircStatus

Description

LAUNCHED

new circuit was created

BUILT

circuit finished being created and can accept traffic

GUARD_WAIT

waiting to see if there’s a circuit with a better guard before using

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 currently 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

PT_MISSING

no pluggable transport was available

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

stem.ConnectionType(enum)

Purpose for a tor connection. Tor may provide types not in this enum.

The meaning behind these values is a bit unclear, pending ticket 10086.

New in version 1.2.0.

ConnectionType

Description

OR

carrying traffic within the tor network

DIR

fetching or sending tor descriptor data

EXIT

carrying traffic between the tor network and an external destination

stem.TokenBucket(enum)

Bucket categories of TB_EMPTY events.

New in version 1.2.0.

TokenBucket

Description

GLOBAL

global token bucket

RELAY

relay token bucket

ORCONN

bucket used for OR connections

stem.HSDescAction(enum)

Action beeing taken in a HS_DESC event.

New in version 1.2.0.

Changed in version 1.4.0: Added the UPLOAD and UPLOADED actions.

Changed in version 1.5.0: Added the CREATED action.

HSDescAction

Description

REQUESTED

uncached hidden service descriptor is being requested

UPLOAD

descriptor is being uploaded with HSPOST

RECEIVED

hidden service descriptor has been retrieved

UPLOADED

descriptor was uploaded with HSPOST

IGNORE

fetched descriptor was ignored because we already have its v0 descriptor

FAILED

we were unable to retrieve the descriptor

CREATED

hidden service descriptor was just created

stem.HSDescReason(enum)

Reason for the hidden service descriptor to fail to be fetched.

New in version 1.3.0.

Changed in version 1.4.0: Added the UPLOAD_REJECTED reason.

Changed in version 1.6.0: Added the QUERY_NO_HSDIR reason.

HSDescReason

Description

BAD_DESC

descriptor was unparseable

QUERY_REJECTED

hidden service directory refused to provide the descriptor

UPLOAD_REJECTED

descriptor was rejected by the hidden service directory

NOT_FOUND

descriptor with the given identifier wasn’t found

QUERY_NO_HSDIR

no hidden service directory was found

UNEXPECTED

failure type is unknown

stem.HSAuth(enum)

Type of authentication being used for a HS_DESC event.

New in version 1.2.0.

HSAuth

Description

NO_AUTH

no authentication

BASIC_AUTH

general hidden service authentication

STEALTH_AUTH

authentication method that hides service activity from unauthorized clients

UNKNOWN

unrecognized method of authentication

exception stem.ControllerError[source]

Bases: 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.DescriptorUnavailable(message)[source]

Bases: stem.UnsatisfiableRequest

Tor was unable to provide a descriptor for the given relay.

Changed in version 1.7.0: Subclassed under UnsatisfiableRequest rather than OperationFailed.

exception stem.Timeout(message)[source]

Bases: stem.UnsatisfiableRequest

Timeout requested by the caller was reached.

New in version 1.7.0.

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.