
    <iL                       S r SSKrSSKrSSKrSSKrSSKrSSKrSSKrSSK	r	 SSKJ
r
   SSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKJ r J!r!J"r"  SSKJ#r#  Sr$Sr%\RL                  RN                  RQ                  SS	S
5      r)\RL                  RN                  RT                  " S6 r+\RL                  RN                  RU                  SSSSSSSSS5	      r,\-" \." \RL                  R^                  R`                  \." \1Rd                  S5      5      5      r3Sr4SSSSSS.r5Sr6Sr7Sr8Sr9Sq: " S S\Rv                  " S/ SQ5      5      r< " S  S!\Rv                  " S!S"S#/5      5      r= " S$ S%\Rv                  " S%/ S&Q5      5      r>S1S' jr?S( r@ " S) S*\A5      rB " S+ S,\B5      rCS- rDS. rE\?" 5       \ 4S/ j5       rFS0 rGg! \ a
    SSKJ
r
   GNf = f! \ a    SSKr GNf = f)2a-  
Module for interacting with the Tor control socket. The
:class:`~stem.control.Controller` is a wrapper around a
:class:`~stem.socket.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 <../faq.html#how-do-i-connect-to-tor>`_ of getting a
:class:`~stem.control.Controller`, but the most flexible are
:func:`~stem.control.Controller.from_port` and
:func:`~stem.control.Controller.from_socket_file`. These static
:class:`~stem.control.Controller` methods give you an **unauthenticated**
Controller you can then authenticate yourself using its
:func:`~stem.control.Controller.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

.. data:: 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
  ========== ===========

.. data:: EventType (enum)

  Known types of events that the
  :func:`~stem.control.Controller.add_event_listener` method of the
  :class:`~stem.control.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 :class:`~stem.response.events.Event` subclasses as
  follows...

  .. deprecated:: 1.6.0

     Tor dropped EventType.AUTHDIR_NEWDESCS as of version 0.3.2.1.
     (:spec:`6e887ba`)

  ======================= ===========
  EventType               Event Class
  ======================= ===========
  **ADDRMAP**             :class:`stem.response.events.AddrMapEvent`
  **AUTHDIR_NEWDESCS**    :class:`stem.response.events.AuthDirNewDescEvent`
  **BUILDTIMEOUT_SET**    :class:`stem.response.events.BuildTimeoutSetEvent`
  **BW**                  :class:`stem.response.events.BandwidthEvent`
  **CELL_STATS**          :class:`stem.response.events.CellStatsEvent`
  **CIRC**                :class:`stem.response.events.CircuitEvent`
  **CIRC_BW**             :class:`stem.response.events.CircuitBandwidthEvent`
  **CIRC_MINOR**          :class:`stem.response.events.CircMinorEvent`
  **CLIENTS_SEEN**        :class:`stem.response.events.ClientsSeenEvent`
  **CONF_CHANGED**        :class:`stem.response.events.ConfChangedEvent`
  **CONN_BW**             :class:`stem.response.events.ConnectionBandwidthEvent`
  **DEBUG**               :class:`stem.response.events.LogEvent`
  **DESCCHANGED**         :class:`stem.response.events.DescChangedEvent`
  **ERR**                 :class:`stem.response.events.LogEvent`
  **GUARD**               :class:`stem.response.events.GuardEvent`
  **HS_DESC**             :class:`stem.response.events.HSDescEvent`
  **HS_DESC_CONTENT**     :class:`stem.response.events.HSDescContentEvent`
  **INFO**                :class:`stem.response.events.LogEvent`
  **NETWORK_LIVENESS**    :class:`stem.response.events.NetworkLivenessEvent`
  **NEWCONSENSUS**        :class:`stem.response.events.NewConsensusEvent`
  **NEWDESC**             :class:`stem.response.events.NewDescEvent`
  **NOTICE**              :class:`stem.response.events.LogEvent`
  **NS**                  :class:`stem.response.events.NetworkStatusEvent`
  **ORCONN**              :class:`stem.response.events.ORConnEvent`
  **SIGNAL**              :class:`stem.response.events.SignalEvent`
  **STATUS_CLIENT**       :class:`stem.response.events.StatusEvent`
  **STATUS_GENERAL**      :class:`stem.response.events.StatusEvent`
  **STATUS_SERVER**       :class:`stem.response.events.StatusEvent`
  **STREAM**              :class:`stem.response.events.StreamEvent`
  **STREAM_BW**           :class:`stem.response.events.StreamBwEvent`
  **TB_EMPTY**            :class:`stem.response.events.TokenBucketEmptyEvent`
  **TRANSPORT_LAUNCHED**  :class:`stem.response.events.TransportLaunchedEvent`
  **WARN**                :class:`stem.response.events.LogEvent`
  ======================= ===========

.. data:: Listener (enum)

  Purposes for inbound connections that Tor handles.

  .. versionchanged:: 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**)
  =============== ===========
    N)OrderedDict)	UNDEFINED
CircStatusSignal)logg?MALFORMED_EVENTSINITRESETCLOSED)!ADDRMAPAUTHDIR_NEWDESCSBUILDTIMEOUT_SETBW
CELL_STATSCIRCCIRC_BW
CIRC_MINORCONF_CHANGEDCONN_BWCLIENTS_SEENDEBUGDESCCHANGEDERRGUARDHS_DESCHS_DESC_CONTENTINFONETWORK_LIVENESSNEWCONSENSUSNEWDESCNOTICENSORCONNSIGNALSTATUS_CLIENTSTATUS_GENERALSTATUS_SERVERSTREAM	STREAM_BWTB_EMPTYTRANSPORT_LAUNCHEDWARNORDIRSOCKSTRANSNATDDNSCONTROLEXTOR
HTTPTUNNEL)AccelDir	AccelNameDataDirectoryDisableAllSwapDisableDebuggerAttachmentHardwareAccelHiddenServiceNonAnonymousModeHiddenServiceSingleHopModeKeepBindCapabilitiesPidFileRunAsDaemonSandboxSyslogIdentityTagTokenBucketRefillIntervalUserTHiddenServiceOptions)hiddenservicedirhiddenserviceporthiddenserviceversionhiddenserviceauthorizeclienthiddenserviceoptions)addressversionzconfig-fileexit-policy/defaultfingerprintzconfig/nameszconfig/defaultsz
info/nameszevents/nameszfeatures/nameszprocess/descriptor-limitzstatus/version/current)accounting/enabled)rJ   rF   rG   rH   rI   zTor is currently not configured to retrieve server descriptors. As of Tor version 0.2.3.25 it downloads microdescriptors instead unless you set 'UseMicrodescriptors 0' in your torrc.c                       \ rS rSrSrSrg)AccountingStatsi  a  
Accounting information, determining the limits where our relay suspends
itself.

:var float retrieved: unix timestamp for when this was fetched
:var str status: hibernation status of 'awake', 'soft', or 'hard'
:var datetime interval_end: time when our limits reset
:var int time_until_reset: seconds until our limits reset
:var int read_bytes: number of bytes we've read relaying
:var int read_bytes_left: number of bytes we can read until we suspend
:var int read_limit: reading threshold where we suspend
:var int written_bytes: number of bytes we've written relaying
:var int write_bytes_left: number of bytes we can write until we suspend
:var int write_limit: writing threshold where we suspend
 N__name__
__module____qualname____firstlineno____doc____static_attributes__rR       F/home/james-whalen/.local/lib/python3.13/site-packages/stem/control.pyrQ   rQ     s    rZ   rQ   
	retrievedstatusinterval_endtime_until_reset
read_bytesread_bytes_left
read_limitwritten_byteswrite_bytes_leftwrite_limitc                       \ rS rSrSrSrg)UserTrafficAllowedi  z
Indicates if we're likely to be servicing direct user traffic or not.

:var bool inbound: if **True** we're likely providing guard or bridge connnections
:var bool outbound: if **True** we're likely providng exit connections
rR   NrS   rR   rZ   r[   rh   rh     s    rZ   rh   inboundoutboundc                       \ rS rSrSrSrg)CreateHiddenServiceOutputi  a@  
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**.

:var str path: hidden service directory
:var str hostname: content of the hostname file if available
:var dict hostname_for_client: mapping of client names to their onion address
  if available
:var dict config: tor's new hidden service configuration
rR   NrS   rR   rZ   r[   rl   rl     s    rZ   rl   pathhostnamehostname_for_clientconfigc                    ^  U 4S jnU$ )z\
Provides a decorator to support having a default value. This should be
treated as private.
c                    >^ ^ S mT(       d"  [         R                  " T 5      U U4S j5       nU$ [         R                  " T 5      U U4S j5       nU$ )Nc                     [         R                  " U 5      R                  SS  nSU;   a  UR                  S5      OS nUb  U[	        U5      :  a  X   $ UR                  S[        5      $ )N   default)inspectgetfullargspecargsindexlengetr   )funcry   kwargs	arg_namesdefault_positions        r[   get_default4with_default.<locals>.decorator.<locals>.get_default  sd    ((.33AB7i7@I7M3SW		%*:SY*F%%zz)Y//rZ   c                 X   >  T" U /UQ70 UD6$ !   T" TX5      nU[         :X  a  e Us $ = fNr   )selfry   r~   rv   r}   r   s       r[   wrapped0with_default.<locals>.decorator.<locals>.wrapped  s@    	d,T,V,
,	d3'	!Ns    )c              ?      >#     T" U /UQ70 UD6 H  nUv   M	     g !   T" TX5      nU[         :X  a  e Ub  U H  nUv   M	      g  g = f7fr   r   )r   ry   r~   valrv   r}   r   s        r[   r   r     s`     	$000cI 1	d3'	!" #	 ! #s   A
 A
&AA
)	functoolswraps)r}   r   r   yieldss   ` @r[   	decoratorwith_default.<locals>.decorator  sS    0 t	 	4 N t  NrZ   rR   )r   r   s   ` r[   with_defaultr     s    &P 
rZ   c           	         [         c  [        R                  R                  R	                  5       n[
        R                  R                  [
        R                  R                  [        5      S5      n UR                  U5        [        UR                  5        Vs/ s H>  o3R                  S5      (       d  M  UR                  5       SS UR                  U5      4PM@     sn5      q [         R'                  U R                  5       5      $ s  snf ! [          a(  n["        R$                  " SU< SU< 35         SnAgSnAff = f)z
Provides a description for Tor events.

:param str event: 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
Nzsettings.cfgzevent.description.   z?BUG: stem failed to load its internal manual information from 'z': )EVENT_DESCRIPTIONSstemutilconfConfigosrn   joindirname__file__loaddictkeys
startswithlower	get_value	Exceptionr   warnr|   )eventrq   config_pathkeyexcs        r[   event_descriptionr     s     YY^^""$F'',,rwwx8.IKkk+V\VaVaVc  !MVcsgugu  wK  hL!J#))+bc"2F4D4DS4I!JVc  !M  N
 
			.. !M 	hh[fhklms0   2(D D	7(D	D 	D 
E D;;E c                       \ rS rSrSrSS jrS rS rS rS r	S r
S	 rS
 rS rS rSS jrS rS rS rS rS rS rS rS rS rS rS rSrg)BaseControlleri   ao  
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 :class:`~stem.control.Controller`
provide higher level functionality.

It's highly suggested that you don't interact directly with the
:class:`~stem.socket.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.
c                    Xl         [        R                  " 5       U l        / U l        [        R                  " 5       U l        [        R                  " 5       U l        [        R                  " 5       U l	        S U l
        [        R                  " 5       U l        S U l        U R                   R                  U l        U R                   R                   U l        U R                  U R                   l        U R                   U R                   l        SU l        SU l        / U l        U R                   R+                  5       (       a  U R-                  5         U(       a  U R/                  5         g g )N        F)_socket	threadingRLock	_msg_lock_status_listeners_status_listeners_lockqueueQueue_reply_queue_event_queue_reader_threadEvent_event_notice_event_thread_connect_socket_connect_close_socket_close_last_heartbeat_is_authenticated_state_change_threadsis_alive_launch_threads_post_authentication)r   control_socketis_authenticateds      r[   __init__BaseController.__init__0  s    !L__&DND"+//"3D DD D #*DD
  <<00D,,D MMDLL++DLLD"D!#D||

! rZ   c                    U R                      U R                  R                  5       (       Gd   U R                  R                  5       n[	        U[
        R                  5      (       a  O[	        U[
        R                  5      (       a  [        R                  " SU-  5        O{[	        U[
        R                  5      (       a  [        R                  " SU-  5        OB[	        U[
        R                  R                  5      (       a  [        R                  " SU-  5        U R                  R                  5       (       d  GM   U R                  R!                  U5        U R                  R#                  5       n[	        U[
        R                  5      (       a  UeUsSSS5        $ ! [        R                   a     My  f = f! [
        R                   a    U R%                  5         e f = f! , (       d  f       g= f)a  
Sends a message to our control socket and provides back its reply.

:param str message: message to be formatted and sent to tor

:returns: :class:`~stem.response.ControlMessage` with the response

:raises:
  * :class:`stem.ProtocolError` the content from the socket is
    malformed
  * :class:`stem.SocketError` if a problem arises in using the
    socket
  * :class:`stem.SocketClosed` if the socket is shut down
z%Tor provided a malformed message (%s)z!Socket experienced a problem (%s)z Failed to deliver a response: %sN)r   r   empty
get_nowait
isinstancer   SocketClosedProtocolErrorr   infoControllerErrorresponseControlMessager   Emptyr   sendr|   close)r   messager   s      r[   msgBaseController.msgV  ss     
: !!''))	&&113($"3"344(D$6$677HH<xGH(D$8$899HH88CD(DMM$@$@AAHH7(BC !!''))$'"$$((*
 h 4 455.s 
R {{ 	 		"   	

u 
sf   !G%9F!(G%)8F!!G%"8F!G%AF!G% AF<!F95G%8F99G%<&G""G%%
G3c                 6    U R                   R                  5       $ )z
Checks if our socket is currently connected. This is a pass-through for our
socket's :func:`~stem.socket.BaseSocket.is_alive` method.

:returns: **bool** that's **True** if our socket is connected and **False** otherwise
)r   r   r   s    r[   r   BaseController.is_alive  s     <<  ""rZ   c                 6    U R                   R                  5       $ )z
Returns if the connection is for the local system or not.

.. versionadded:: 1.3.0

:returns: **bool** that's **True** if the connection is for the local host and **False** otherwise
)r   is_localhostr   s    r[   r   BaseController.is_localhost  s     <<$$&&rZ   c                 6    U R                   R                  5       $ )aI  
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.

.. versionadded:: 1.3.0

:returns: **float** for when we last connected or disconnected, zero if
  we've never connected
)r   connection_timer   s    r[   r   BaseController.connection_time  s     <<''))rZ   c                 H    U R                  5       (       a  U R                  $ S$ )z
Checks if our socket is both connected and authenticated.

:returns: **bool** that's **True** if our socket is authenticated to tor
  and **False** otherwise
F)r   r   r   s    r[   r   BaseController.is_authenticated  s     &*]]__4!!?%?rZ   c                 8    U R                   R                  5         g)z
Reconnects our control socket. This is a pass-through for our socket's
:func:`~stem.socket.ControlSocket.connect` method.

:raises: :class:`stem.SocketError` if unable to make a socket
N)r   connectr   s    r[   r   BaseController.connect  s     	LLrZ   c                     U R                   R                  5         U R                   HE  nUR                  5       (       d  M  [        R
                  " 5       U:w  d  M5  UR                  5         MG     g)zu
Closes our socket connection. This is a pass-through for our socket's
:func:`~stem.socket.BaseSocket.close` method.
N)r   r   r   r   r   current_threadr   r   ts     r[   r   BaseController.close  sJ     	LL ''	
)2249	 (rZ   c                     U R                   $ )z
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: :class:`~stem.socket.ControlSocket` we're communicating with
)r   r   s    r[   
get_socketBaseController.get_socket  s     <<rZ   c                     U R                   $ )z
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
)r   r   s    r[   get_latest_heartbeat#BaseController.get_latest_heartbeat  s     rZ   c                     U R                      U R                  R                  X45        SSS5        g! , (       d  f       g= f)a  
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 :data:`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.

:param function callback: function to be notified when our state changes
:param bool spawn: calls function via a new thread if **True**, otherwise
  it's part of the connect/close method call
Nr   r   append)r   callbackspawns      r[   add_status_listener"BaseController.add_status_listener  s0    6 
	$	$
##X$56 
%	$	$s	   3
Ac                     U R                      / Sp2U R                   H   u  pEXA:w  a  UR                  XE45        M  SnM"     X l        UsSSS5        $ ! , (       d  f       g= f)z
Stops listener from being notified of further events.

:param function callback: function to be removed from our listeners

:returns: **bool** that's **True** if we removed one or more occurrences of
  the callback, **False** otherwise
FTNr   )r   r   new_listeners
is_changedlistenerr   s         r[   remove_status_listener%BaseController.remove_status_listener%  sY     
	$	$"$eZ!33/(


0
1*	 4  - 
%	$	$s   ;A
A c                     U $ r   rR   r   s    r[   	__enter__BaseController.__enter__;  s    KrZ   c                 $    U R                  5         g r   )r   )r   	exit_typevalue	tracebacks       r[   __exit__BaseController.__exit__>  s    JJLrZ   c                     g)z
Callback to be overwritten by subclasses for event listening. This is
notified whenever we receive an event from the control socket.

:param stem.response.ControlMessage event_message: message received from
  the control socket
NrR   )r   event_messages     r[   _handle_eventBaseController._handle_eventA  s     	rZ   c                     U R                  5         U R                  [        R                  5        U R	                  5         SU l        g NF)r   _notify_status_listenersStater	   r   r   r   s    r[   r   BaseController._connectL  s4    !!%**-"DrZ   c                 x   U R                   R                  5         SU l        U R                  U R                  4 HN  nU(       d  M  UR                  5       (       d  M#  [        R                  " 5       U:w  d  M>  UR                  5         MP     U R                  [        R                  5        U R                  5         g r  )r   setr   r   r   r   r   r   r   r  r  r   r   r   s     r[   r   BaseController._closeR  s    
 	"D !!4#5#56	
qzz||	 8 8 :a ?	 7 	!!%,,/rZ   c                     SU l         g )NT)r   r   s    r[   r   #BaseController._post_authenticationd  s     "DrZ   c           	         U R                   R                  5          U R                     SnU[        R                  [        R
                  4;   a  SnOU[        R                  :X  a  Sn[        R                  " 5       nUb%  X R                  5       :w  a   SSS5        SSS5        g[        [        S U R                  5      5      U l        U R                   Ho  u  pEU(       aZ  XU4n[        R                  " XFSU-  S9nUR                  S5        UR!                  5         U R                  R#                  U5        Mf  U" XU5        Mq     SSS5        SSS5        g! , (       d  f       N= f! , (       d  f       g= f)z}
Informs our status listeners that a state change occurred.

:param stem.control.State state: state change that has occurred
NTFc                 "    U R                  5       $ r   )r   )r   s    r[   <lambda>9BaseController._notify_status_listeners.<locals>.<lambda>  s
    1::<rZ   z%s notification)targetry   name)r   _get_send_lockr   r  r	   r
   r   timer   listfilterr   r   r   Thread	setDaemonstartr   )r   stateexpect_alivechange_timestampr   r   ry   notice_threads           r[   r  'BaseController._notify_status_listenersi  s(    
	$	$	&&& UZZ--,ell",99;#(G
% ' 
'	&* &*&1GIcIc*d%e"#55OH!12D%,,hTehmTmnM##D)!&&--m<T"23  6- ' 
'	&&& 
'	&s0   E+A,EE+%B$E	E+
E(	$E++
E9c                    U R                   R                  5          U R                  (       a  U R                  R                  5       (       dY  [        R
                  " U R                  SS9U l        U R                  R                  S5        U R                  R                  5         U R                  (       a  U R                  R                  5       (       dY  [        R
                  " U R                  SS9U l	        U R                  R                  S5        U R                  R                  5         SSS5        g! , (       d  f       g= f)ze
Initializes daemon threads. Threads can't be reused so we need to recreate
them if we're restarted.
zTor listener)r  r  TzEvent notifierN)r   r  r   r   r   r   _reader_loopr!  r"  r   _event_loopr   s    r[   r   BaseController._launch_threads  s     
	$	$	&  (;(;(D(D(F(F'..8I8IR`a%%d+!!#t'9'9'B'B'D'D&--t7G7GP`a$$T*  " 
'	&	&s   DD77
Ec                    U R                  5       (       a   U R                  R                  5       n[        R                  " 5       U l        UR                  5       S   S   S:X  a6  U R                  R                  U5        U R                  R                  5         OU R                  R                  U5         U R                  5       (       a  M  gg! [        R                   a%  nU R                  R                  U5         SnANMSnAff = f)a	  
Continually pulls from the control socket, directing the messages into
queues based on their type. Controller messages come in two varieties...

* Responses to messages we've sent (GETINFO, SETCONF, etc).
* Asynchronous events, identified by a status code of 650.
r   650N)r   r   recvr  r   contentr   putr   r  r   r   r   )r   control_messager   s      r[   r)  BaseController._reader_loop  s     --//#,,++-#yy{""$R(+u4





0



 
 
" 




0 --// !! # 	c""#s   BC C D	$DD	c                 
   Sn  U R                   R                  5       nU R                  U5        U R                   R                  5         U R	                  5       (       d>  U(       d  [
        R
                  " 5       nO![
        R
                  " 5       U-
  [        :  a  gM  ! [        R                   aO    U R	                  5       (       d   gU R                  R                  S5        U R                  R                  5          Ndf = f)z
Continually pulls messages from the _event_queue and sends them to our
handle_event callback. This is done via its own thread so subclasses with a
lengthy handle_event implementation don't block further reading from the
socket.
N皙?)r   r   r
  	task_doner   r  EVENTS_LISTENING_TIMEOUTr   r   r   waitclear)r   socket_closed_atr	  s      r[   r*  BaseController._event_loop  s     
#))446=)##% }}!#yy{yy{--0HH  [[ #}}
%  "#s   A6B < B )D
5DD)r   r   r   r   r   r   r   r   r   r   r   r   r   r   NF)T)rT   rU   rV   rW   rX   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r
  r   r   r   r  r   r)  r*  rY   rR   rZ   r[   r   r      sz    $"LQf#	'*@& 7<,		#$"
*4X#(#:#rZ   r   c                     ^  \ rS rSrSr\SSS j5       r\STS j5       rSUU 4S jjrU 4S jr	S r
S	 r\" 5       \S4S
 j5       r\" 5       \4S j5       r\" 5       \4S j5       r\" 5       \4S j5       r\" 5       \4S j5       r\" 5       \4S j5       r\4S jr\" 5       \4S j5       r\" 5       \4S j5       r\" 5       \4S j5       r\" 5       \4S j5       r\" 5       \4S j5       rS r\" 5       S\4S j5       r\" SS9\4S j5       r\" 5       S\4S j5       r\" SS9\4S j5       rS r\" 5       S\4S j5       r \" SS9\4S  j5       r!\" 5       \SSS4S! j5       r"\S4S" jr#\S4S# jr$S$ r%\" 5       \4S% j5       r&S& r'S' r(S( r)SUS) jr*\" 5       \4S* j5       r+S+ r,SVS, jr-SWS- jr.\" 5       \SS4S. j5       r/SXS/ jr0S0 r1S1 r2S2 r3SWS3 jr4SWS4 jr5SWS5 jr6S6 r7S7 r8S8 r9S9 r:S: r;SUS; jr<S< r=S= r>\" 5       \4S> j5       r?\" 5       \4S? j5       r@SYS@ jrASZSA jrBSB rCS[SD jrD\" 5       \4SE j5       rESWSF jrF\GR                  R                  SC4SG jrJSH rKSI rLSJ rM\" 5       \S4SK j5       rNSL rOSM rPSN rQU 4SO jrRSP rSSQ rTSRrUU =rV$ )\
Controlleri  z
Connection with Tor's control socket. This is built on top of the
BaseController and provides a more user friendly API for library users.
c                    SSK nUR                  R                  R                  U 5      (       d  [	        SU -  5      eUS:w  a8  UR                  R                  R                  U5      (       d  [	        SU-  5      eUS:X  a  UR                  R                  U 5      nOUR                  R                  X5      n[        U5      $ )a#  
Constructs a :class:`~stem.socket.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.

.. versionchanged:: 1.5.0
   Use both port 9051 and 9151 by default.

:param str address: ip address of the controller
:param int port: port number of the controller

:returns: :class:`~stem.control.Controller` attached to the given port

:raises: :class:`stem.SocketError` if we're unable to establish a connection
r   NzInvalid IP address: %srv   zInvalid port: %s)
stem.connectionr   
connectionis_valid_ipv4_address
ValueErroris_valid_port_connection_for_default_portsocketControlPortr>  )rK   portr   control_ports       r[   	from_portController.from_port  s    ( 9955g>>/'9::		499#7#7#E#Ed#K#K)D011y__AA'Jl[[,,W;ll##rZ   c                 V    [         R                  R                  U 5      n[        U5      $ )a   
Constructs a :class:`~stem.socket.ControlSocketFile` based Controller.

:param str path: path where the control socket is located

:returns: :class:`~stem.control.Controller` attached to the given socket file

:raises: :class:`stem.SocketError` if we're unable to establish a connection
)r   rF  ControlSocketFiler>  )rn   r   s     r[   from_socket_fileController.from_socket_file  s#     [[2248Nn%%rZ   Fc                   >^  ST l         0 T l        ST l        [        R                  " 5       T l        0 T l        [        R                  " 5       T l        / T l        S T l	        S T l
        S T l        [        [        T ];  X5        U 4S jnT R                  U[         R"                  5        U 4S jnT R                  U[         R$                  5        U 4S jnT R                  U[         R&                  5        g )NTr   c                    > U R                   [        R                  :X  a0  TR                  5         TR	                  [
        R                  5        g g r   )signalr   RELOADclear_cacher  r  r
   r   r   s    r[   _sighup_listener-Controller.__init__.<locals>._sighup_listener/  s6    		&%%ekk2 
'rZ   c                 L  > TR                  5       (       a  [        S U R                  R                  5        5       5      n[        S U R                   5       5      n0 nUR                  U5        UR                  U5        TR                  US5        TR                  U5        g g )Nc              3   J   #    U  H  u  pUR                  5       U4v   M     g 7fr   r   .0kvs      r[   	<genexpr>EController.__init__.<locals>._confchanged_listener.<locals>.<genexpr>8  s     Q;P41A;P   !#c              3   D   #    U  H  oR                  5       / 4v   M     g 7fr   rZ  )r\  r]  s     r[   r_  r`  9  s     C{!wwy"o{s    getconf)is_caching_enabledr   changeditemsunsetupdate
_set_cache_confchanged_cache_invalidation)r   to_cache_changedto_cache_unsetto_cacher   s       r[   _confchanged_listener2Controller.__init__.<locals>._confchanged_listener6  s    		 	 	"	"Q5==;N;N;PQQCu{{CC()'),,,X6 
#rZ   c                    > U R                   S;   a/  TR                  SS 05        TR                  SS 0S5        S Tl        g g )N)EXTERNAL_ADDRESSDNS_USELESSexit_policyrK   getinfo)actionri  _last_address_excrU  s    r[   _address_changed_listener6Controller.__init__.<locals>._address_changed_listenerE  sA    	<	<-.D)95!% 
=rZ   )_is_caching_enabled_request_cache_last_newnymr   r   _cache_lock_event_listeners_event_listeners_lock_enabled_features_is_geoip_unavailablerv  _last_fingerprint_excsuperr>  r   add_event_listener	EventTyper$   r   r'   )r   r   r   rV  rn  rw  	__class__s   `     r[   r   Controller.__init__  s    #DDD (D D!*!2DD!%D!D!%D	*d$^F3
 	,i.>.>?7 	193I3IJ& 	5y7N7NOrZ   c                 J   > U R                  5         [        [        U ]  5         g r   )rT  r  r>  r   )r   r  s    r[   r   Controller.closeM  s    	*d!#rZ   c                 L    SSK nUR                  R                  " U /UQ70 UD6  g)z{
A convenience method to authenticate the controller. This is just a
pass-through to :func:`stem.connection.authenticate`.
r   N)r@  rA  authenticate)r   ry   r~   r   s       r[   r  Controller.authenticateQ  s#     OO  777rZ   c                     U R                      U R                  5         U R                  5         U R                  " U0 UD6  SSS5        g! , (       d  f       g= f)z
Reconnects and authenticates to our control socket.

.. versionadded:: 1.5.0

:raises:
  * :class:`stem.SocketError` if unable to re-establish socket
  * :class:`stem.connection.AuthenticationFailure` if unable to authenticate
N)r   r   rT  r  )r   ry   r~   s      r[   	reconnectController.reconnectZ  s=     

lln

(( 
s   3A		
Ac                 2   [         R                   " 5       n0 n[        R                  R                  U5      (       a  Sn[	        U/5      nOU(       d  0 $ Sn[	        U5      nU H  nUR                  S5      (       a1  US:w  a+  U R                  5       (       a  [        R                  " S5      eUS:X  a  U R                  (       a  U R                  eUS:X  d  Mu  U R                  (       d  M  U R                  SS	5      b  M  U R                  e   U Vs/ s H  owR                  5       PM     nnU R                  US
5      n	U	 H%  n
[        X5      nX   X['   UR                  U5        M'     U(       df  [        (       a6  [         R"                  " SSR%                  UR'                  5       5      -  5        U(       a  U$ [)        UR+                  5       5      S   $  U R-                  SSR%                  U5      -  5      n[        R.                  R1                  SU5        UR3                  U5        [        R4                  R7                  5       (       a6  U(       d/  [9        S UR:                  R=                  5        5       5      Ul        UR?                  UR:                  5        U RA                  5       (       a}  0 nUR:                  R=                  5        HK  u  pU
R                  5       n
U
[B        ;   d
  U
[D        ;   a  XU
'   M/  U
R                  S5      (       d  MG  XU
'   MM     U RG                  US
5        SU;   a  S	U l        SU;   a  S	U l	        [         RH                  " SSR%                  U5      [         R                   " 5       U-
  4-  5        U(       a  U$ [)        UR+                  5       5      S   $ s  snf ! [        RJ                   aL  nSU;   a  Xl        SU;   a  Xl	        [         RH                  " SSR%                  U5      < SU< S35        e S	nAff = f)a  
get_info(params, default = UNDEFINED, get_bytes = False)

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

.. versionchanged:: 1.1.0
   Added the get_bytes argument.

.. versionchanged:: 1.7.0
   Errors commonly provided a :class:`stem.ProtocolError` when we should
   raise a :class:`stem.OperationFailed`.

:param str,list params: GETINFO option or options to be queried
:param object default: response if the query fails
:param bool get_bytes: 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:
  * :class:`stem.ControllerError` if the call fails and we weren't
    provided a default response
  * :class:`stem.InvalidArguments` if the 'params' requested was
    invalid
  * :class:`stem.ProtocolError` if the geoip database is unavailable
FTzip-to-country/ip-to-country/0.0.0.0z!Tor geoip database is unavailablerK   rN   ORPortNrt  zGETINFO %s (cache fetch) r   z
GETINFO %sGETINFOc              3   |   #    U  H2  u  pU[         R                  R                  R                  U5      4v   M4     g 7fr   )r   r   	str_tools_to_unicoder[  s      r[   r_  &Controller.get_info.<locals>.<genexpr>  s.     oVnFQDII$7$7$C$CA$F GVns   :<zGETINFO %s (runtime: %0.4f)zGETINFO 
 (failed: ))&r  r   r   _is_strr  r   is_geoip_unavailabler   rv  r  get_confr   _get_cache_map_case_insensitive_lookupremoveLOG_CACHE_FETCHESr   tracer   r   r  valuesr   r   convert_assert_matchesprereqis_python_3r   entriesrf  rh  rd  CACHEABLE_GETINFO_PARAMS&CACHEABLE_GETINFO_PARAMS_UNTIL_SETCONFri  debugr   )r   paramsrv   	get_bytes
start_timereplyis_multipleparam
from_cachecached_resultsr   user_expected_keyr   rm  r  r   s                   r[   get_infoController.get_infoj  sO   H JEyy  kF8}f	k6{f			*	+	+9P0PUYUnUnUpUp  !DEEI$"8"8$$$M!d&@&@&@T]]S[]aEbEj(((  .44VE++-VJ4((Y?N26?!/!4emm%&  				,sxx

/EEF	ELLN#A&&-,&)99:h
mmIx0v& 
	 	 	"	"9oV^VfVfVlVlVnooll8##$		 	 	"	""**002JC		#,,7]0]!SM~~.//!SM 3 	),	f	!%	&	 %)"	ii-&1A499;Q[C[0\\]	ELLN#A&&m 5n  	f	!$	&	 %("	iiSXXf-=sCDs-   N1D<N6 A<N6 N6 6P
APPc                     U R                  S5      nU(       d^  U R                  S5      n[        R                  R	                  UR                  S5      (       a  USS OU5      nU R                  SU05        U$ )a  
get_version(default = UNDEFINED)

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

:param object default: response if the query fails

:returns: :class:`~stem.version.Version` of the tor instance that we're
  connected to

:raises:
  * :class:`stem.ControllerError` if unable to query the version
  * **ValueError** if unable to parse the version

  An exception is only raised if we weren't provided a default response.
rL   zTor    N)
_get_cacher  r   rL   Versionr   ri  )r   rv   rL   version_strs       r[   get_versionController.get_version  sf    ( ooi(GMM),k$$8N8Nv8V8V[_\ghg
ooy'*+NrZ   c                    U R                  S5      nU(       dP   [        R                  R                  " U R	                  S5      R                  5       6 nU R                  SU05        U$ U$ ! [        R                   a    / nU R                  S5      S:X  a  UR                  S5        U R                  S5      S:X  a  UR                  S5        U R                  S	S
S9 H  nX4R                  S5      -  nM     X0R	                  S5      R                  S5      -  n[        R                  R                  X0R	                  SS5      5      n U$ f = f)am  
get_exit_policy(default = UNDEFINED)

Effective ExitPolicy for our relay.

.. versionchanged:: 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. (:trac:`25739`)

:param object default: response if the query fails

:returns: :class:`~stem.exit_policy.ExitPolicy` of the tor instance that
  we're connected to

:raises:
  * :class:`stem.ControllerError` if unable to query the policy
  * **ValueError** if unable to parse the policy

  An exception is only raised if we weren't provided a default response.
rs  zexit-policy/full	ExitRelay0z
reject *:*ExitPolicyRejectPrivate1zreject private:*
ExitPolicyTmultiple,rM   rK   N)r  r   rs  r  r  
splitlinesri  OperationFailedr  r   splitget_config_policy)r   rv   policyrulespolicy_lines        r[   get_exit_policyController.get_exit_policy  s0   0 __]+F"[!!,,dmm<N.O.Z.Z.\]/0D M6MC !! [$ ==%,
,,|
$==23s:
,,)
*==$=GK
$$S)
)% H 	45;;C@@!!33E==TX;YZMC[s   AA+ +CEEc                    ^ U4S jnU R                  T5       VVs/ s H  u  pEU" U5      (       d  M  UPM     snn$ s  snnf )a  
get_ports(listener_type, default = UNDEFINED)

Provides the local ports where tor is listening for the given type of
connections. This is similar to
:func:`~stem.control.Controller.get_listeners`, but doesn't provide
addresses nor include non-local endpoints.

.. versionadded:: 1.2.0

:param stem.control.Listener listener_type: connection type being handled
  by the ports we return
:param object default: response if the query fails

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

:raises: :class:`stem.ControllerError` if unable to determine the ports
  and no default was provided
c                   > [         R                  R                  R                  U 5      (       a  U S:H  =(       d    U R	                  S5      $ [         R                  R                  R                  U 5      (       a,  [         R                  R                  R                  U 5      S;   $ [        R                  " ST< SU < 35        g)Nz0.0.0.0z127.)z'0000:0000:0000:0000:0000:0000:0000:0000z'0000:0000:0000:0000:0000:0000:0000:0001zRequest for z3 ports got an address that's neither IPv4 or IPv6: F)	r   r   rA  rB  r   is_valid_ipv6_addressexpand_ipv6_addressr   r   )rK   listener_types    r[   r   *Controller.get_ports.<locals>.is_localhost[  s    				3	3G	<	<)#Aw'9'9&'AA9955g>>yy##77@ E
 
 	

 	ZgipqrrZ   )get_listeners)r   r  rv   r   addrrH  s    `    r[   	get_portsController.get_portsD  s9    .
 &*%7%7%F]%F\d,W[J\D%F]]]s   ==c                    U R                  US5      nUGc  / nSUR                  5       -  n U R                  U5      R                  5        H  nUR	                  S5      (       a  UR                  S5      (       d  [        R                  " SU< SU< 35      eSU;  a  [        R                  " SU< SU< 35      eUSS	 nUR                  SS5      u  pxUS
:X  a  M  UR	                  S5      (       a  UR                  S5      (       a  USS	 nUR                  Xx45        M     U H  u  px[        R(                  R*                  R-                  U5      (       dL  [        R(                  R*                  R/                  U5      (       d  [        R                  " SU< SU< 35      e[        R(                  R*                  R1                  U5      (       a  M  [        R                  " S U< SU< 35      e   U VVs/ s H  u  pxU[3        U5      4PM     nnnU R5                  X0S5        U$ ! [        R                   Ga    [        R                  S[        R                  S[        R                  S[        R                  S[        R                   S[        R"                  S[        R$                  S0U   n	[        R                  S[        R                  S[        R                  S[        R                  S[        R                   S[        R"                  S[        R$                  S0U   n
U R'                  U	5      R                  5       S   nU R'                  U
SS9 Ht  nSU;   aY  UR                  SS5      u  pxUR	                  S5      (       a  UR                  S5      (       a  USS	 nUR                  Xx45        Mb  UR                  Xk45        Mv      GNf = fs  snnf )!a  
get_listeners(listener_type, default = UNDEFINED)

Provides the addresses and ports where tor is listening for connections of
the given type. This is similar to
:func:`~stem.control.Controller.get_ports` but includes listener addresses
and non-local endpoints.

.. versionadded:: 1.2.0

.. versionchanged:: 1.5.0
   Recognize listeners with IPv6 addresses.

:param stem.control.Listener listener_type: connection type being handled
  by the listeners we return
:param object default: response if the query fails

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

:raises: :class:`stem.ControllerError` if unable to determine the listeners
  and no default was provided
	listenersznet/listeners/%s"z	'GETINFO z'' responses are expected to be quoted: :z"' had a listener without a colon: ru   r-  unix[]r  DirPort	SocksPort	TransPortNatdPortDNSPortrG  ORListenAddressDirListenAddressSocksListenAddressTransListenAddressNatdListenAddressDNSListenAddressControlListenAddressr   Tr  zInvalid address for a z listener: zInvalid port for a )r  r   r  r  r   endswithr   r   rsplitr   InvalidArgumentsListenerr-   r.   r/   r0   r1   r2   r3   r  r   rA  rB  r  rD  intri  )r   r  rv   r  proxy_addrsqueryr   r  rH  port_optionlistener_option
port_values               r[   r  Controller.get_listenersi  s9   4 {;Ik =#6#6#88e;7e,224H%%c**x/@/@/E/E$$_dfn%opp("$$Z_ai%jkka^(sA.*$ V^__S!!dmmC&8&8":D


d\
*+ 5| $*$yy##99$??		H\H\HrHrswHxHx""m]a#bc
c%%33D99""=Z^#_`
`	 $ :EE$D#d)$iE
oo}0+>c "" $7 ++x
,,	
..+
..+
--
,,	


M
  ++(
,,*
...
...
--,
,,*


2
  ]];/557:
o$GHH_!a0JDs##c(:(:!BZd|,56 H7$7\ Fs   C8H, ;O,F)OOc                    U R                  S5      S:w  a  [        R                  " S5      e[        R                  " 5       nU R                  S5      nU R                  S5      nU R                  S5      nU R                  S5      n[        R                  R
                  R                  U5      nUR                  SS	5       Vs/ s H  n[        U5      PM     snu  pUR                  SS	5       Vs/ s H  n[        U5      PM     snu  p[        UUU[        S
[        R                  " UR                  5       5      [        U5      -
  5      UU
X-   U	UX-   S9
$ s  snf s  snf )a  
get_accounting_stats(default = UNDEFINED)

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

.. versionadded:: 1.3.0

:param object default: response if the query fails

:returns: :class:`~stem.control.AccountingStats` with our accounting stats

:raises: :class:`stem.ControllerError` if unable to determine the listeners
  and no default was provided
rO   r  zAccounting isn't enabledzaccounting/hibernatingzaccounting/interval-endzaccounting/byteszaccounting/bytes-leftr  ru   r   r\   )r  r   r   r  r   r  _parse_timestampr  r  rQ   maxcalendartimegm	timetuple)r   rv   r]   r^   r_   usedleftr   	used_readused_written	left_readleft_writtens               r[   get_accounting_statsController.get_accounting_stats  s6   $ }})*c1  !;<<		I]]34F==!:;L==+,D==01D99&&77EL37::c13EF3ECs3x3EFI37::c13EF3ECs3x3EFI!Q0F0F0H ICPYN Z[!("% /  GFs   E0Ec                 B    U R                  [        R                  U5      $ )a  
Provides the SOCKS **(address, port)** tuples that tor has open.

.. deprecated:: 1.2.0
   Use :func:`~stem.control.Controller.get_listeners` with
   **Listener.SOCKS** instead.

:param object default: response if the query fails

:returns: list of **(address, port)** tuples for the available SOCKS
  listeners

:raises: :class:`stem.ControllerError` if unable to determine the listeners
  and no default was provided
)r  r  r/   r   rv   s     r[   get_socks_listenersController.get_socks_listeners  s    " hnng66rZ   c                 @    SSK nUR                  R                  U 5      $ )a  
get_protocolinfo(default = UNDEFINED)

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

:param object default: response if the query fails

:returns: :class:`~stem.response.protocolinfo.ProtocolInfoResponse` provided by tor

:raises:
  * :class:`stem.ProtocolError` if the PROTOCOLINFO response is
    malformed
  * :class:`stem.SocketError` if problems arise in establishing or
    using the socket

  An exception is only raised if we weren't provided a default response.
r   N)r@  rA  get_protocolinfo)r   rv   r   s      r[   r
  Controller.get_protocolinfo  s    ( ??++D11rZ   c                    U R                  S5      nU(       a  U$ U R                  SS5      nU(       dV  U R                  5       (       aA  U R                  S5      nU(       a)  [        R
                  R                  R                  U5      nU(       a  U R                  SU05        U$ [        U R                  5       (       a  S5      eS5      e)aL  
get_user(default = UNDEFINED)

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.

.. versionadded:: 1.1.0

:param object default: response if the query fails

:returns: str with the username tor is running as
userzprocess/userNzUnable to resolve tor's userTor isn't running locally)
r  r  r   get_pidr   r   systemr  ri  rC  )r   rv   r  pids       r[   get_userController.get_user)  s      ??6"Dk==.DD%%''LLc	yy$$S)
oovtn%k9J9J9L9L5nnRmnnrZ   c                 Z   U R                  S5      nU(       a  U$ U R                  SS5      nU(       a   UR                  5       (       a  [        U5      nU(       Gd}  U R	                  5       (       Gag  U R                  SS5      nUbR  [        U5       nUR                  5       R                  5       nUR                  5       (       a  [        U5      nSSS5        U(       d)  [        R                  R                  R                  S5      nU(       d  U R                  5       n[        U[        R                  R                   5      (       a4  [        R                  R                  R#                  UR$                  5      nO\[        U[        R                  R&                  5      (       a3  [        R                  R                  R)                  UR*                  5      nU(       a  U R-                  SU05        U$ [/        U R	                  5       (       a  S5      eS5      e! , (       d  f       GNQ= f)a  
get_pid(default = UNDEFINED)

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.

.. versionadded:: 1.1.0

:param object default: response if the query fails

:returns: **int** for tor's pid

:raises: **ValueError** if unable to determine the pid and no default was
  provided
r  zprocess/pidNr?   torzUnable to resolve tor's pidr  )r  r  isdigitr  r   r  openreadstripr   r   r  pid_by_namer   r   rF  rG  pid_by_portrH  rM  pid_by_open_filern   ri  rC  )r   rv   r  getinfo_pidpid_file_pathpid_filepid_file_contentsr   s           r[   r  Controller.get_pidL  s   & //%
 C
j--t4K{**,,c4$$&&mmIt4m		"- H&mmo335
&&(('(C	 ! ii**51*ndkk&=&=>>		  ,,^-@-@A#(E(EFF		  11.2E2EF#

ooucl#j8I8I8K8K4mmQlmm+ ! s   ?H
H*c                    U R                  S5      nU(       a  U$ U R                  5       [        R                  R                  R
                  :  a]  U R                  SS5      nU(       aD  UR                  5       (       d  [        SU-  5      e[        R                  " 5       [        U5      -
  nU(       d  U R                  5       (       al  U R                  5       (       d  [        S5      eU R                  S5      nU(       d  [        S5      e[        R                  R                  R                  U5      nU(       a  U R!                  SU05        U$ [        U R                  5       (       a  S5      eS5      e)	aG  
get_start_time(default = UNDEFINED)

Provides when the tor process began.

.. versionadded:: 1.8.0

:param object default: response if the query fails

:returns: **float** for the unix timestamp of when the tor process began

:raises: **ValueError** if unable to determine when the process began and
  no default was provided
r  uptimeNz='GETINFO uptime' did not provide a valid numeric response: %sz>Unable to determine the uptime when tor is not running locallyz.Unable to determine the pid of the tor processz Unable to resolve when tor beganr  )r  r  r   rL   RequirementGETINFO_UPTIMEr  r  rC  r  floatr   r  r   r  r  ri  )r   rv   r  r#  r  s        r[   get_start_timeController.get_start_time  s$   " .JT\\55DDD}}Xt,f	~~Z]ccd
dYY[5=0
$++--   YZZLLcIJJ99##..s3j
oo|Z01T=N=N=P=P9rrVqrrrZ   c                 N    [         R                   " 5       U R                  5       -
  $ )aH  
get_uptime(default = UNDEFINED)

Provides the duration in seconds that tor has been running.

.. versionadded:: 1.8.0

:param object default: response if the query fails

:returns: **float** for the number of seconds tor has been running

:raises: **ValueError** if unable to determine the uptime and no default
  was provided
)r  r'  r  s     r[   
get_uptimeController.get_uptime  s    " 99;,,...rZ   c                 .   Su  pU R                  SS5      S:X  a  SnU R                  SS5      (       aX  U(       d'  U R                  SS9nU=(       a    SUR                  ;   nU R                  S5      nU=(       a    UR	                  5       n[        X5      $ )	a#  
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.

.. versionadded:: 1.5.0

:returns: :class:`~stem.cotroller.UserTrafficAllowed` with **inbound** and
  **outbound** boolean attributes to indicate if we're likely servicing
  direct user traffic
)FFBridgeRelayNr  Tr  )rv   Guard)r  get_network_statusflagsr  is_exiting_allowedrh   )r   inbound_allowedoutbound_allowedconsensus_entryrs  s        r[   is_user_traffic_allowed"Controller.is_user_traffic_allowed  s    4 )5%O}}]D)S0o}}Xt$$11D1A)Ng9N9N.N((.k$I)G)G)Io@@rZ   Nc                    Uc   U R                  S5      n[        R                  R                  R                  U5      (       a  SU-  nOB[        R                  R                  R                  U5      (       a  SU-  nO[        SU-  5      e U R                  USS9nU(       d  [        R                  " S5      e[        R                  R                  R                  U5      $ ! [        R                   a  n[        R                  " SU-  5      eSnAff = f! [        R                   a>  n[        U5      R                  S	5      (       a  [        R                  " S
U-  5      ee SnAff = f)a  
get_microdescriptor(relay = None, default = UNDEFINED)

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.

.. versionchanged:: 1.3.0
   Changed so we'd fetch our own descriptor if no 'relay' is provided.

:param str relay: fingerprint or nickname of the relay to be queried
:param object default: response if the query fails

:returns: :class:`~stem.descriptor.microdescriptor.Microdescriptor` for the given relay

:raises:
  * :class:`stem.DescriptorUnavailable` if unable to provide a descriptor
    for the given relay
  * :class:`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.
NrN   +Unable to determine our own fingerprint: %szmd/id/%sz
md/name/%s*'%s' isn't a valid fingerprint or nicknameTr  0GETINFO request contained unrecognized keywords:1Tor was unable to provide the descriptor for '%s'HDescriptor information is unavailable, tor might still be downloading it)r  r   r   r   	tor_toolsis_valid_fingerprintis_valid_nicknamerC  r  strr   DescriptorUnavailable
descriptormicrodescriptorMicrodescriptorr   relayrv   r   r  desc_contents         r[   get_microdescriptorController.get_microdescriptor  s>   @ }Xm, yy//665 e				.	.u	5	5U"eCeKLL]]5d];l &&'qrr??**::<HH+ !! X""#PSV#VWWX    	S		O	P	P(()\_d)dee	/   C# D #D7DDE*,9E%%E*T)r   c              #     #    U R                  5       [        R                  R                  R                  :  av  U R                  SSS9nU(       d  [        R                  " S5      e[        R                  R                  R                  [        R                  " U5      5       H  nUv   M	     gU R                  SS5      nUc  [        R                  " SS9e[        R                  R!                  U5      (       d  [        R                  " S	U-  S9eSnS
 HJ  n[        R                  R#                  XF5      n[        R                  R!                  U5      (       d  MH  Un  O   Uc  [        R                  " SU-  S9e[        R                  R%                  U5       HZ  n['        U[        R                  R                  R(                  5      (       d   [        R                  " S[+        U5      -  S9eUv   M\     g7f)a  
get_microdescriptors(default = UNDEFINED)

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.

:param list default: items to provide if the query fails

:returns: iterates over
  :class:`~stem.descriptor.microdescriptor.Microdescriptor` for relays in
  the tor network

:raises: :class:`stem.ControllerError` if unable to query tor and no
  default was provided
zmd/allTr:  r=  r8   Nz(Unable to determine tor's data directoryr   z1Data directory reported by tor doesn't exist (%s))zcached-microdescszcached-microdescs.newz;Data directory doesn't contain cached microdescriptors (%s)z@BUG: Descriptor reader provided non-microdescriptor content (%s))r  r   rL   r$  GETINFO_MICRODESCRIPTORSr  rB  rC  rD  _parse_fileioBytesIOr  r  r   rn   existsr   
parse_filer   rE  type)r   rv   rH  descdata_directorymicrodescriptor_filefilenamecached_descriptorss           r[   get_microdescriptorsController.get_microdescriptors-  s    . T\\55NNN]]8]>l(()stt//11==bjj>VW$
 X
 }}_d;n		""-WXXWW^^N++""-`cq-qrr!D(WW\\.C77>>,--!3

 E 
	%""-jm{-{||//,,-AB$ $ ? ? O OPP$$/qtxy}t~/~

 Cs   EG=BG=c                 0    Uc   U R                  S5      n[        R                  R                  R                  U5      (       a  SU-  nOB[        R                  R                  R                  U5      (       a  SU-  nO[        SU-  5      e U R                  USS9nU(       d  [        R                  " S5      e[        R                  R                  R                  U5      $ ! [        R                   a  n[        R                  " SU-  5      eSnAff = f! [        R                   a>  n[        U5      R                  S	5      (       a  [        R                  " S
U-  5      ee SnAff = f!   U R                  5       (       d  [        [         5      ee = f)a}  
get_server_descriptor(relay = None, default = UNDEFINED)

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

.. versionchanged:: 1.3.0
   Changed so we'd fetch our own descriptor if no 'relay' is provided.

:param str relay: fingerprint or nickname of the relay to be queried
:param object default: response if the query fails

:returns: :class:`~stem.descriptor.server_descriptor.RelayDescriptor` for the given relay

:raises:
  * :class:`stem.DescriptorUnavailable` if unable to provide a descriptor
    for the given relay
  * :class:`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.
NrN   r8  z
desc/id/%szdesc/name/%sr9  Tr:  r;  r<  r=  )r  r   r   r   r>  r?  r@  rC  r  rA  r   rB  rC  server_descriptorRelayDescriptor _is_server_descriptors_availableSERVER_DESCRIPTORS_UNSUPPORTEDrF  s         r[   get_server_descriptor Controller.get_server_descriptorl  se   J		Z--.% 
			1	1%	8	8u$990077&EMNN}}U}= (()stt__..>>|LL+ ## 	Z$$%RUX%XY
Y	Z "" s8QRR**+^af+fg
g
	2244788sS   E. C$ A6E. D AE. $D8DDE. E+-9E&&E++E. .'Fc              #   T  #    U R                  SSS9nU(       dE  U R                  5       (       d  [        R                  " [        5      e[        R
                  " S5      e[        R                  R                  R                  [        R                  " U5      5       H  nUv   M	     g7f)a  
get_server_descriptors(default = UNDEFINED)

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

:param list default: items to provide if the query fails

:returns: iterates over
  :class:`~stem.descriptor.server_descriptor.RelayDescriptor` for relays in
  the tor network

:raises: :class:`stem.ControllerError` if unable to query tor and no
  default was provided
zdesc/all-recentTr:  r=  N)r  r_  r   r   r`  rB  rC  r]  rO  rP  rQ  )r   rv   rH  rU  s       r[   get_server_descriptors!Controller.get_server_descriptors  s~     8 ==!2=EL2244""#ABB(()stt11==bjj>VWj Xs   B&B(c                     U R                  5       [        R                  R                  R                  :  =(       d    U R                  SS5      S:H  $ )zE
Checks to see if tor server descriptors should be available or not.
UseMicrodescriptorsNr  )r  r   rL   r$  MICRODESCRIPTOR_IS_DEFAULTr  r   s    r[   r_  +Controller._is_server_descriptors_available  sC      8 8 S SS ===.5<=rZ   c                    Uc   U R                  S5      n[        R                  R                  R                  U5      (       a  SU-  nOB[        R                  R                  R                  U5      (       a  SU-  nO[        SU-  5      e U R                  USS9nU(       d  [        R                  " S5      e[        R                  R                  R                  U5      $ ! [        R                   a  n[        R                  " SU-  5      eSnAff = f! [        R                   a>  n[        U5      R                  S	5      (       a  [        R                  " S
U-  5      ee SnAff = f)a  
get_network_status(relay = None, default = UNDEFINED)

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.

.. versionchanged:: 1.3.0
   Changed so we'd fetch our own descriptor if no 'relay' is provided.

:param str relay: fingerprint or nickname of the relay to be queried
:param object default: response if the query fails

:returns: :class:`~stem.descriptor.router_status_entry.RouterStatusEntryV3`
  for the given relay

:raises:
  * :class:`stem.DescriptorUnavailable` if unable to provide a descriptor
    for the given relay
  * :class:`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.
NrN   r8  zns/id/%sz
ns/name/%sr9  Tr:  r;  r<  r=  )r  r   r   r   r>  r?  r@  rC  r  rA  r   rB  rC  router_status_entryRouterStatusEntryV3rF  s         r[   r/  Controller.get_network_status  s>   B }Xm, yy//665 e				.	.u	5	5U"eCeKLL]]5d];l &&'qrr??..BB<PP+ !! X""#PSV#VWWX    	S		O	P	P(()\_d)dee	rK  c              #   >  #    U R                  SSS9nU(       d  [        R                  " S5      e[        R                  R                  R                  [        R                  " U5      S[        R                  R                  R                  S9nU H  nUv   M	     g7f)a  
get_network_statuses(default = UNDEFINED)

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

:param list default: items to provide if the query fails

:returns: iterates over
  :class:`~stem.descriptor.router_status_entry.RouterStatusEntryV3` for
  relays in the tor network

:raises: :class:`stem.ControllerError` if unable to query tor and no
  default was provided
zns/allTr:  r=  F)entry_classN)	r  r   rB  rC  rk  rO  rP  rQ  rl  )r   rv   rH  desc_iteratorrU  s        r[   get_network_statusesController.get_network_statuses   s     . ==t=<L&&'qrrOO77CCjjOO77KK D M j s   BBc           	      H  ^^ UR                  S5      (       a  USS n[        R                  R                  R	                  U5      (       d  [        SU-  5      eU R                  5       [        R                  R                  R                  :  a9  [        R                  " S[        R                  R                  R                  -  S9e[        R                  " 5       Ssmn[        R                  " 5       Ssmn[        R                  " 5       nU(       aL  U4S jnU4S jnU R                  U[        R                   5        U R                  U[        R"                  5         S	U-  n	U(       a+  U	S
S
R%                  U V
s/ s H  n
SU
-  PM
     sn
5      -   -  n	U R'                  U	5      n[        R(                  R+                  SU5        UR-                  5       (       d#  [        R.                  " SUR0                  -  5      eU(       d3   U(       a  U R3                  U5        U(       a  U R3                  U5        gg [5        TXX5      nUR6                  U:X  Ga  UR8                  (       a=  UR8                  U(       a  U R3                  U5        U(       a  U R3                  U5        $ $  [5        TXX5      nUR6                  U:X  a  UR:                  [        R<                  R>                  :X  aw  UR@                  [        RB                  RD                  :X  a  [        RF                  " SU-  5      e[        RF                  " SU< SURH                  < SUR@                  < 35      eM  GM,  s  sn
f ! U(       a  U R3                  U5        U(       a  U R3                  U5        f f = f)a  
get_hidden_service_descriptor(address, default = UNDEFINED, servers = None, await_result = True)

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.** (:trac:`25417`)

.. versionadded:: 1.4.0

.. versionchanged:: 1.7.0
   Added the timeout argument.

:param str address: address of the hidden service descriptor, the '.onion' suffix is optional
:param object default: response if the query fails
:param list servers: requrest the descriptor from these specific servers
:param float timeout: seconds to wait when **await_result** is **True**

:returns: :class:`~stem.descriptor.hidden_service.HiddenServiceDescriptorV2`
  for the given service if **await_result** is **True**, or **None** otherwise

:raises:
  * :class:`stem.DescriptorUnavailable` if **await_result** is **True** and
    unable to provide a descriptor for the given service
  * :class:`stem.Timeout` if **timeout** was reached
  * :class:`stem.ControllerError` if unable to query the descriptor
  * **ValueError** if **address** doesn't conform with the pattern of a
    hidden service address

  An exception is only raised if we weren't provided a default response.
.onionNiz/'%s.onion' isn't a valid hidden service addressz#HSFETCH was added in tor version %srM  c                 (   > TR                  U 5        g r   r1  r   hs_desc_queues    r[   hs_desc_listenerBController.get_hidden_service_descriptor.<locals>.hs_desc_listenery      % rZ   c                 (   > TR                  U 5        g r   rv  )r   hs_desc_content_queues    r[   hs_desc_content_listenerJController.get_hidden_service_descriptor.<locals>.hs_desc_content_listener|  s    !!%(rZ   z
HSFETCH %sr  z	SERVER=%s
SINGLELINEz-HSFETCH returned unexpected response code: %sz%No running hidden service at %s.onionz&Unable to retrieve the descriptor for z.onion (retrieved from ): )%r  r   r   r>  is_valid_hidden_service_addressrC  r  rL   r$  HSFETCHUnsatisfiableRequestr   r   r  r  r  r   r   r   r   r   r  is_okr   coderemove_event_listener_get_with_timeoutrK   rC  ru  HSDescActionFAILEDreasonHSDescReason	NOT_FOUNDrB  directory_fingerprint)r   rK   rv   serversawait_resulttimeoutry  r~  r  requestsr   r   r}  rx  s                @@r[   get_hidden_service_descriptor(Controller.get_hidden_service_descriptorE  s   L !!g99>>wGGH7RSSDLL44<<<%%0UX\XdXdXpXpXxXx0xyy&+kkmT#M#6;kkmT33J!) .	0A0AB
6	8Q8QR%=w&g	3G"DGq;?G"DEEE'"h
mmL(3^^  !PS[S`S`!`aa( 
""#34	!""#;< 
"+ #$97O%]]g%%% 
""#34	!""#;< 
" )-M==G+@Q@Q@X@X0X\\T%6%6%@%@@445\_f5fgg44  BI  KP  Kf  Kf  hm  ht  ht  6u  v  v   #E: 
""#34	!""#;< 
"s&   "M. ?M)A;M. <:M. (CM. .3N!c                     UR                  5       R                  5       nU(       d  U[        :w  a  U$ S$ U R                  XU5      n[	        XAU5      $ )a  
get_conf(param, default = UNDEFINED, multiple = False)

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

:param str param: configuration option to be queried
:param object default: response if the option is unset or the query fails
:param bool multiple: 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:
  * :class:`stem.ControllerError` if the call fails and we weren't
    provided a default response
  * :class:`stem.InvalidArguments` if the configuration option
    requested was invalid
N)r   r  r   get_conf_mapr  )r   r  rv   r  r  s        r[   r  Controller.get_conf  sM    R KKM!E9,W6$69G#GG<<rZ   c           	      X  ^ [         R                   " 5       n0 n[        R                  R                  U5      (       a  U/nU Vs/ s H  ofR	                  5       (       d  M  UPM     nnU/ :X  a  0 $ [        U Vs/ s H  n[        R                  Xf5      PM     sn5      nU Vs/ s H  oR                  5       PM     n	nU R                  U	S5      n
U
 H%  n[        X{5      nX   X\'   UR                  U5        M'     U(       dT  [        (       a6  [        R                  " SSR                  UR!                  5       5      -  5        U R#                  UTU5      $  U R%                  SSR                  U5      -  5      n[        R&                  R)                  SU5        UR+                  UR,                  5        U R/                  5       (       a<  [1        S UR,                  R3                  5        5       5      nU R5                  US5        [7        U5       HF  nUR                  5       [        R9                  5       ;  d  M+  [        XU5      nX:w  d  M>  X[   X\'   X[	 MH     [        R:                  " SSR                  U5      [         R                   " 5       U-
  4-  5        U R#                  UTU5      $ s  snf s  snf s  snf ! [        R<                   aX  n[        R:                  " SSR                  U5      < S	U< S
35        T[>        :w  a  [1        U4S jU 5       5      s SnA$ e SnAff = f)a@  
get_conf_map(params, default = UNDEFINED, multiple = True)

Similar to :func:`~stem.control.Controller.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 :func:`~stem.control.Controller.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
:func:`~stem.control.Controller.get_hidden_service_conf` method instead.

:param str,list params: configuration option(s) to be queried
:param object default: value for the mappings if the configuration option
  is either undefined or the query fails
:param bool multiple: 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:
  * :class:`stem.ControllerError` if the call fails and we weren't provided
    a default response
  * :class:`stem.InvalidArguments` if the configuration option requested
    was invalid
rc  zGETCONF %s (cache fetch)r  z
GETCONF %sGETCONFc              3   J   #    U  H  u  pUR                  5       U4v   M     g 7fr   rZ  r[  s      r[   r_  *Controller.get_conf_map.<locals>.<genexpr>0	  s     L3K41A3Kra  zGETCONF %s (runtime: %0.4f)zGETCONF r  r  c              3   *   >#    U  H  oT4v   M
     g 7fr   rR   )r\  r  rv   s     r[   r_  r  L	  s     9&G$&s   N) r  r   r   r  r  r  MAPPED_CONFIG_KEYSr|   r   r  r  r  r  r   r  r   r   _get_conf_dict_to_responser   r   r  rh  r  rd  r   rf  ri  r  r  r  r   r   )r   r  rv   r  r  r  entrylookup_paramsr  r  r  r   r  r   rm  r   s     `             r[   r  Controller.get_conf_map  s   ` JEyy  xf "(9;;=eF9|i 6R6%+//=6RSM .;;]E++-]J;((Y?N2=F!/!4e,-  				,sxx

/EEF,,UGXFF$,-)@@Ah
mmIx0ll8##$		 	 	"	"L83C3C3I3I3KLL), e#yy{077996vCH
%',zE$
  
ii--1H$))+XbJb0ccd,,UGXFFm : S <Z  	iiSXXm-DcJK	I	9&999sK   J. J.9J3#J8C!J= <J= AJ= =L)AL$L)#L$$L)c                     0 n[        UR                  5       5       H:  u  pVU/ :X  a  U[        :w  a  X$U'   M  U(       a  / OSXE'   M*  U(       a  UOUS   XE'   M<     U$ )z
Translates a dictionary of 'config key => [value1, value2...]' into the
return value of :func:`~stem.control.Controller.get_conf_map`, taking into
account what the caller requested.
Nr   )r  rf  r   )r   config_dictrv   r  return_dictr   r  s          r[   r  %Controller._get_conf_dict_to_responseP	  s^     KK--/0	2i$c
#+R+
%-66!9 1 rZ   c                 &    XR                  5       ;   $ )a  
is_set(param, default = UNDEFINED)

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

.. versionadded:: 1.5.0

:param str param: configuration option to check
:param object default: response if the query fails

:returns: **True** if option differs from its default and **False**
  otherwise

:raises: :class:`stem.ControllerError` if the call fails and we weren't
  provided a default response
)_get_custom_options)r   r  rv   s      r[   is_setController.is_sete	  s    & ,,...rZ   c           	      l   U R                  S5      nU(       d  U R                  S5      R                  5       nSSSU R                  S5      -  S4nU H  nXB;   d  M
  UR	                  U5        M     [        U Vs/ s H  oDR                  SS	5      PM     sn5      nU R                  SU05        U$ s  snf )
Nget_custom_optionszconfig-textzLog notice stdoutz Log notice file /var/log/tor/logzDataDirectory /home/%s/.tor	undefinedzHiddenServiceStatistics 0r  ru   )r  r  r  r  r  r   r  ri  )r   resultconfig_linesdefault_lineslines        r[   r  Controller._get_custom_optionsz	  s    __12F]]=1<<>l 	*%k(BB#	m  $


d
#   LALDZZQ'LABf
oo+V45M Bs   :B1c                 *    U R                  X0S5        g)av  
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

:param str param: configuration option to be set
:param str,list value: value to set the parameter to

:raises:
  * :class:`stem.ControllerError` if the call fails
  * :class:`stem.InvalidArguments` if configuration options
    requested was invalid
  * :class:`stem.InvalidRequest` if the configuration setting is
    impossible or if there's a syntax error in the configuration values
FN)set_options)r   r  r  s      r[   set_confController.set_conf	  s    ( 	e^U+rZ   c           	      h    U R                  [        U Vs/ s H  o"S4PM     sn5      S5        gs  snf )a  
Reverts one or more parameters to their default values.

:param str params: configuration option to be reset

:raises:
  * :class:`stem.ControllerError` if the call fails
  * :class:`stem.InvalidArguments` if configuration options requested was invalid
  * :class:`stem.InvalidRequest` if the configuration setting is
    impossible or if there's a syntax error in the configuration values
NT)r  r   )r   r  r  s      r[   
reset_confController.reset_conf	  s-     	Tf=fU4=f=>E=s   /c                    [         R                   " 5       nU(       a  SOS/n[        U[        5      (       a  [        UR	                  5       5      nU H  u  pV[        U[
        5      (       a)  UR                  U< SUR                  5       < S35        MC  [        U[        R                  R                  5      (       a9  UR                  U Vs/ s H  ou< SUR                  5       < S3PM     sn5        M  U(       d  UR                  U5        M  [        SU< SU< S[        U5      R                  < S35      e   S	R                  U5      nU R!                  U5      n	["        R$                  R'                  S
U	5        U	R)                  5       (       a  [*        R,                  " SU[         R                   " 5       U-
  4-  5        U R/                  5       (       a?  [        S U 5       5      n
U R1                  U
S5        U R3                  [        U5      5        gg[*        R,                  " U< SU	R4                  < SU	R6                  < S35        U VVs/ s HH  u  p["        R8                  R:                  R=                  U5      R?                  5       [@        ;   d  MF  UPMJ     nnnU(       a0  ["        RB                  " SSR                  [E        U5      5      -  US9eU	R4                  S:X  a  U	R6                  RG                  S5      (       aV  U	R6                  SU	R6                  RI                  SS5       n["        RB                  " U	R4                  U	R6                  U/5      e["        RJ                  " U	R4                  U	R6                  5      eU	R4                  S;   a+  ["        RJ                  " U	R4                  U	R6                  5      e["        RL                  " SU	R4                  -  5      es  snf s  snnf )a  
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 :func:`~stem.control.Controller.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).

:param dict,list params: mapping of configuration options to the values
  we're setting it to
:param bool reset: issues a RESETCONF, returning **None** values to their
  defaults if **True**

:raises:
  * :class:`stem.ControllerError` if the call fails
  * :class:`stem.InvalidArguments` if configuration options
    requested was invalid
  * :class:`stem.InvalidRequest` if the configuration setting is
    impossible or if there's a syntax error in the configuration values
	RESETCONFSETCONFz="r  zCannot set z to z since the value was a z but we only accept stringsr  r  z%s (runtime: %0.4f)c              3   J   #    U  H  u  pUR                  5       S 4v   M     g 7fr   rZ  r[  s      r[   r_  )Controller.set_options.<locals>.<genexpr>	  s     =fdaD)fra  rc  z (failed, code: z, message: r  z(%s cannot be changed while tor's running, )r   	arguments552z%Unrecognized option: Unknown option '%   ')513553z#Returned unexpected status code: %sN)'r  r   r   r  rf  rA  r   r  collectionsabcIterableextendrC  rT  rT   r   r   r   r   r  r  r   r  rd  ri  rj  r  r   r   r  r  r   IMMUTABLE_CONFIG_OPTIONSr  sortedr   findInvalidRequestr   )r   r  resetr  
query_compr  r  r   r  r   rm  r]  r^  immutable_paramsr   s                  r[   r  Controller.set_options	  s   D J "'+I6J&$FLLN#f	E3		uekkm<=e[__5566uMusyy{;uMN% fkmrtxy~t  uI  uI  J  K  	K  HHZ ExxHMM,1~~	ii%		j0H(IIJ		 	 	"	"=f==),,,T&\:	 
# 
iix}}hN^N^_`(.y$))2E2E2Q2QRS2T2Z2Z2\`x2x!y	##.X[_[d[dekl|e}[~.~  M]  ^  	^	%	&&'NOO  H$4$4$9$9#r$BC#%%hmmX5E5EuM
M!!(--1A1ABB==N*!!(--1A1ABB  !F!VWWC N( zs   !O.
AO3O3c                    U R                  S5      nUb#  [        (       a  [        R                  " S5        U$ [        R                  " 5       n U R                  S5      n[        R                  R                  SU5        [        R                  " S[        R                  " 5       U-
  -  5        [        5       nSnUR                  5        GH  u  pxn	U	S:X  a  M  S	U	;  a  M  U	R                  S	S
5      u  pU
S:X  a
  UnS/ 0X&'   M;  U
S:X  Gaj  U=pSnUR                  5       (       d>  UR                  5       u  pUR                  5       (       a  UnOUR                  SS
5      u  p[        R                   R"                  R%                  U5      (       d  [        R&                  " SU< SU	< 35      e[        R                   R"                  R)                  U5      (       d  [        R&                  " SU< SU	< 35      e[        R                   R"                  R%                  U5      (       d  [        R&                  " SU< SU	< 35      eX&   S   R+                  [-        U5      U[-        U5      45        GM  XU   U
'   GM     U R/                  SU05        U$ ! [        R                   a  n[        R                  " SU-  5        e SnAff = f)a_  
get_hidden_service_conf(default = UNDEFINED)

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"
    },
  }

.. versionadded:: 1.3.0

:param object default: response if the query fails

:returns: **dict** with the hidden service configuration

:raises: :class:`stem.ControllerError` if the call fails and we weren't
  provided a default response
hidden_service_confNz*GETCONF HiddenServiceOptions (cache fetch)zGETCONF HiddenServiceOptionsr  z-GETCONF HiddenServiceOptions (runtime: %0.4f)z)GETCONF HiddenServiceOptions (failed: %s)rE   =ru   HiddenServiceDirHiddenServicePort	127.0.0.1r  z4GETCONF provided an invalid HiddenServicePort port (r  z>GETCONF provided an invalid HiddenServicePort target address (z;GETCONF provided an invalid HiddenServicePort target port ()r  r  r   r  r  r   r   r   r  r  r   r   r0  r  r  r  r   rA  rD  r   rB  r   r  ri  )r   rv   service_dir_mapr  r   r   	directorystatus_codedividerr0  r]  r^  rH  target_porttarget_addressr  s                   r[   get_hidden_service_conf"Controller.get_hidden_service_conf
  st   H oo&;<O"				>?J89h
mmIx0	ii?z)+ , "mOI)1)9)9);%g	*	*	G	]]3"da	
 	 	&92%>"##$yy{{,$^^ K*0--Q*?'Nyy##11$77""dhjq#rs
s%%;;NKK""n|  F  $G  H  H%%33K@@""kvx  $A  B  B"#67>>D	>[^_j[k?lm()	"1%C *<F 	OO*O<=W  	ii;cABs   A J K
+KK
c                    U(       d  U R                  S5        g/ nU H  nUR                  SU45        [        X   R                  5       5       H  u  pEUS:X  az  U Hr  n[	        U[
        5      (       a
  U< SU< 3nO=[	        U[        5      (       a  O'[	        U[        5      (       a  Uu  pxn	U< SU< SU	< 3nUR                  SU45        Mt     M  UR                  U[        U5      45        M     M     U R                  U5        g)a  
Update all the configured hidden services from a dictionary having
the same format as
:func:`~stem.control.Controller.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 :func:`~stem.control.Controller.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),
  ]

.. versionadded:: 1.3.0

:param dict conf: configuration dictionary

:raises:
  * :class:`stem.ControllerError` if the call fails
  * :class:`stem.InvalidArguments` if configuration options
    requested was invalid
  * :class:`stem.InvalidRequest` if the configuration setting is
    impossible or if there's a syntax error in the configuration values
r  Nr  z 127.0.0.1:r  r  )	r  r   r  rf  r   r  rA  tupler  )
r   r   hidden_service_optionsr  r]  r^  r  rH  r  r  s
             r[   set_hidden_service_conf"Controller.set_hidden_service_confk
  s    J 
oo()  	##%7$CDt,,./$!##e%%%+0%8eE3''E5))27/dK$(.+Fe"))+>*FG  !
'
'CF
4 0 $ 	+,rZ   c                    [         R                  R                  R                  U5      (       d  [	        SU-  5      eU(       a<  [         R                  R                  R                  U5      (       d  [	        SU-  5      eUb<  [         R                  R                  R                  U5      (       d  [	        SU-  5      eUS;  a  [	        SU-  5      e[        U5      nU(       a  UOSnUc  UO
[        U5      nU R                  5       nX;   a  X#U4Xq   S   ;   a  gUR                  U[        5       5      R                  S/ 5      R                  X#U45        U(       a&  U(       a  U< SS	R                  U5      < 3nXU   S
'   U H  nS
Xq   ;   d
  SXq   ;   d  M  SXq   S'   M     U R                  U5        S0 pU R                  5       (       Ga  [        R                  R                  US5      n[        R                  R!                  U5      (       dh  [         R                  R"                  R%                  U R'                  S5      5      nU(       a)  [         R                  R"                  R)                  X5      n[        R                  R!                  U5      (       GaI  [*        R*                  " 5       n[        R                  R-                  U5      (       d[  [*        R*                  " 5       U-
  nUS:  a  O<[*        R.                  " S5        [        R                  R-                  U5      (       d  M[   [1        U5       nUR3                  5       R5                  5       n	U(       a{  SU	;   au  U	R7                  5        Ha  nSU;   d  M  UR9                  5       S   nUR9                  SS5      S   n[;        U5      S:X  d  MD  UR=                  S5      (       d  M\  UU
U'   Mc     SSS5        [?        UU	U
US9$ ! , (       d  f       N= f!    N!= f)a  
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
:func:`~stem.control.Controller.create_ephemeral_hidden_service` instead.

.. versionadded:: 1.3.0

.. versionchanged:: 1.4.0
   Added the auth_type and client_names arguments.

:param str path: path for the hidden service's data directory
:param int port: hidden service port
:param str target_address: address of the service, by default 127.0.0.1
:param int target_port: port of the service, by default this is the same as
  **port**
:param str auth_type: authentication type: basic, stealth or None to disable auth
:param list client_names: client names (1-16 characters "A-Za-z0-9+-_")

:returns: :class:`~stem.cotroller.CreateHiddenServiceOutput` if we create
  or update a hidden service, **None** otherwise

:raises: :class:`stem.ControllerError` if the call fails
%s isn't a valid port numberz%s isn't a valid IPv4 addressN)Nbasicstealthz,%s isn't a recognized type of authenticationr  r  r  r  HiddenServiceAuthorizeClientRendPostPeriod2HiddenServiceVersionro      r5  
z # client: r   ru      rt  rm   ) r   r   rA  rD  rC  rB  r  r  
setdefaultr   r   r   r  r   r   rn   isabsr  cwdr  expand_pathr  rR  sleepr  r  r  r  r  r{   r  rl   )r   rn   rH  r  r  	auth_typeclient_namesr   hsacro   rp   hostname_pathr  r  	wait_timehostname_filer  rK   clients                      r[   create_hidden_service Controller.create_hidden_service
  s=   @ 99--d335<==			 4 4 J J> Z Z6GHH		 )=)=)K)KK)X)X5CDD	4	4E	QRRt9D'5^;N%-$3{3CK'')D|{;tzJ]?^^OOD+-(334GLSSUYkvTwx\!388L#9:d374j/0 	'4:	59ITZ9W-0
)*  	  &$("!ggll44mWW]]=))ii""4<<#56))**66}J-	}	%	%YY[
''..//iikJ.)!^JJt ''..//	M"m$))+113H 0 #--/$ D( JJLO'::mQ7:&\R'G,<,<X,F,F29'/ 0 #& %/	 ' #" 	
s=   6P AO65O6O6	O6"P 6
P P P Pc                    U(       a<  [         R                  R                  R                  U5      (       d  [	        SU-  5      eU(       a  [        U5      OSnU R                  5       nX;  a  gU(       d  X1	 OVX1   S    Vs/ s H  oDS   U:X  d  M  UPM     nnU(       d  gU H  nX1   S   R                  U5        M     X1   S   (       d  X1	 U R                  U5        gs  snf )aL  
Discontinues a given hidden service.

.. versionadded:: 1.3.0

:param str path: path for the hidden service's data directory
:param int port: hidden service port

:returns: **True** if the hidden service is discontinued, **False** if it
  wasn't running in the first place

:raises: :class:`stem.ControllerError` if the call fails
r  NFr  r   T)	r   r   rA  rD  rC  r  r  r  r  )r   rn   rH  r   r  	to_removes         r[   remove_hidden_service Controller.remove_hidden_service"  s     DII((66t<<5<==3t9$D'')D
*&*j1D&EZ&EUqUYIY5&EiZ%
&'..u5  Z+,J  & [s   C C c                    U R                  5       [        R                  R                  R                  :  a9  [        R
                  " S[        R                  R                  R                  -  S9e/ nU(       a#   X@R                  S5      R                  S5      -  nU(       a#   X@R                  S5      R                  S5      -  nU Vs/ s H  of(       d  M  UPM     sn$ ! [        R                  [        R                  4 a  nS[        U5      ;  a  e  SnAN~SnAff = f! [        R                  [        R                  4 a  nS[        U5      ;  a  e  SnANSnAff = fs  snf )a  
list_ephemeral_hidden_services(default = UNDEFINED, our_services = True, detached = False)

Lists hidden service addresses created by
:func:`~stem.control.Controller.create_ephemeral_hidden_service`.

.. versionadded:: 1.4.0

.. versionchanged:: 1.6.0
   Tor change caused this to start providing empty strings if unset
   (:trac:`21329`).

:param object default: response if the query fails
:param bool our_services: include services created with this controller
  that weren't flagged as 'detached'
:param bool detached: include services whos contiuation isn't tied to a
  controller

:returns: **list** of hidden service addresses without their '.onion'
  suffix

:raises: :class:`stem.ControllerError` if the call fails and we weren't
  provided a default response
6Ephemeral hidden services were added in tor version %srM  zonions/currentr  z(No onion services of the specified type.Nzonions/detached)r  r   rL   r$  	ADD_ONIONr  r  r  r   r  rA  )r   rv   our_servicesdetachedr  r   rs          r[   list_ephemeral_hidden_services)Controller.list_ephemeral_hidden_servicesK  sG   6 DLL44>>>%%0hkokwkw  lD  lD  lN  lN  1N  O  OF	-- 0177== -- 1288>>
 #v!Av##!   $"6"67  6SXE
 F   $"6"67 5SXE
 F $s<   :"C! $"D" 

E#E#!$DDD"$E EE c                 d  ^ U R                  5       [        R                  R                  R                  :  a9  [        R
                  " S[        R                  R                  R                  -  S9e[        R                  " 5       Ssmn[        R                  " 5       nU(       a&  U4S jnU R                  U[        R                  5        SU< SU< 3n/ nU(       a  UR                  S5        U(       a  UR                  S5        Ub  U R                  5       [        R                  R                  R                  :  a9  [        R
                  " S	[        R                  R                  R                  -  S9eUR                  S
5        U	b  U R                  5       [        R                  R                  R                  :  a9  [        R
                  " S[        R                  R                  R                  -  S9eUR                  S5        U R                  5       [        R                  R                  R                  :  a=  U R!                  SS5      S:X  a'  U R!                  SS5      S:X  a  UR                  S5        U
b  U R                  5       [        R                  R                  R"                  :  a9  [        R
                  " S[        R                  R                  R"                  -  S9eUR                  S5        U(       a  USSR%                  U5      -  -  nU	b  USU	-  -  n['        U[(        5      (       a	  USU-  -  nOo['        U[*        5      (       a  U H  nUSU-  -  nM     OH['        U[,        5      (       a(  UR/                  5        H  u  nnUSU< SU< 3-  nM     O[1        S5      eUb8  UR/                  5        H$  u  nnU(       a  USU< SU< 3-  nM  USU-  -  nM&     U
b  USU
-  -  nU R3                  U5      n[        R4                  R7                  SU5        U(       Gab  / / nn  [9        TX|5      nUR:                  [        R<                  R>                  :X  a6  UR@                  URB                  :X  a  UR                  URD                  5        OUR:                  [        R<                  RF                  :X  a  URD                  U;   a  OUR:                  [        R<                  RH                  :X  a{  URD                  U;   ak  UR                  URD                  < SURJ                  < S35        [M        U5      [M        U5      :X  a&  [        RN                  " SS R%                  U5      -  S9eGMI  U RQ                  U5        U$ U$ ! U RQ                  U5        f = f)!a  
Creates a new hidden service. Unlike
:func:`~stem.control.Controller.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',
  })

Please note that **basic_auth** only works for legacy (v2) hidden services.

To use client auth with a **version 3** service, pass the **client_auth_v3**
argument. The value must be a base32-encoded public key from a key pair you
have generated elsewhere.

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)

.. versionadded:: 1.4.0

.. versionchanged:: 1.5.0
   Added the basic_auth argument.

.. versionchanged:: 1.5.0
   Added support for non-anonymous services. To do so set
   'HiddenServiceSingleHopMode 1' and 'HiddenServiceNonAnonymousMode 1' in
   your torrc.

.. versionchanged:: 1.7.0
   Added the timeout and max_streams arguments.

.. versionchanged:: 1.8.2
   Added the client_auth_v3 argument.

:param int,list,dict ports: hidden service port(s) or mapping of hidden
  service ports to their targets
:param str key_type: type of key being provided, generates a new key if
  'NEW' (options are: **NEW**, **RSA1024**, and **ED25519-V3**)
:param str key_content: 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**)
:param bool discard_key: avoid providing the key back in our response
:param bool detached: continue this hidden service even after this control
  connection is closed if **True**
:param bool await_publication: blocks until our descriptor is successfully
  published if **True**
:param float timeout: seconds to wait when **await_result** is **True**
:param dict basic_auth: required user credentials to access a v2 service
:param int max_streams: maximum number of streams the hidden service will
  accept, unlimited if zero or not set
:param str client_auth_v3: base32-encoded public key for **version 3**
  onion services that require client authentication

:returns: :class:`~stem.response.add_onion.AddOnionResponse` with the response

:raises:
  * :class:`stem.ControllerError` if the call fails
  * :class:`stem.Timeout` if **timeout** was reached
r  rM  Nc                 (   > TR                  U 5        g r   rv  rw  s    r[   ry  DController.create_ephemeral_hidden_service.<locals>.hs_desc_listener  r{  rZ   z
ADD_ONION r  	DiscardPKDetachzEBasic authentication support was added to ADD_ONION in tor version %s	BasicAuthz^Limitation of the maximum number of streams to accept was added to ADD_ONION in tor version %sMaxStreamsCloseCircuitr=   r  r<   NonAnonymouszTClient authentication support for v3 onions was added to ADD_ONION in tor version %sV3Authz	 Flags=%sr  z MaxStreams=%sz Port=%sz Port=z[The 'ports' argument of create_ephemeral_hidden_service() needs to be an int, list, or dictz ClientAuth=z ClientAuth=%sz ClientAuthV3=%sr  z (r  z4Failed to upload our hidden service descriptor to %sr  ))r  r   rL   r$  r  r  r   r   r  r  r  r   r   ADD_ONION_BASIC_AUTHADD_ONION_MAX_STREAMSADD_ONION_NON_ANONYMOUSr  ONION_SERVICE_AUTH_ADDr   r   r  r  r   rf  rC  r   r   r  r  ru  r  UPLOADrK   
service_idr  UPLOADEDr  r  r{   r  r  )r   portskey_typekey_contentdiscard_keyr  await_publicationr  
basic_authmax_streamsclient_auth_v3ry  r  r  r0  rH  r  client_nameclient_blobr   directories_uploaded_tofailuresr   rx  s                          @r[   create_ephemeral_hidden_service*Controller.create_ephemeral_hidden_service  s$   b DLL44>>>%%0hkokwkw  lD  lD  lN  lN  1N  O  O&+kkmT#M#J! .	0A0AB#+[9GEll;ll8				dll66KK	K''2y  }A  }I  }I  }U  }U  }j  }j  3j  k  	kll;				dll66LL	L''  3S  VZ  Vb  Vb  Vn  Vn  VD  VD  3D  E  	Ell+,T\\55MMM	3T	:c	AdmmTsuyFz  B  GB^$!				dll66MM	M''  3I  LP  LX  LX  Ld  Ld  L{  L{  3{  |  	|ll8sxx..g!K//g%e##g	E4	 	 $:$$ 	E4	 	 ++-,$D&11 ( tuu&0&6&6&8
"+{
KE
E'
%3
3'	 '9 !#n44gxx HMM+x0 +-bx5#M7G%\\T..555%--8K^K^:^#**5+F+FG||t00999e>Y>Y]t>t||t00777E<W<W[r<rOO)D)DellST*+s8}<((3ilpluluv~l3  A  A  	""#34O8O 	""#34s   =E
V V/c                    U R                  5       [        R                  R                  R                  :  a9  [        R
                  " S[        R                  R                  R                  -  S9eU R                  SU-  5      n[        R                  R                  SU5        UR                  5       (       a  gUR                  S:X  a  g[        R                  " SUR                  -  5      e)	a  
Discontinues a given hidden service that was created with
:func:`~stem.control.Controller.create_ephemeral_hidden_service`.

.. versionadded:: 1.4.0

:param str service_id: 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: :class:`stem.ControllerError` if the call fails
r  rM  zDEL_ONION %sr  Tr  Fz/DEL_ONION returned unexpected response code: %s)r  r   rL   r$  r  r  r   r   r  r  r  r   )r   r  r   s      r[   remove_ephemeral_hidden_service*Controller.remove_ephemeral_hidden_serviceV  s     DLL44>>>%%0hkokwkw  lD  lD  lN  lN  1N  O  Oxx34HMM,1~~	%	PS[S`S``aarZ   c           	         U R                      U R                  5       (       a  U H  n[        R                  R                  R
                  R                  U5      nU(       d  M?  U R                  5       UR                  :  d  M_  [        R                  " SU< SUR                  < S35      e   U H.  nU R                  R                  U/ 5      R                  U5        M0     U R                  5       S   n[        U5      R                  [        U5      5      nU(       a(  [        R                   " SSR#                  U5      -  5      e SSS5        g! , (       d  f       g= f)a{  
Directs further tor controller events to a given function. The function is
expected to take a single argument, which is a
:class:`~stem.response.events.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.

.. versionchanged:: 1.7.0
   Listener exceptions and malformed events no longer break further event
   processing. Added the **MALFORMED_EVENTS** constant.

:param functor listener: function to be called when an event is received
:param stem.control.EventType events: event types to be listened for

:raises: :class:`stem.ProtocolError` if unable to set the events
i(  z event requires Tor version z	 or laterru   zSETEVENTS rejected %sr  N)r~  r   r   r   eventsEVENT_TYPE_TO_CLASSr|   r  _VERSION_ADDEDr  r}  r  r   _attach_listenersr  intersectionr   r   )r   r   r,  
event_typefailed_eventss        r[   r  Controller.add_event_listenerr  s   L 
	#	#				 	  J}}++??CCJO*ZT--/*2K2KK%%cZdfpff  ,A  B  B	 ! *((R8??I  ,,.q1m -(55c&kBm	  !8499];S!STT 
# 
$	#	#s   AE$ECE
E c                    U R                      Sn[        U R                  R                  5       5       H=  u  p4X;   d  M  UR	                  U5        [        U5      S:X  d  M.  SnU R                  U	 M?     U(       ai  U R                  SSR                  U R                  R                  5       5      -  5      nUR                  5       (       d  [        R                  " SU-  5      eSSS5        g! , (       d  f       g= f)z
Stops a listener from being notified of further tor events.

:param stem.control.EventListener listener: listener to be removed

:raises: :class:`stem.ProtocolError` if unable to set the events
Fr   TSETEVENTS %sr  z)SETEVENTS received unexpected response
%sN)r~  r  r}  rf  r  r{   r   r   r   r  r   r   )r   r   event_types_changedr1  event_listenersr   s         r[   r   Controller.remove_event_listener  s     
	#	#!)-d.C.C.I.I.K)L
%*&

 
 
*!Q&"&%%j1 *M 
88NSXXd6K6K6P6P6R-SST~~""#ORZ#Z[
[ 
$	#	#s   .C-C-!BC--
C;c                     U R                      U R                  5       (       d
   SSS5        gU(       a	  U< SU< 3OUnU R                  R                  US5      sSSS5        $ ! , (       d  f       g= f)z
Queries our request cache for the given key.

:param str param: key to be queried
:param str namespace: namespace in which to check for the key

:returns: cached value corresponding to key or **None** if the key wasn't found
N.)r|  rd  rz  r|   )r   r  	namespace	cache_keys       r[   r  Controller._get_cache  sY     
		$$&& 
	 3<Y.i  $$Y5 
		s   A$-A$$
A2c                     U R                      0 nU R                  5       (       a=  U H7  nU(       a	  U< SU< 3OUnXPR                  ;   d  M&  U R                  U   X4'   M9     UsSSS5        $ ! , (       d  f       g= f)z
Queries our request cache for multiple entries.

:param list params: keys to be queried
:param str namespace: namespace in which to check for the keys

:returns: **dict** of 'param => cached value' pairs of keys present in cache
r:  N)r|  rd  rz  )r   r  r;  cached_valuesr  r<  s         r[   r  Controller._get_cache_map  si     
		m		 	 	"	"E6?E2U)---#'#6#6y#AM 	   
		s   <A-A--
A;c                    U R                      U R                  5       (       d
   SSS5        gUcc  U(       a\  [        U R                  R	                  5       5       H+  nUR                  SU-  5      (       d  M  U R                  U	 M-      SSS5        gUS:X  a&  UR                  5       n[         H  nXA;   d  M
  X	 M     [        UR                  5       5       Ha  u  pEU(       a
  U< SU< 3nOUnUc8  U[        U R                  R	                  5       5      ;   a  U R                  U	 MQ  MS  XPR                  U'   Mc     SSS5        g! , (       d  f       g= f)z
Sets the given request cache entries. If the new cache value is **None**
then it is removed from our cache.

:param dict params: **dict** of 'cache_key => value' pairs to be cached
:param str namespace: namespace for the keys
Nz%s.rc  r:  )	r|  rd  r  rz  r   r   copyUNCACHEABLE_GETCONF_PARAMSrf  )r   r  r;  r<  r   r  s         r[   ri  Controller._set_cache  s#    
		$$&& 
	 
Id116689I!!%)"344##I. : 	 
	 
i	-C] . V\\^,*#!*C0))=$t22779::##I. ; ,1

i
( -+ 
		s$   EAE8E"E9BE
Ec           
         U R                      U R                  5       (       d
   SSS5        g[        S UR                  5        5       5      (       a  U R	                  SS05        U R	                  [        [         Vs/ s H  o"R                  5       S4PM     sn5      S5        U R	                  SS5        U R	                  SS05        U R	                  SS05        SSS5        gs  snf ! , (       d  f       g= f)z
Drops dependent portions of the cache when configuration changes.

:param dict params: **dict** of 'config_key => value' pairs for configs
  that changed. The entries' values are currently unused.
Nc              3   H   #    U  H  nS UR                  5       ;   v   M     g7f)hiddenNrZ  )r\  r  s     r[   r_  =Controller._confchanged_cache_invalidation.<locals>.<genexpr>#  s     BM5X&Ms    "r  rt  r  r  rs  )r|  rd  anyr   ri  r   r  r   )r   r  r]  s      r[   rj  *Controller._confchanged_cache_invalidation  s     
		$$&& 
	 
BFKKMB	B	B.56 ood7]^7]!WWY-7]^_ajk
oodK(
oo+T23
oo}d+, 
	 _ 
	s$   C*AC*=C%AC*%C**
C8c                     U R                   $ )zn
**True** if caching has been enabled, **False** otherwise.

:returns: bool to indicate if caching is enabled
)ry  r   s    r[   rd  Controller.is_caching_enabled/  s     ###rZ   c                 T    Xl         U R                   (       d  U R                  5         gg)z
Enables or disables caching of information retrieved from tor.

:param bool enabled: **True** to enable caching, **False** to disable it
N)ry  rT  )r   enableds     r[   set_cachingController.set_caching8  s$      '##
 $rZ   c                 z    U R                      0 U l        SU l        SU l        SSS5        g! , (       d  f       g= f)z
Drops any cached results.
r   N)r|  rz  r{  r  r   s    r[   rT  Controller.clear_cacheD  s1    
 
		dd#'d  
		s   ,
:c           
      ^   U R                  SU-  5      n[        R                  R                  SU5        UR                  S;   a  UR                  S:X  aw  UR
                  R                  S5      (       aW  [        R                  " UR                  UR
                  UR
                  SUR
                  R                  SS5      S-
   /5      e[        R                  " UR                  UR
                  5      eUR                  5       (       d"  [        R                  " S	[        U5      -  5      eg
)z
Sends the configuration text to Tor and loads it as if it has been read from
the torrc.

:param str configtext: the configuration text

:raises: :class:`stem.ControllerError` if the call fails
zLOADCONF
%sr  )r  r  r  zDInvalid config file: Failed to parse/validate config: Unknown optionF   r:  ru   z)+LOADCONF Received unexpected response
%sN)r   r   r   r  r  r   r   r  r  r  r  r   rA  )r   
configtextr   s      r[   	load_confController.load_confN  s     xx34HMM,1}}&	%	H$4$4$?$?  AG  %H  %H##HMM83C3ChFVFVWYZbZjZjZoZopsuwZx{|Z|F}E~x/?/?@@^^KcRZm[\\ rZ   c                    U R                  5       [        R                  R                  R                  :  a  SnU R                  U(       a  SOS5      n[        R                  R                  SU5        UR                  5       (       a  gUR                  S:X  a+  [        R                  " UR                  UR                  5      e[        R                  " S5      e)a  
Saves the current configuration options into the active torrc file.

.. versionchanged:: 1.6.0
   Added the force argument.

:param bool force: overwrite the configuration even if it includes a
  '%include' clause, this is ignored if tor doesn't support it

:raises:
  * :class:`stem.ControllerError` if the call fails
  * :class:`stem.OperationFailed` if the client is unable to save
    the configuration file
FzSAVECONF FORCESAVECONFr  T551z*SAVECONF returned unexpected response code)r  r   rL   r$  SAVECONF_FORCEr   r   r  r  r  r  r   r   )r   forcer   s      r[   	save_confController.save_confb  s      DLL44CCCexxE(zBHMM,1~~	%	  0@0@AAKLLrZ   c                    UR                  5       nXR                  ;   a  gSnUS:X  a%  [        R                  R                  R
                  nO*US:X  a$  [        R                  R                  R                  nU(       a8  U R                  S5      nU(       a   X2:  a  U R                  R                  U5        XR                  ;   $ )z
Checks if a control connection feature is enabled. These features can be
enabled using :func:`~stem.control.Controller.enable_feature`.

:param str feature: feature to be checked

:returns: **True** if feature is enabled, **False** otherwise
TNEXTENDED_EVENTSVERBOSE_NAMES)	upperr  r   rL   r$  FEATURE_EXTENDED_EVENTSFEATURE_VERBOSE_NAMESr  r   )r   featuredefaulted_versionour_versions       r[   is_feature_enabledController.is_feature_enabled  s     mmoG((( 	%	% LL44LLo% LL44JJ	&&t,;;

 
 
'
'
0....rZ   c                    [         R                  R                  U5      (       a  U/nU R                  SSR	                  U5      -  5      n[         R
                  R                  SU5        UR                  5       (       d  UR                  S:X  ax  / nUR                  R                  S5      (       a*  UR                  SUR                  R                  SS5       /n[         R                  " UR                  UR                  U5      e[         R                  " SUR                  -  5      eU =R                  U Vs/ s H  oDR                  5       PM     sn-  sl        g	s  snf )
a  
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

:param str,list features: a single feature or a list of features to be enabled

:raises:
  * :class:`stem.ControllerError` if the call fails
  * :class:`stem.InvalidArguments` if features passed were invalid
zUSEFEATURE %sr  r  r  zUnrecognized feature "r  r  z0USEFEATURE provided an invalid response code: %sN)r   r   r  r   r   r   r  r  r  r   r   r  r  r   r  rb  )r   featuresr   invalid_featurer  s        r[   enable_featureController.enable_feature  s   & yy""hxx#((8*<<=HMM,1>>	%	&&'?@@%--b1A1A1F1FsB1OPQ/##HMM83C3C_UUQT\TaTaabb(C({{}(CCCs   ;Ec                 t    U R                  5        H  nUR                  U:X  d  M  Us  $    [        SU-  5      e)a  
get_circuit(circuit_id, default = UNDEFINED)

Provides a circuit currently available from tor.

:param int circuit_id: circuit to be fetched
:param object default: response if the query fails

:returns: :class:`stem.response.events.CircuitEvent` for the given circuit

:raises:
  * :class:`stem.ControllerError` if the call fails
  * **ValueError** if the circuit doesn't exist

  An exception is only raised if we weren't provided a default response.
z9Tor currently does not have a circuit with the id of '%s')get_circuitsidrC  )r   
circuit_idrv   circs       r[   get_circuitController.get_circuit  s<    & !!#	J	 $ PS]]
^^rZ   c           	      v   / nU R                  S5      nUR                  5        H  n[        R                  R	                  [
        R                  " [        R                  R                  R                  SU-  5      5      5      n[        R                  R                  SU5        UR                  U5        M     U$ )a.  
get_circuits(default = UNDEFINED)

Provides tor's currently available circuits.

:param object default: response if the query fails

:returns: **list** of :class:`stem.response.events.CircuitEvent` for our circuits

:raises: :class:`stem.ControllerError` if the call fails and no default was provided
zcircuit-statusz650 CIRC %s
EVENTr  r  r   rF  recv_messagerP  rQ  r   r  	_to_bytesr   r  r   )r   rv   circuitsr   rs  circ_messages         r[   rp  Controller.get_circuits  s     H}}-.H##%[[--bjj9L9L9V9VWhkoWo9p.qrl
mmG\2ool# &
 OrZ   c                 (    U R                  SXX45      $ )a?  
Requests a new circuit. If the path isn't provided, one is automatically
selected.

.. versionchanged:: 1.7.0
   Added the timeout argument.

:param list,str path: one or more relays to make a circuit through
:param str purpose: 'general' or 'controller'
:param bool await_build: blocks until the circuit is built if **True**
:param float timeout: seconds to wait when **await_build** is **True**

:returns: str of the circuit id of the newly created circuit

:raises:
  * :class:`stem.ControllerError` if the call fails
  * :class:`stem.Timeout` if **timeout** was reached
r  )extend_circuit)r   rn   purposeawait_buildr  s        r[   new_circuitController.new_circuit  s    ( sD;HHrZ   c                 `  ^ [         R                  " 5       Ssmn[        R                  " 5       nU(       a&  U4S jnU R                  U[        R
                  5         [        U5      nUcX  US:X  aR  [        R                  R                  R                  nU R                  5       U:  d  [        R                  " SSU-  5      eU/n	[        R                  R                  U5      (       a  U/nU(       a   U	R                  SR!                  U5      5        U(       a  U	R                  SU-  5        U R#                  SS	R!                  U	5      -  5      n
[        R$                  R'                  S
U
5        U
R(                  S;   a+  [        R                  " U
R(                  U
R*                  5      eU
R-                  5       (       d#  [        R.                  " SU
R(                  -  5      eU
R*                  R1                  S5      (       d  [        R.                  " SU
5      eU
R*                  R3                  S	S5      S   nU(       a   [5        TXW5      nUR6                  U:X  a  UR8                  [:        R<                  :X  a  OyUR8                  [:        R>                  :X  a$  [        R@                  " SURB                  -  U5      eUR8                  [:        RD                  :X  a  [        R@                  " SU5      eM  UU(       a  U RG                  U5        $ $ ! U(       a  U RG                  U5        f f = f)a  
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

.. versionchanged:: 1.7.0
   Added the timeout argument.

:param str circuit_id: id of a circuit to be extended
:param list,str path: one or more relays to make a circuit through, this is
  required if the circuit id is non-zero
:param str purpose: 'general' or 'controller'
:param bool await_build: blocks until the circuit is built if **True**
:param float timeout: seconds to wait when **await_build** is **True**

:returns: str of the circuit id of the created or extended circuit

:raises:
  * :class:`stem.InvalidRequest` if one of the parameters were invalid
  * :class:`stem.CircuitExtensionFailed` if we were waiting for the circuit
    to build but it failed
  * :class:`stem.Timeout` if **timeout** was reached
  * :class:`stem.ControllerError` if the call fails
Nc                 (   > TR                  U 5        g r   rv  )r   
circ_queues    r[   circ_listener0Controller.extend_circuit.<locals>.circ_listener;  s    urZ   r  i   z3EXTENDCIRCUIT requires the path prior to version %sr  z
purpose=%szEXTENDCIRCUIT %sr  r  512r  z3EXTENDCIRCUIT returned unexpected response code: %sz	EXTENDED z"EXTENDCIRCUIT response invalid:
%sru   z Circuit failed to be created: %sz!Circuit was closed prior to build)$r   r   r  r  r  r   rA  r   rL   r$  EXTENDCIRCUIT_PATH_OPTIONALr  r  r   r  r   r   r   r   r  r  r   r  r   r   r  r  rq  r^   r   BUILTr  CircuitExtensionFailedr  r   r  )r   rr  rn   r  r  r  r  r  path_opt_versionry   r   r  rs  r  s                @r[   r  Controller.extend_circuit  s{   X !&tJJ mY^^<12z?j	*+<<33OO!%55##C)^aq)qr
r\d			4	 	 v	CHHTN#	L7*+,sxx~=>h
mmL(3	.	(!!(--1A1ABB~~  !VYaYfYf!fgg((55  !FQQ$$**3215k	":wC$WW#{{j...
 1 11//0RUYU`U`0`bfgg
 1 11//0SUYZZ  	""=1 
""=1 
s   JL L-c                 \   U R                  SU< SU< 35      n[        R                  R                  SU5        UR	                  5       (       d^  UR
                  S:X  a+  [        R                  " UR
                  UR                  5      e[        R                  " SUR
                  -  5      eg)aO  
Changes a circuit's purpose. Currently, two purposes are recognized...
  * general
  * controller

:param str circuit_id: id of the circuit whose purpose is to be changed
:param str purpose: purpose (either 'general' or 'controller')

:raises: :class:`stem.InvalidArguments` if the circuit doesn't exist or if the purpose was invalid
zSETCIRCUITPURPOSE z	 purpose=r  r  z7SETCIRCUITPURPOSE returned unexpected response code: %sN)	r   r   r   r  r  r  r  r   r   )r   rr  r  r   s       r[   repurpose_circuitController.repurpose_circuits  s     xxZQRHMM,1>>	%	!!(--1A1ABB  !Z]e]j]j!jkk	 rZ    c                    U R                  SU< SU< 35      n[        R                  R                  SU5        UR	                  5       (       d  UR
                  S;   ax  UR                  R                  S5      (       a-  [        R                  " UR
                  UR                  U/5      e[        R                  " UR
                  UR                  5      e[        R                  " SUR
                  -  5      eg)au  
Closes the specified circuit.

:param str circuit_id: id of the circuit to be closed
:param str flag: optional value to modify closing, the only flag available
  is 'IfUnused' which will not close the circuit unless it is unused

:raises: :class:`stem.InvalidArguments` if the circuit is unknown
:raises: :class:`stem.InvalidRequest` if not enough information is provided
zCLOSECIRCUIT r  r  r  zUnknown circuit z2CLOSECIRCUIT returned unexpected response code: %sN)r   r   r   r  r  r  r   r   r  r  r   )r   rr  flagr   s       r[   close_circuitController.close_circuit  s     xx
DABHMM,1>>	.	(&&'9::%%hmmX5E5E
|T
T!!(--1A1ABB  !UX`XeXe!eff rZ   c           	      v   / nU R                  S5      nUR                  5        H  n[        R                  R	                  [
        R                  " [        R                  R                  R                  SU-  5      5      5      n[        R                  R                  SU5        UR                  U5        M     U$ )a,  
get_streams(default = UNDEFINED)

Provides the list of streams tor is currently handling.

:param object default: response if the query fails

:returns: list of :class:`stem.response.events.StreamEvent` objects

:raises: :class:`stem.ControllerError` if the call fails and no default was
  provided
zstream-statusz650 STREAM %s
rw  rx  )r   rv   streamsr   streamr   s         r[   get_streamsController.get_streams  s     G}}_-H%%'((DII4G4G4Q4QRehnRn4o)pqg
mmGW-nnW (
 NrZ   c                 j   SU< SU< 3nU(       a  USU-  -  nU R                  U5      n[        R                  R                  SU5        UR	                  5       (       d  UR
                  S:X  a+  [        R                  " UR
                  UR                  5      eUR
                  S:X  a+  [        R                  " UR
                  UR                  5      eUR
                  S:X  a+  [        R                  " UR
                  UR                  5      e[        R                  " SUR
                  -  5      eg	)
a{  
Attaches a stream to a circuit.

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

:param str stream_id: id of the stream that must be attached
:param str circuit_id: id of the circuit to which it must be attached
:param int exiting_hop: hop in the circuit where traffic should exit

:raises:
  * :class:`stem.InvalidRequest` if the stream or circuit id were unrecognized
  * :class:`stem.UnsatisfiableRequest` if the stream isn't in a state where it can be attached
  * :class:`stem.OperationFailed` if the stream couldn't be attached for any other reason
zATTACHSTREAM r  z HOP=%sr  r  rZ  555z2ATTACHSTREAM returned unexpected response code: %sN)r   r   r   r  r  r  r  r   r  r  r   )r   	stream_idrr  exiting_hopr  r   s         r[   attach_streamController.attach_stream  s    " %.z:Ey;&&exxHMM,1>>	%	!!(--1A1ABB==E!""8==(2B2BCC==E!''x7G7GHH  !UX`XeXe!eff rZ   c                    U R                  SU< S[        R                  R                  U5      S-   < SU< 35      n[        R                  R                  SU5        UR                  5       (       d  UR                  S;   a  UR                  R                  S5      (       a-  [        R                  " UR                  UR                  U/5      eUR                  R                  S5      (       a-  [        R                  " UR                  UR                  U/5      e[        R                  " UR                  UR                  5      e[        R                  " SUR                  -  5      eg	)
aX  
Closes the specified stream.

:param str stream_id: id of the stream to be closed
:param stem.RelayEndReason reason: reason the stream is closing
:param str flag: not currently used

:raises:
  * :class:`stem.InvalidArguments` if the stream or reason are not recognized
  * :class:`stem.InvalidRequest` if the stream and/or reason are missing
zCLOSESTREAM r  ru   r  r  zUnknown stream zUnrecognized reason z1CLOSESTREAM returned unexpected response code: %sN)r   r   RelayEndReasonindex_ofr   r  r  r  r   r   r  r  r   )r   r  r  r  r   s        r[   close_streamController.close_stream  s     xx)T=P=P=Y=YZ`=ade=egklmHMM,1>>	.	(&&'899%%hmmX5E5E	{S
S(()?@@%%hmmX5E5ExP
P!!(--1A1ABB  !TW_WdWd!dee rZ   c                    U R                  SU-  5      n[        R                  R                  SU5        UR	                  5       (       a:  U[        R
                  R                  :X  a  [        R                  " 5       U l        ggUR                  S:X  a-  [        R                  " UR                  UR                  U/5      e[        R                  " SUR                  -  5      e)z
Sends a signal to the Tor client.

:param stem.Signal signal: type of signal to be sent

:raises:
  * :class:`stem.ControllerError` if sending the signal failed
  * :class:`stem.InvalidArguments` if signal provided wasn't recognized
z	SIGNAL %sr  r  z6SIGNAL response contained unrecognized status code: %sN)r   r   r   r  r  r   NEWNYMr  r{  r  r  r   r   )r   rR  r   s      r[   rR  Controller.signal  s     xxf,-HMM,1~~	4;;%%	% IIK 
& 
%	##HMM83C3CfXNNWZbZgZgghhrZ   c                 T    U R                  5       (       a  U R                  5       S:H  $ g)z
Indicates if tor would currently accept a NEWNYM signal. This can only
account for signals sent via this controller.

.. versionadded:: 1.2.0

:returns: **True** if tor would currently accept a NEWNYM signal, **False**
  otherwise
r   F)r   get_newnym_waitr   s    r[   is_newnym_availableController.is_newnym_available  s&     }}!!#s**rZ   c                 `    [        SU R                  S-   [        R                  " 5       -
  5      $ )z
Provides the number of seconds until a NEWNYM signal would be respected.
This can only account for signals sent via this controller.

.. versionadded:: 1.2.0

:returns: **float** for the number of seconds until tor would respect
  another NEWNYM signal
r   
   )r  r{  r  r   s    r[   r  Controller.get_newnym_wait  s'     sD%%*TYY[899rZ   c                     U(       d  SnOSnSnU HO  n[        U R                  U5      5      nUS:X  a  UR                  S5      (       a  M;  U(       a  [        XF5      OUnMQ     U$ )a  
get_effective_rate(default = UNDEFINED, burst = False)

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)

.. versionadded:: 1.3.0

:param object default: response if the query fails
:param bool burst: provides the burst bandwidth, otherwise this provides
  the standard rate

:returns: **int** with the effective bandwidth rate in bytes per second

:raises: :class:`stem.ControllerError` if the call fails and no default was
  provided
)BandwidthRateRelayBandwidthRateMaxAdvertisedBandwidth)BandwidthBurstRelayBandwidthBurstNr   Relay)r  r  r   min)r   rv   burst
attributesr  attr
attr_values          r[   get_effective_rateController.get_effective_rate,  s`    . Tj<jEt}}T*+j	qT__W55(-c%$:e  LrZ   c                    U R                   c%   U R                  S5        SU l         U R                   $ U R                   $ ! [        R                   a0  nS[	        U5      ;   a  SU l          SnAU R                   $  SnAgSnAff = f)a  
Provides **True** if tor's geoip database is unavailable, **False**
otherwise.

.. versionchanged:: 1.6.0
   No longer requires previously failed GETINFO requests to determine this.

.. deprecated:: 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
Nr  FzGeoIP data not loadedT)r  r  r   r   rA  )r   r   s     r[   r  Controller.is_geoip_unavailableT  s    & !!)-.%*" %%%4%%% !! "c#h.'+$
$
$ %%% 	s   ? BA>>Bc           	         SR                  [        UR                  5       5       VVs/ s H  u  p#U< SU< 3PM     snn5      nU R                  SU-  5      n[        R
                  R                  SU5        UR                  $ s  snnf )a  
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.

:param dict mapping: mapping of original addresses to replacement addresses

:raises:
  * :class:`stem.InvalidRequest` if the addresses are malformed
  * :class:`stem.OperationFailed` if Tor couldn't fulfill the request

:returns: **dict** with 'original -> replacement' address mappings
r  r  zMAPADDRESS %s
MAPADDRESS)r   r  rf  r   r   r   r  r  )r   mappingr]  r^  mapaddress_argr   s         r[   map_addressController.map_addresss  sn    & XXd7==?>ST>SFQ!Q/>STUNxx.89HMM,1	 Us   B
c                    U R                  5       [        R                  R                  R                  :  a9  [        R
                  " S[        R                  R                  R                  -  S9eU R                  S5        g)z
Drops our present guard nodes and picks a new set.

.. versionadded:: 1.2.0

:raises: :class:`stem.ControllerError` if Tor couldn't fulfill the request
z&DROPGUARDS was added in tor version %srM  
DROPGUARDSN)r  r   rL   r$  r  r  r   r   s    r[   drop_guardsController.drop_guards  s[     DLL44???%%0X[_[g[g[s[s[~[~0~HH\rZ   c           	        > [         [        U ]  5         U R                      U R	                  5       S   nU(       ab  U H  nU R
                  U	 M     SSR                  U5      -  n[        R                  " U[        R                  SSR                  U5      -  5        S S S 5        U R                  SS 5      nU[        [        R                   " 5       5      :X  a  U R#                  5       (       as  U R%                  S5      n[        R&                  R)                  S	U5        UR+                  5       (       a   U R-                  S5        g [        R                  " SU-  5        g g g ! [        R                   a#  n[        R                  " SU-  5         S nANS nAff = f! , (       d  f       GN= f! [        R.                   a#  n[        R                  " S
U-  5         S nAg S nAff = f)Nru   z!stem.controller.event_reattach-%s-zOWe were unable to re-attach our event listeners to the new tor instance for: %sr  zEUnable to issue the SETEVENTS request to re-attach our listeners (%s)__OwningControllerProcessTAKEOWNERSHIPr  zWe were unable to reset tor's __OwningControllerProcess configuration. It will continue to periodically check if our pid exists. (%s)zWe were unable assert ownership of tor through TAKEOWNERSHIP, despite being configured to be the owning process through __OwningControllerProcess. (%s))r  r>  r   r~  r/  r}  r   r   log_oncer,   r   r   r   r  rA  r   getpidr   r   r   r  r  r  r   )r   r2  r1  
logging_idr   
owning_pidr   r  s          r[   r   Controller._post_authentication  s   	*d02 
	#	#`..03)j%%j1 * ;SXXm=TT*
,,z388-~  BF  BK  BK  LY  BZ  .Z  [ 
$  :DAJS%%$*;*;*=*=/*h
mmL(3				b
//5
6 	  k  nv  v  	w +>%  `X[^^__` 
$	#8 ## 	b
((  [  ^a  a  b  b	bsG   FA<E$6F0 $F8FFFF
F-0G'G""G'c           
      *    [         R                  R                  SU5        UR                  nU R                     [        U R                  R                  5       5       H  u  pEXB:X  d  M  U H  n U" U5        M     M      S S S 5        g ! [         R                   a.  n[
        R                  " SU< SU< 35        [        n S nANS nAff = f! [         a)  n[
        R                  " SU< SU< 35         S nAM  S nAff = f! , (       d  f       g = f)Nrw  zTor sent a malformed event (r  z-Event listener raised an uncaught exception ()r   r   r  rT  r   r   errorr   r~  r  r}  rf  r   r   )r   r	  r1  r   r  r7  r   s          r[   r
  Controller._handle_event  s    $
mmG]3 %%j
 
	#	#,01F1F1L1L1N,O
(-&)hf}% * -P 
$	#	  $	iimLM#j$  fhhQTVcdeef 
$	#sR   ,B	 ,D*D0C8D	C$CC
D	C<	6D<D	D
Dc           	         / / p!U R                      U R                  5       (       a  U R                  SSR                  U R                  R                  5       5      -  5      nUR                  5       (       a$  [        U R                  R                  5       5      nO[        U R                  R                  5       5       Hb  nU R                  SSR                  X/-   5      -  5      nUR                  5       (       a  UR                  U5        MQ  UR                  U5        Md     SSS5        X4$ ! , (       d  f       X4$ = f)a  
Attempts to subscribe to the self._event_listeners events from tor. This is
a no-op if we're not currently authenticated.

:returns: tuple of the form (set_events, failed_events)

:raises: :class:`stem.ControllerError` if unable to make our request to tor
r5  r  N)	r~  r   r   r   r}  r   r  r  r   )r   
set_eventsr2  r   r   s        r[   r/  Controller._attach_listeners  s    !#B		#	#				 	 88NSXXd6K6K6P6P6R-SST>>D116689* D116689exx*w:N1O OPH~~&""5) :+ 
$: &&; 
$	#: &&s   DD..
D>)
r|  r  r}  r~  ry  r  rv  r  r{  rz  )r  rv   )z/var/run/tor/controlr<  )NNNNr   )	NEWBESTFFFNNNN)NgeneralFN)r  Nr  FN)r  )WrT   rU   rV   rW   rX   staticmethodrJ  rN  r   r   r  r  r   r   r  r  r  r  r  r  r  r
  r  r  r'  r*  r5  rI  rZ  ra  rd  r_  r/  rq  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r&  r)  r  r  r  r  ri  rj  rd  rO  rT  rV  r]  rh  rm  rt  rp  r  r  r  r  r  r  r   r  MISCr  rR  r  r  r  r  r  r  r   r
  r/  rY   __classcell__)r  s   @r[   r>  r>    s)   
 $ $B & &/Pb$8)  >'0e y yv >"+  8 >&/ > >@ >/8 "^ "^H >3< g gR >+4 ) )V +4 7& >'0 2 2, >(  o  oD >' 5n 5nn >%. 0s 0sd >!* / /$'AR >(,	 7I 7Ir +4 < <| >*.) B BH -6 $ $L= >'+y 8Q 8Qt +4 " "H >=FRVgkw{ a= a=F '0E /=b ,5 tl* >$- / /(6,,FOXb >.7 ] ]~?-Btl'R >5>t`e 2$ 2$hTlb88Ut\46",(1T-0$
(](M:/>$DL >.7 _ _0 >#,  .I,f2Pl*g. >"+  0!gF .2-@-@-E-Eb f:i. : >)2E % %N&>2$wLf")' )'rZ   r>  c                     U (       a,   U R                  S5       Vs/ s H  n[        U5      PM     sn$ / $ s  snf ! [        R                   a"  n[        R                  " U< SU < 35      eSnAff = f)a  
Parses a circuit path as a list of **(fingerprint, nickname)** tuples. Tor
circuit paths are defined as being of the form...

::

  Path = LongName *("," LongName)
  LongName = Fingerprint [ ( "=" / "~" ) Nickname ]

  example:
  $999A226EBED397F331B612FE1E4CFAE5C1F201BA=piyaz

... *unless* this is prior to tor version 0.2.2.1 with the VERBOSE_NAMES
feature turned off (or before version 0.1.2.2 where the feature was
introduced). In that case either the fingerprint or nickname in the tuple
will be **None**, depending on which is missing.

::

  Path = ServerID *("," ServerID)
  ServerID = Nickname / Fingerprint

  example:
  $E57A476CD4DFBD99B4EE52A100A58610AD6E80B9,hamburgerphone,PrivacyRepublic14

:param str path: circuit path to be parsed

:returns: list of **(fingerprint, nickname)** tuples, fingerprints do not have a proceeding '$'

:raises: :class:`stem.ProtocolError` if the path is malformed
r  z: N)r  _parse_circ_entryr   r   )rn   r  r   s      r[   _parse_circ_pathr    si    B 
748JJsODO5&ODD
 I E 735667s!   ; 6; ; A1A,,A1c                    SU ;   a  U R                  S5      u  pO*SU ;   a  U R                  S5      u  pOU S   S:X  a  U Sp!OSU p!UbM  [        R                  R                  R	                  US5      (       d  [        R
                  " SU-  5      eUSS nUbG  [        R                  R                  R                  U5      (       d  [        R
                  " S	U-  5      eX4$ )
a   
Parses a single relay's 'LongName' or 'ServerID'. See the
:func:`~stem.control._parse_circ_path` function for more information.

:param str entry: relay information to be parsed

:returns: **(fingerprint, nickname)** tuple

:raises: :class:`stem.ProtocolError` if the entry is malformed
r  ~r   $NTz1Fingerprint in the circuit path is malformed (%s)ru   z.Nickname in the circuit path is malformed (%s))r  r   r   r>  r?  r   r@  )r  rN   nicknames      r[   r  r  (  s     	E\!KK,K
e|!KK,KQx3!4 !%9933KFFRU``aaab/K$))"5"5"G"G"Q"Q


MPXX
YY
	  rZ   c                 H   U b  [        U [        5      (       aI  [        U R                  5       5       H+  u  p4UR	                  5       UR	                  5       :X  d  M)  Us  $    O/U  H)  nUR	                  5       UR	                  5       :X  d  M'  Us  $    [        SU< SU < 35      e)a  
Makes a case insensitive lookup within a list or dictionary, providing the
first matching entry that we come across.

:param list,dict entries: list or dictionary to be searched
:param str key: entry or key value to look up
:param object default: value to be returned if the key doesn't exist

:returns: case insensitive match or default if one was provided and key wasn't found

:raises: **ValueError** if no such value exists
zkey 'z' doesn't exist in dict: )r   r   r  rf  r   rC  )r  r   rv   r]  r^  r  s         r[   r  r  M  s~     '4  w}}'$!779		#( ( %;;=CIIK',  	3HIIrZ   c                 ,   U(       aM  U[         R                   " 5       U-
  -
  nUS::  a  [        R                  " SU-  5      e U R                  SU5      $ U R                  5       $ ! [        R
                   a    [        R                  " SU-  5      ef = f)z2
Pulls an item from a queue with a given timeout.
r   z Reached our %0.1f second timeoutT)r  r   Timeoutr|   r   r   )event_queuer  r  	time_lefts       r[   r  r  i  s    
 499;34IA~LL;gEFFG__T9-- ?? ;; GLL;gEFFGs   A% %.Br<  )HrX   r  collections.abcr  r   rw   rP  r   r   r  r   ImportErrorstem.util.ordereddictr   r   stem.descriptor.microdescriptorr   stem.descriptor.reader#stem.descriptor.router_status_entry!stem.descriptor.server_descriptorstem.exit_policystem.responsestem.response.eventsstem.socket	stem.utilstem.util.confstem.util.connectionstem.util.enumstem.util.str_toolsstem.util.systemstem.util.tor_toolsstem.versionr   r   r   r   r7  r   r   enumEnumr  UppercaseEnumr  r  r  mapr  r  rA  r   r  r  r  r  r  rC  r`  r   
namedtuplerQ   rh   rl   r   r   objectr   r>  r  r  r  r  rR   rZ   r[   <module>r     sV  tl     	 	  0% '  * (             . . 
  %  			FGX6 IINN(( "	H 99>>''			
 s499#6#6#B#BC		 T E    $   --0"80  * & "?   k,,->  A_  ` $//0DyR\F]^  6 67R  UJ  !K ".b/4B#V B#JU0' U0'p`(V"!J 5> J J6G{  0//0  s"   G G1 G.-G.1
G?>G?