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
  |- get_start_time - timestamp when the tor process began
  |- get_uptime - duration tor has been running
  |- 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- Controllercan 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 - Eventsubclasses 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. - Changed in version 1.8.0: Added the EXTOR and HTTPTUNNEL listeners. - 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) - EXTOR - pluggable transport for Extended ORPorts (torrc’s ExtORPort) - HTTPTUNNEL - http tunneling proxy (torrc’s HTTPTunnelPort) 
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.
DownloadFailed - Inability to download a resource.
  +- DownloadTimeout - Download timeout reached.
- 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. - Changed in version 1.8.0: Added the ACTIVE and DORMANT signals. You can check for Tor support for these signals with the DORMANT_MODE - Requirement- 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 - DORMANT - enables dormant mode, during which tor will avoid cpu and network usage - ACTIVE - disables dormant mode 
- 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. - Changed in version 1.8.0: Added the STALE_DESC 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 - STALE_DESC - relay descriptor is outdated and should be re-uploaded - 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 - RelayEndReasonenumeration 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. - Changed in version 1.8.0: Added the QUERY_RATE_LIMITED 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 - QUERY_RATE_LIMITED - request was throttled - 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