o
    „^I ã                   @   sz  d Z ddlZddlZddlZddlZddlZddlZddlZddlZzddlm	Z	 W n e
y9   ddlm	Z	 Y nw zddlZW n e
yM   ddlZY nw ddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlmZm Z m!Z! ddlm"Z" dZ#dZ$ej%j& 'dd	d
¡Z(ej%j&j)dŽ Z*ej%j& )ddddddddd¡	Z+e,e-ej%j.j/e-e0j1dƒƒƒZ2dZ3ddddddœZ4dZ5dZ6dZ7dZ8da9G dd„ de :dg d¢¡ƒZ;G d d!„ d!e :d!d"d#g¡ƒZ<G d$d%„ d%e :d%g d&¢¡ƒZ=d8d(d)„Z>d*d+„ Z?G d,d-„ d-e@ƒZAG d.d/„ d/eAƒZBd0d1„ ZCd2d3„ ZDe>ƒ efd4d5„ƒZEd6d7„ ZFdS )9a“-  
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)!ZADDRMAPZAUTHDIR_NEWDESCSZBUILDTIMEOUT_SETZBWZ
CELL_STATSÚCIRCZCIRC_BWZ
CIRC_MINORÚCONF_CHANGEDZCONN_BWZCLIENTS_SEENÚDEBUGZDESCCHANGEDZERRZGUARDÚHS_DESCÚHS_DESC_CONTENTÚINFOZNETWORK_LIVENESSZNEWCONSENSUSZNEWDESCZNOTICEZNSZORCONNÚSIGNALZSTATUS_CLIENTZSTATUS_GENERALÚSTATUS_SERVERZSTREAMZ	STREAM_BWZTB_EMPTYZTRANSPORT_LAUNCHEDÚWARNÚORÚDIRÚSOCKSÚTRANSÚNATDÚDNSÚCONTROLZEXTORZ
HTTPTUNNEL)ZAccelDirZ	AccelNameÚDataDirectoryZDisableAllSwapZDisableDebuggerAttachmentZHardwareAccelÚHiddenServiceNonAnonymousModeÚHiddenServiceSingleHopModeZKeepBindCapabilitiesÚPidFileZRunAsDaemonZSandboxZSyslogIdentityTagZTokenBucketRefillIntervalZ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)r$   r    r!   r"   r#   z¶Tor 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                   @   ó   e Zd ZdZdS )ÚAccountingStatsa×  
  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__Ú__doc__© r1   r1   ú./usr/lib/python3/dist-packages/stem/control.pyr+   ©  ó    r+   ©
Ú	retrievedÚstatusÚinterval_endZtime_until_resetZ
read_bytesZread_bytes_leftZ
read_limitZwritten_bytesZwrite_bytes_leftZwrite_limitc                   @   r*   )ÚUserTrafficAllowedzê
  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
  Nr,   r1   r1   r1   r2   r8   »  r3   r8   ZinboundZoutboundc                   @   r*   )ÚCreateHiddenServiceOutputaV  
  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
  Nr,   r1   r1   r1   r2   r9   Ä  r3   r9   ©ÚpathÚhostnameÚhostname_for_clientÚconfigFc                    s   ‡ fdd„}|S )zb
  Provides a decorator to support having a default value. This should be
  treated as private.
  c                    sD   dd„ ‰ˆst  ˆ ¡‡ ‡fdd„ƒ}|S t  ˆ ¡‡ ‡fdd„ƒ}|S )Nc                 S   sR   t  | ¡jdd … }d|v r| d¡nd }|d ur#|t|ƒk r#|| S | dt¡S )Né   Údefault)ÚinspectZ
getargspecÚargsÚindexÚlenÚgetr   )ÚfuncrB   ÚkwargsZ	arg_namesZdefault_positionr1   r1   r2   Úget_defaultÜ  s
   z4with_default.<locals>.decorator.<locals>.get_defaultc                    s>   zˆ | g|¢R i |¤ŽW S    ˆˆ ||ƒ}|t kr‚ | Y S ©N©r   )ÚselfrB   rG   r@   ©rF   rH   r1   r2   Úwrappedæ  s   z0with_default.<locals>.decorator.<locals>.wrappedc                 ?   sl    zˆ | g|¢R i |¤ŽD ]}|V  qW d S    ˆˆ ||ƒ}|t kr$‚ |d ur0|D ]}|V  q*Y d S Y d S rI   rJ   )rK   rB   rG   Úvalr@   rL   r1   r2   rM   ò  s   €ÿþ)Ú	functoolsÚwraps)rF   rM   ©ÚyieldsrL   r2   Ú	decoratorÛ  s   	ñzwith_default.<locals>.decoratorr1   )rR   rS   r1   rQ   r2   Úwith_defaultÕ  s   (rT   c              
      sš   t du rFtjj ¡ ‰ tj tj t	¡d¡}zˆ  
|¡ t‡ fdd„ˆ  ¡ D ƒƒa W n tyE } zt d||f ¡ W Y d}~dS d}~ww t  |  ¡ ¡S )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.cfgc                    s0   g | ]}|  d ¡r| ¡ dd… ˆ  |¡f‘qS )zevent.description.é   N)Ú
startswithÚlowerZ	get_value)Ú.0Úkey©r>   r1   r2   Ú
<listcomp>  s   0 z%event_description.<locals>.<listcomp>zFBUG: stem failed to load its internal manual information from '%s': %s)ÚEVENT_DESCRIPTIONSÚstemÚutilÚconfZConfigÚosr;   ÚjoinÚdirnameÚ__file__ÚloadÚdictÚkeysÚ	Exceptionr   ÚwarnrE   rW   )ÚeventZconfig_pathÚexcr1   rZ   r2   Úevent_description  s   
€þrk   c                   @   sÄ   e Zd ZdZd1dd„Zdd„ Zdd„ Zd	d
„ Zdd„ Zdd„ Z	dd„ Z
dd„ Zdd„ Zdd„ Zd2dd„Zdd„ Zdd„ Zdd„ Zd d!„ Zd"d#„ Zd$d%„ Zd&d'„ Zd(d)„ Zd*d+„ Zd,d-„ Zd.d/„ Zd0S )3ÚBaseControllera…  
  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.
  Fc                 C   sª   || _ t ¡ | _g | _t ¡ | _t ¡ | _t ¡ | _	d | _
t ¡ | _d | _| j j| _| j j| _| j| j _| j| j _d| _d| _g | _| j  ¡ rK|  ¡  |rS|  ¡  d S d S )Nç        F)Ú_socketÚ	threadingÚRLockÚ	_msg_lockÚ_status_listenersÚ_status_listeners_lockÚqueueÚQueueÚ_reply_queueÚ_event_queueÚ_reader_threadZEventÚ_event_noticeÚ_event_threadÚ_connectÚ_socket_connectÚ_closeÚ_socket_closeÚ_last_heartbeatÚ_is_authenticatedÚ_state_change_threadsÚis_aliveÚ_launch_threadsÚ_post_authentication)rK   Úcontrol_socketÚis_authenticatedr1   r1   r2   Ú__init__0  s*   









ÿzBaseController.__init__c              	   C   s  | j y | j ¡ sQz8| j ¡ }t|tjƒrn*t|tjƒr$t 	d| ¡ nt|tj
ƒr2t 	d| ¡ nt|tjjƒr@t 	d| ¡ W n
 tjyK   Y nw | j ¡ r	z| j |¡ | j ¡ }t|tj
ƒre|‚|W W  d  ƒ S  tjy{   |  ¡  ‚ w 1 sw   Y  dS )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)rq   rv   ÚemptyÚ
get_nowaitÚ
isinstancer]   ZSocketClosedÚProtocolErrorr   ÚinfoÚControllerErrorÚresponseZControlMessagert   ÚEmptyrn   ÚsendrE   Úclose)rK   ÚmessagerŽ   r1   r1   r2   ÚmsgV  s:   

€ü
ô
Ç:ùÆzBaseController.msgc                 C   ó
   | j  ¡ S )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
    )rn   r‚   ©rK   r1   r1   r2   r‚   ©  s   
zBaseController.is_alivec                 C   r”   )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
    )rn   Úis_localhostr•   r1   r1   r2   r–   ³  s   
	zBaseController.is_localhostc                 C   r”   )ae  
    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
    )rn   Úconnection_timer•   r1   r1   r2   r—   ¾  s   
zBaseController.connection_timec                 C   s   |   ¡ r| jS d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•   r1   r1   r2   r†   Ì  s   zBaseController.is_authenticatedc                 C   s   | j  ¡  dS )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)rn   Úconnectr•   r1   r1   r2   r˜   Ö  s   zBaseController.connectc                 C   s6   | j  ¡  | jD ]}| ¡ rt ¡ |kr| ¡  qdS )z
    Closes our socket connection. This is a pass-through for our socket's
    :func:`~stem.socket.BaseSocket.close` method.
    N)rn   r‘   r   r‚   ro   Úcurrent_threadra   ©rK   Útr1   r1   r2   r‘   à  s   

	€þzBaseController.closec                 C   ó   | j S )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
    )rn   r•   r1   r1   r2   Ú
get_socketó  ó   zBaseController.get_socketc                 C   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•   r1   r1   r2   Úget_latest_heartbeatý  rž   z#BaseController.get_latest_heartbeatTc                 C   s<   | j  | j ||f¡ W d  ƒ dS 1 sw   Y  dS )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©rs   rr   Úappend)rK   ÚcallbackÚspawnr1   r1   r2   Úadd_status_listener  s   "ÿz"BaseController.add_status_listenerc                 C   sj   | j ( g d}}| jD ]\}}||kr| ||f¡ qd}q|| _|W  d  ƒ S 1 s.w   Y  dS )a  
    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    )rK   r¢   Znew_listenersZ
is_changedÚlistenerr£   r1   r1   r2   Úremove_status_listener%  s   

$öz%BaseController.remove_status_listenerc                 C   s   | S rI   r1   r•   r1   r1   r2   Ú	__enter__;  s   zBaseController.__enter__c                 C   s   |   ¡  d S rI   )r‘   )rK   Z	exit_typeÚvalueÚ	tracebackr1   r1   r2   Ú__exit__>  s   zBaseController.__exit__c                 C   s   dS )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
    Nr1   )rK   Úevent_messager1   r1   r2   Ú_handle_eventA  s   	zBaseController._handle_eventc                 C   s&   |   ¡  |  tj¡ |  ¡  d| _d S ©NF)rƒ   Ú_notify_status_listenersÚStater   r|   r€   r•   r1   r1   r2   r{   L  s   
zBaseController._connectc                 C   sZ   | j  ¡  d| _| j| jfD ]}|r | ¡ r t ¡ |kr | ¡  q|  	t
j¡ |  ¡  d S r­   )ry   Úsetr€   rx   rz   r‚   ro   r™   ra   r®   r¯   r
   r~   rš   r1   r1   r2   r}   R  s   
€zBaseController._closec                 C   s
   d| _ d S )NT)r€   r•   r1   r1   r2   r„   d  s   
z#BaseController._post_authenticationc              	   C   s<  | j  ¡  | js d}|tjtjfv rd}n|tjkrd}t ¡ }|dur;||  ¡ kr;	 W d  ƒ W d  ƒ dS t	t
dd„ | jƒƒ| _| jD ]+\}}|rn| ||f}tj||d| d}| d¡ | ¡  | j |¡ qI|| ||ƒ qIW d  ƒ n1 sw   Y  W d  ƒ dS W d  ƒ dS 1 s—w   Y  dS )z‰
    Informs our status listeners that a state change occurred.

    :param stem.control.State state: state change that has occurred
    NTFc                 S   s   |   ¡ S rI   )r‚   )r›   r1   r1   r2   Ú<lambda>ˆ  s    z9BaseController._notify_status_listeners.<locals>.<lambda>z%s notification)ÚtargetrB   Úname)rn   Ú_get_send_lockrs   r¯   r   r	   r
   Útimer‚   ÚlistÚfilterr   rr   ro   ÚThreadÚ	setDaemonÚstartr¡   )rK   ÚstateZexpect_aliveZchange_timestampr¥   r£   rB   Znotice_threadr1   r1   r2   r®   i  s4   

îÿ

÷êÿ"ÿz'BaseController._notify_status_listenersc                 C   s°   | j  ¡ I | jr| j ¡ s"tj| jdd| _| j d¡ | j ¡  | j	r*| j	 ¡ sFtj| j
dd| _	| j	 d¡ | j	 ¡  W d  ƒ dS W d  ƒ dS 1 sQw   Y  dS )zq
    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)rn   r´   rx   r‚   ro   r¸   Ú_reader_loopr¹   rº   rz   Ú_event_loopr•   r1   r1   r2   rƒ   •  s   	
÷"úzBaseController._launch_threadsc              
   C   sœ   |   ¡ rLz(| j ¡ }t ¡ | _| ¡ d d dkr%| j |¡ | j 	¡  n| j
 |¡ W n tjyE } z| j
 |¡ W Y d}~nd}~ww |   ¡ sdS dS )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   Z650N)r‚   rn   Zrecvrµ   r   Úcontentrw   Úputry   r°   rv   r]   r   )rK   Zcontrol_messagerj   r1   r1   r2   r¼   ©  s   	

€€úôzBaseController._reader_loopc                 C   s   d}	 z'| j  ¡ }|  |¡ | j  ¡  |  ¡ s)|st ¡ }nt ¡ | tkr)W dS W n tjyF   |  ¡ s9Y dS | j	 
d¡ | j	 ¡  Y nw q)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.
    NTçš™™™™™©?)rw   r‰   r¬   Z	task_doner‚   rµ   ÚEVENTS_LISTENING_TIMEOUTrt   r   ry   ÚwaitÚclear)rK   Zsocket_closed_atr«   r1   r1   r2   r½   Æ  s&   



€ûózBaseController._event_loopN©F)T)r-   r.   r/   r0   r‡   r“   r‚   r–   r—   r†   r˜   r‘   r   rŸ   r¤   r¦   r§   rª   r¬   r{   r}   r„   r®   rƒ   r¼   r½   r1   r1   r1   r2   rl      s0    
&S





,rl   c                       sÊ  e Zd ZdZed¢dd„ƒZed£dd„ƒZd¤‡ fd
d„	Z‡ fdd„Zdd„ Z	dd„ Z
eƒ ed	fdd„ƒZeƒ efdd„ƒZeƒ efdd„ƒZeƒ efdd„ƒZeƒ efdd„ƒZeƒ efdd„ƒZefdd„Zeƒ efd d!„ƒZeƒ efd"d#„ƒZeƒ efd$d%„ƒZeƒ efd&d'„ƒZeƒ efd(d)„ƒZd*d+„ Zeƒ d,efd-d.„ƒZed/d0efd1d2„ƒZeƒ d,efd3d4„ƒZed/d0efd5d6„ƒZd7d8„ Zeƒ d,efd9d:„ƒZed/d0efd;d<„ƒZ eƒ ed,d/d,fd=d>„ƒZ!ed	fd?d@„Z"ed/fdAdB„Z#dCdD„ Z$eƒ efdEdF„ƒZ%dGdH„ Z&dIdJ„ Z'dKdL„ Z(d¤dMdN„Z)eƒ efdOdP„ƒZ*dQdR„ Z+d¥dSdT„Z,d¦dUdV„Z-eƒ ed/d	fdWdX„ƒZ.d§d[d\„Z/d]d^„ Z0d_d`„ Z1dadb„ Z2d¦dcdd„Z3d¦dedf„Z4d¦dgdh„Z5didj„ Z6dkdl„ Z7dmdn„ Z8dodp„ Z9dqdr„ Z:d¤dsdt„Z;dudv„ Z<dwdx„ Z=eƒ efdydz„ƒZ>eƒ efd{d|„ƒZ?d¨d~d„Z@d©dd‚„ZAdƒd„„ ZBdªd†d‡„ZCeƒ efdˆd‰„ƒZDd¦dŠd‹„ZEeFjGjHd…fdŒd„ZIdŽd„ ZJdd‘„ ZKd’d“„ ZLeƒ ed	fd”d•„ƒZMd–d—„ ZNd˜d™„ ZOdšd›„ ZP‡ fdœd„ZQdždŸ„ ZRd d¡„ ZS‡  ZTS )«Ú
Controllerz‘
  Connection with Tor's control socket. This is built on top of the
  BaseController and provides a more user friendly API for library users.
  ú	127.0.0.1r@   c                 C   sv   ddl }|jj | ¡std|  ƒ‚|dkr"|jj |¡s"td| ƒ‚|dkr0|j | ¡}t	|ƒS |j | |¡}t	|ƒS )aO  
    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: %sr@   zInvalid port: %s)
Ústem.connectionr^   Ú
connectionÚis_valid_ipv4_addressÚ
ValueErrorÚis_valid_portZ_connection_for_default_portÚsocketÚControlPortrÆ   )r%   Úportr]   Zcontrol_portr1   r1   r2   Ú	from_portë  s   þzController.from_portú/var/run/tor/controlc                 C   s   t j | ¡}t|ƒS )a4  
    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]   rÍ   ÚControlSocketFilerÆ   )r;   r…   r1   r1   r2   Úfrom_socket_file  s   zController.from_socket_fileFc                    s¨   dˆ _ i ˆ _dˆ _t ¡ ˆ _i ˆ _t ¡ ˆ _g ˆ _d ˆ _	d ˆ _
d ˆ _ttˆ ƒ ||¡ ‡ fdd„}ˆ  |tj¡ ‡ fdd„}ˆ  |tj¡ ‡ fdd„}ˆ  |tj¡ d S )	NTrm   c                    s(   | j tjkrˆ  ¡  ˆ  tj¡ d S d S rI   )Úsignalr   ZRELOADÚclear_cacher®   r¯   r	   ©ri   r•   r1   r2   Ú_sighup_listener/  s   þz-Controller.__init__.<locals>._sighup_listenerc                    sj   ˆ   ¡ r3tdd„ | j ¡ D ƒƒ}tdd„ | jD ƒƒ}i }| |¡ | |¡ ˆ  |d¡ ˆ  |¡ d S d S )Nc                 s   ó     | ]\}}|  ¡ |fV  qd S rI   ©rW   ©rX   ÚkÚvr1   r1   r2   Ú	<genexpr>8  ó   € zEController.__init__.<locals>._confchanged_listener.<locals>.<genexpr>c                 s   s    | ]	}|  ¡ g fV  qd S rI   rÙ   ©rX   rÛ   r1   r1   r2   rÝ   9  ó   € Úgetconf)Úis_caching_enabledre   ZchangedÚitemsZunsetÚupdateÚ
_set_cacheÚ_confchanged_cache_invalidation)ri   Zto_cache_changedZto_cache_unsetÚto_cacher•   r1   r2   Ú_confchanged_listener6  s   

öz2Controller.__init__.<locals>._confchanged_listenerc                    s6   | j dv rˆ  dd i¡ ˆ  dd id¡ d ˆ _d S d S )N)ZEXTERNAL_ADDRESSZDNS_USELESSÚexit_policyr%   Úgetinfo)Úactionrå   Ú_last_address_excrÖ   r•   r1   r2   Ú_address_changed_listenerE  s
   

ýz6Controller.__init__.<locals>._address_changed_listener)Ú_is_caching_enabledÚ_request_cacheÚ_last_newnymro   rp   Ú_cache_lockÚ_event_listenersÚ_event_listeners_lockÚ_enabled_featuresÚ_is_geoip_unavailablerì   Ú_last_fingerprint_excÚsuperrÆ   r‡   Úadd_event_listenerÚ	EventTyper   r   r   )rK   r…   r†   r×   rè   rí   ©Ú	__class__r•   r2   r‡     s"   

zController.__init__c                    s   |   ¡  tt| ƒ ¡  d S rI   )rÕ   r÷   rÆ   r‘   r•   rú   r1   r2   r‘   M  s   zController.closec                 O   s&   ddl }|jj| g|¢R i |¤Ž dS )z‡
    A convenience method to authenticate the controller. This is just a
    pass-through to :func:`stem.connection.authenticate`.
    r   N)rÈ   rÉ   Úauthenticate)rK   rB   rG   r]   r1   r1   r2   rü   Q  s   zController.authenticatec                 O   sL   | j  |  ¡  |  ¡  | j|i |¤Ž W d  ƒ dS 1 sw   Y  dS )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)rq   r˜   rÕ   rü   )rK   rB   rG   r1   r1   r2   Ú	reconnectZ  s
   "ýzController.reconnectc              
   C   s  t   ¡ }i }tj |¡rd}t|gƒ}n
|si S d}t|ƒ}|D ]0}| d¡r4|dkr4|  ¡ r4t d¡‚|dkr>| jr>| j‚|dkrP| j	rP|  
dd	¡d	u rP| j	‚q d
d„ |D ƒ}|  |d¡}	|	D ]}
t||
ƒ}|	|
 ||< | |¡ q`|strƒt dd | ¡ ¡ ¡ |r‡|S t| ¡ ƒd S z|  dd |¡ ¡}tj d|¡ | |¡ tj ¡ rº|sºtdd„ |j ¡ D ƒƒ|_| |j¡ |  ¡ rði }|j ¡ D ]\}
}|
  ¡ }
|
t!v sÛ|
t"v rà|||
< qË|
 d¡ré|||
< qË|  #|d¡ d|v r÷d	| _d|v rþd	| _	t $dd |¡t   ¡ | f ¡ |r|W S t| ¡ ƒd W S  tj%yG } zd|v r.|| _d|v r6|| _	t $dd |¡|f ¡ ‚ d	}~ww )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 unavailabler%   r(   ÚORPortNc                 S   ó   g | ]}|  ¡ ‘qS r1   rÙ   ©rX   Úparamr1   r1   r2   r[   ¥  ó    z'Controller.get_info.<locals>.<listcomp>rê   zGETINFO %s (cache fetch)ú r   z
GETINFO %sZGETINFOc                 s   s&    | ]\}}|t jj |¡fV  qd S rI   )r]   r^   Ú	str_toolsÚ_to_unicoderÚ   r1   r1   r2   rÝ   ¿  s   €$ z&Controller.get_info.<locals>.<genexpr>zGETINFO %s (runtime: %0.4f)zGETINFO %s (failed: %s))&rµ   r]   r^   Ú_is_strr°   rV   Úis_geoip_unavailabler‹   rì   rö   Úget_confÚ_get_cache_mapÚ_case_insensitive_lookupÚremoveÚLOG_CACHE_FETCHESr   Útracera   rf   r¶   Úvaluesr“   rŽ   ÚconvertZ_assert_matchesZprereqZis_python_3re   Úentriesrã   rä   râ   rW   ÚCACHEABLE_GETINFO_PARAMSÚ&CACHEABLE_GETINFO_PARAMS_UNTIL_SETCONFrå   Údebugr   )rK   Úparamsr@   Ú	get_bytesÚ
start_timeÚreplyZis_multipler  Ú
from_cacheÚcached_resultsrY   Úuser_expected_keyrŽ   rç   r¨   rj   r1   r1   r2   Úget_infoj  s~   $
€



€ 

€øzController.get_infoc                 C   sL   |   d¡}|s$|  d¡}tj | d¡r|dd… n|¡}|  d|i¡ |S )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.
    r&   zTor é   N)Ú
_get_cacher  r]   r&   ZVersionrV   rå   )rK   r@   r&   Zversion_strr1   r1   r2   Úget_versionæ  s   

"zController.get_versionc              
   C   sÔ   |   d¡}|shztjj|  d¡ ¡ Ž }|  d|i¡ W |S  tjyg   g }|  d¡dkr2| 	d¡ |  d¡dkr>| 	d¡ | jd	d
dD ]	}|| 
d¡7 }qE||  d¡ 
d¡7 }tj ||  dd¡¡}Y |S w |S )a¥  
    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.
    ré   zexit-policy/fullZ	ExitRelayÚ0z
reject *:*ZExitPolicyRejectPrivateÚ1zreject private:*Ú
ExitPolicyT©Úmultipleú,r'   r%   N)r  r]   ré   r"  r  Ú
splitlinesrå   ÚOperationFailedr	  r¡   ÚsplitZget_config_policy)rK   r@   ZpolicyZrulesZpolicy_liner1   r1   r2   Úget_exit_policy  s&   
"ß

ß!zController.get_exit_policyc                    s$   ‡fdd„‰ ‡ fdd„|   ˆ¡D ƒS )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                    sV   t jj | ¡r| dkp|  d¡S t jj | ¡r t jj | ¡dv S t dˆ | f ¡ dS )Nz0.0.0.0z127.)z'0000:0000:0000:0000:0000:0000:0000:0000z'0000:0000:0000:0000:0000:0000:0000:0001zCRequest for %s ports got an address that's neither IPv4 or IPv6: %sF)	r]   r^   rÉ   rÊ   rV   Úis_valid_ipv6_addressZexpand_ipv6_addressr   rŒ   )r%   )Úlistener_typer1   r2   r–   [  s   z*Controller.get_ports.<locals>.is_localhostc                    s   g | ]
\}}ˆ |ƒr|‘qS r1   r1   ©rX   ÚaddrrÏ   )r–   r1   r2   r[   g  ó    z(Controller.get_ports.<locals>.<listcomp>)Úget_listeners)rK   r+  r@   r1   )r–   r+  r2   Ú	get_portsD  s   zController.get_portsc                 C   sL  |   |d¡}|du r$g }d| ¡  }zV|  |¡ ¡ D ]L}| d¡r'| d¡s0t d||f ¡‚d|vr=t d||f ¡‚|dd	… }| dd¡\}}|d
krPq| d¡r`| d¡r`|dd	… }| 	||f¡ qW nz tj
yã   tjdtjdtjdtjdtjdtjdtjdi| }	tjdtjdtjdtjdtjdtjdtjdi| }
|  |	¡ ¡ d }| j|
ddD ]-}d|v rÙ| dd¡\}}| d¡rÑ| d¡rÑ|dd	… }| 	||f¡ q³| 	||f¡ q³Y nw |D ].\}}tjj |¡stjj |¡st d||f ¡‚tjj |¡st d||f ¡‚qæd d!„ |D ƒ}|  ||id¡ |S )"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
    Ú	listenersNznet/listeners/%sú"z4'GETINFO %s' responses are expected to be quoted: %sú:z/'GETINFO %s' had a listener without a colon: %sr?   r¾   Zunixú[ú]rÿ   ZDirPortZ	SocksPortZ	TransPortZNatdPortZDNSPortrÎ   ZORListenAddressZDirListenAddressZSocksListenAddressZTransListenAddressZNatdListenAddressZDNSListenAddressZControlListenAddressr   Tr#  z%Invalid address for a %s listener: %sz"Invalid port for a %s listener: %sc                 S   s   g | ]
\}}|t |ƒf‘qS r1   ©Úintr,  r1   r1   r2   r[   Î  r.  z,Controller.get_listeners.<locals>.<listcomp>)r  rW   r  r(  rV   Úendswithr]   r‹   Úrsplitr¡   ÚInvalidArgumentsÚListenerr   r   r   r   r   r   r   r	  r^   rÉ   rÊ   r*  rÌ   rå   )rK   r+  r@   r1  Zproxy_addrsÚqueryr¥   r-  rÏ   Zport_optionZlistener_optionZ
port_valuer1   r1   r2   r/  i  st   
ëùøùø
÷å( ÿzController.get_listenersc                 C   sÆ   |   d¡dkrt d¡‚t ¡ }|   d¡}|   d¡}|   d¡}|   d¡}tjj |¡}dd	„ | d
d¡D ƒ\}}dd	„ | d
d¡D ƒ\}	}
t|||t	dt
 | ¡ ¡t|ƒ ƒ||	||	 ||
||
 d
S )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
    r)   r!  zAccounting isn't enabledzaccounting/hibernatingzaccounting/interval-endzaccounting/byteszaccounting/bytes-leftc                 S   ó   g | ]}t |ƒ‘qS r1   r6  ©rX   rN   r1   r1   r2   r[   ï  r  z3Controller.get_accounting_stats.<locals>.<listcomp>r  r?   c                 S   r=  r1   r6  r>  r1   r1   r2   r[   ð  r  r   r4   )r  r]   r   rµ   r^   r  Z_parse_timestampr(  r+   ÚmaxÚcalendarZtimegmZ	timetupler7  )rK   r@   r5   r6   r7   ÚusedÚleftZ	used_readZused_writtenZ	left_readZleft_writtenr1   r1   r2   Úget_accounting_statsÓ  s,   




özController.get_accounting_statsc                 C   s   |   tj|¡S )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   ©rK   r@   r1   r1   r2   Úget_socks_listenersÿ  s   zController.get_socks_listenersc                 C   s   ddl }|j | ¡S )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È   rÉ   Úget_protocolinfo)rK   r@   r]   r1   r1   r2   rF    s   zController.get_protocolinfoc                 C   sr   |   d¡}|r	|S |  dd¡}|s#|  ¡ r#|  d¡}|r#tjj |¡}|r.|  d|i¡ |S t	|  ¡ r6dƒ‚dƒ‚)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^   ÚsystemrG  rå   rË   )rK   r@   rG  Úpidr1   r1   r2   Úget_user)  s   

zController.get_userc                 C   s  |   d¡}|r	|S |  dd¡}|r| ¡ rt|ƒ}|sy|  ¡ ry|  dd¡}|durKt|ƒ}| ¡  ¡ }| ¡ r<t|ƒ}W d  ƒ n1 sFw   Y  |sTt	j
j d¡}|sy|  ¡ }t|t	jjƒrjt	j
j |j¡}nt|t	jjƒryt	j
j |j¡}|r„|  d|i¡ |S t|  ¡ rŒdƒ‚dƒ‚)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
    rK  zprocess/pidNr   ZtorzUnable to resolve tor's pidrH  )r  r  Úisdigitr7  r–   r	  ÚopenÚreadÚstripr]   r^   rJ  Zpid_by_namer   rŠ   rÍ   rÎ   Zpid_by_portrÏ   rÒ   Zpid_by_open_filer;   rå   rË   )rK   r@   rK  Zgetinfo_pidZpid_file_pathZpid_fileZpid_file_contentsr…   r1   r1   r2   rI  L  s6   

€üzController.get_pidc                 C   sÄ   |   d¡}|r	|S |  ¡ tjjjkr,|  dd¡}|r,| ¡ s$td| ƒ‚t	 	¡ t
|ƒ }|sL|  ¡ rL|  ¡ s:tdƒ‚|  d¡}|sEtdƒ‚tjj |¡}|rW|  d|i¡ |S t|  ¡ r_dƒ‚dƒ‚)	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 beganrH  )r  r  r]   r&   ÚRequirementZGETINFO_UPTIMEr  rM  rË   rµ   Úfloatr–   rI  r^   rJ  r  rå   )rK   r@   r  rQ  rK  r1   r1   r2   Úget_start_time„  s(   

zController.get_start_timec                 C   s   t   ¡ |  ¡  S )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µ   rT  rD  r1   r1   r2   Ú
get_uptime·  s   zController.get_uptimec                 C   sf   d\}}|   dd¡dkrd}|   dd¡r.|s#| jdd}|o"d|jv }|  d¡}|o-| ¡ }t||ƒS )	ag  
    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
    )FFZBridgeRelayNr!  Trÿ   ©r@   ZGuard)r	  Úget_network_statusÚflagsr)  Zis_exiting_allowedr8   )rK   Zinbound_allowedZoutbound_allowedZconsensus_entryré   r1   r1   r2   Úis_user_traffic_allowedÊ  s   

z"Controller.is_user_traffic_allowedNc              
   C   óä   |du r z|   d¡}W n tjy } zt d| ¡‚d}~ww tjj |¡r,d| }ntjj |¡r8d| }ntd| ƒ‚z	| j |dd}W n tjyc } zt	|ƒ 
d	¡r^t d
| ¡‚‚ d}~ww |skt d¡‚tjj |¡S )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.
    Nr(   ú+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_nicknamerË   r:  ÚstrrV   ÚDescriptorUnavailableÚ
descriptorÚmicrodescriptorÚMicrodescriptor©rK   Zrelayr@   rj   r<  Údesc_contentr1   r1   r2   Úget_microdescriptoró  s.    €ÿ

€ü
zController.get_microdescriptorTrQ   c                 c   s   |   ¡ tjjjkr*| jddd}|st d¡‚tjj 	t
 |¡¡D ]}|V  q"dS |  dd¡}|du r:tjdd‚tj |¡sHtjd	| d‚d}d
D ]}tj ||¡}tj |¡r_|} nqL|du rltjd| d‚tj |¡D ]}t|tjjjƒs†tjdt|ƒ d‚|V  qrdS )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`  r   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]   r&   rR  ZGETINFO_MICRODESCRIPTORSr  re  rf  rg  Ú_parse_fileÚioÚBytesIOr	  r'  r`   r;   Úexistsra   Z
parse_filerŠ   rh  Útype)rK   r@   rj  ÚdescZdata_directoryZmicrodescriptor_fileÚfilenameZcached_descriptorsr1   r1   r2   Úget_microdescriptors-  s6   €
ÿþùzController.get_microdescriptorsc              
   C   s   zs|du r!z|   d¡}W n tjy  } zt d| ¡‚d}~ww tjj |¡r-d| }ntjj |¡r9d| }ntd| ƒ‚z	| j |dd}W n tjyd } zt	|ƒ 
d	¡r_t d
| ¡‚‚ d}~ww |slt d¡‚tjj |¡W S    |  ¡ sttƒ‚‚ )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.
    Nr(   r[  z
desc/id/%szdesc/name/%sr\  Tr]  r^  r_  r`  )r  r]   r   r^   ra  rb  rc  rË   r:  rd  rV   re  rf  Úserver_descriptorZRelayDescriptorÚ _is_server_descriptors_availableÚSERVER_DESCRIPTORS_UNSUPPORTEDri  r1   r1   r2   Úget_server_descriptorl  s8   %€ÿ

€ü
z Controller.get_server_descriptorc                 c   sT    | j ddd}|s|  ¡ st t¡‚t d¡‚tjj t	 
|¡¡D ]}|V  q"dS )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  rv  r]   r   rw  re  rf  ru  rm  rn  ro  )rK   r@   rj  rr  r1   r1   r2   Úget_server_descriptors±  s   €

ÿz!Controller.get_server_descriptorsc                 C   s"   |   ¡ tjjjk p|  dd¡dkS )zM
    Checks to see if tor server descriptors should be available or not.
    ZUseMicrodescriptorsNr   )r  r]   r&   rR  ZMICRODESCRIPTOR_IS_DEFAULTr	  r•   r1   r1   r2   rv  Ø  s   
ÿz+Controller._is_server_descriptors_availablec              
   C   rZ  )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.
    Nr(   r[  zns/id/%sz
ns/name/%sr\  Tr]  r^  r_  r`  )r  r]   r   r^   ra  rb  rc  rË   r:  rd  rV   re  rf  Úrouter_status_entryÚRouterStatusEntryV3ri  r1   r1   r2   rW  å  s.   !€ÿ

€ü
zController.get_network_statusc                 c   sR    | j ddd}|st d¡‚tjjjt |¡dtjjjd}|D ]}|V  q!dS )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)Zentry_classN)	r  r]   re  rf  rz  rm  rn  ro  r{  )rK   r@   rj  Zdesc_iteratorrr  r1   r1   r2   Úget_network_statuses   s   €
ýÿzController.get_network_statusesc              	      sú  |  d¡r|dd… }tjj |¡std| ƒ‚|  ¡ tjjj	k r,tj
dtjjj	 d‚t ¡ d‰}t ¡ d‰ }t ¡ }|rZ‡fdd„}‡ fd	d
„}|  |tj¡ |  |tj¡ z’d| }	|ro|	dd dd„ |D ƒ¡ 7 }	|  |	¡}
tj d|
¡ |
 ¡ s‡t d|
j ¡‚|sœW |r‘|  |¡ |rš|  |¡ dS dS 	 tˆ ||ƒ}|j|krì|jr¾|jW |rµ|  |¡ |r½|  |¡ S S 	 tˆ||ƒ}|j|krë|jtjjkrë|j tj!j"krßt #d| ¡‚t #d||j$|j f ¡‚q¿q|rô|  |¡ |rü|  |¡ w w )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.
    ú.onionNiúÿÿÿz/'%s.onion' isn't a valid hidden service addressz#HSFETCH was added in tor version %srl  c                    ó   ˆ   | ¡ d S rI   ©rÀ   rÖ   ©Úhs_desc_queuer1   r2   Úhs_desc_listenery  ó   zBController.get_hidden_service_descriptor.<locals>.hs_desc_listenerc                    r~  rI   r  rÖ   )Úhs_desc_content_queuer1   r2   Úhs_desc_content_listener|  rƒ  zJController.get_hidden_service_descriptor.<locals>.hs_desc_content_listenerz
HSFETCH %sr  c                 S   s   g | ]}d | ‘qS )z	SERVER=%sr1   )rX   Úsr1   r1   r2   r[   †  r  z<Controller.get_hidden_service_descriptor.<locals>.<listcomp>Ú
SINGLELINEz-HSFETCH returned unexpected response code: %sTz%No running hidden service at %s.onionzFUnable to retrieve the descriptor for %s.onion (retrieved from %s): %s)%r8  r]   r^   ra  Zis_valid_hidden_service_addressrË   r  r&   rR  ZHSFETCHÚUnsatisfiableRequestrt   ru   rµ   rø   rù   r   r   ra   r“   rŽ   r  Úis_okr‹   ÚcodeÚremove_event_listenerÚ_get_with_timeoutr%   rf  rë   ÚHSDescActionÚFAILEDÚreasonZHSDescReasonZ	NOT_FOUNDre  Údirectory_fingerprint)rK   r%   r@   ZserversZawait_resultÚtimeoutr‚  r…  r  ÚrequestrŽ   ri   r1   )r„  r  r2   Úget_hidden_service_descriptorE  sh   
&

ÿë

ÿôù÷
ÿz(Controller.get_hidden_service_descriptorc                 C   s:   |  ¡  ¡ }|s|tkr|S dS |  |||¡}t|||ƒS )a7  
    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)rW   rP  r   Úget_conf_mapr  )rK   r  r@   r$  r  r1   r1   r2   r	  ©  s
   )zController.get_confc              
      sê  t   ¡ }i }tj |¡r|g}dd„ |D ƒ}|g kri S tdd„ |D ƒƒ}dd„ |D ƒ}|  |d¡}|D ]}	t||	ƒ}
||	 ||
< | |
¡ q4|s^trWt	 
dd | ¡ ¡ ¡ |  |ˆ |¡S zg|  dd |¡ ¡}tj d	|¡ | |j¡ |  ¡ rŒtd
d„ |j ¡ D ƒƒ}|  |d¡ t|ƒD ]}	|	 ¡ t ¡ vr­t||	|	ƒ}
|	|
kr­||	 ||
< ||	= qt	 dd |¡t   ¡ | f ¡ |  |ˆ |¡W S  tjyô } z"t	 dd |¡|f ¡ ˆ tkrït‡ fdd„|D ƒƒW  Y d}~S ‚ d}~ww )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
    c                 S   s   g | ]}|  ¡ r|‘qS r1   ©rP  ©rX   Úentryr1   r1   r2   r[   	  ó    z+Controller.get_conf_map.<locals>.<listcomp>c                 S   s   g | ]}t  ||¡‘qS r1   )ÚMAPPED_CONFIG_KEYSrE   r–  r1   r1   r2   r[   	  r˜  c                 S   r   r1   rÙ   r  r1   r1   r2   r[   	  r  rá   zGETCONF %s (cache fetch)r  z
GETCONF %sÚGETCONFc                 s   rØ   rI   rÙ   rÚ   r1   r1   r2   rÝ   0	  rÞ   z*Controller.get_conf_map.<locals>.<genexpr>zGETCONF %s (runtime: %0.4f)zGETCONF %s (failed: %s)c                 3   s    | ]}|ˆ fV  qd S rI   r1   r  rV  r1   r2   rÝ   L	  s   € N)rµ   r]   r^   r  r°   r
  r  r  r  r   r  ra   rf   Ú_get_conf_dict_to_responser“   rŽ   r  rä   r  râ   re   rã   rå   r¶   rW   r™  r  r  r   r   )rK   r  r@   r$  r  r  Zlookup_paramsr  r  rY   r  rŽ   rç   rj   r1   rV  r2   r”  Ú  sR   0
€ "€úzController.get_conf_mapc                 C   s^   i }t | ¡ ƒD ]$\}}|g kr"|tkr|||< q|rg nd||< q|r&|n|d ||< q|S )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¶   rã   r   )rK   Zconfig_dictr@   r$  Zreturn_dictrY   r  r1   r1   r2   r›  P	  s   
z%Controller._get_conf_dict_to_responsec                 C   s   ||   ¡ v S )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)rK   r  r@   r1   r1   r2   Úis_sete	  s   zController.is_setc                 C   sr   |   d¡}|s7|  d¡ ¡ }ddd|  d¡ df}|D ]}||v r&| |¡ qtdd	„ |D ƒƒ}|  d|i¡ |S )
NÚget_custom_optionszconfig-textzLog notice stdoutz Log notice file /var/log/tor/logzDataDirectory /home/%s/.torZ	undefinedzHiddenServiceStatistics 0c                 S   s   g | ]}|  d d¡‘qS )r  r?   )r(  )rX   Úliner1   r1   r2   r[   	  r˜  z2Controller._get_custom_options.<locals>.<listcomp>)r  r  r&  rL  r  re   rå   )rK   ÚresultZconfig_linesZdefault_linesrŸ  r1   r1   r2   rœ  z	  s   
ü
€zController._get_custom_optionsc                 C   s   |   ||id¡ dS )a®  
    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)rK   r  r¨   r1   r1   r2   Úset_conf•	  s   zController.set_confc                 G   s   |   tdd„ |D ƒƒd¡ dS )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
    c                 S   s   g | ]}|d f‘qS rI   r1   r–  r1   r1   r2   r[   ¸	  r  z)Controller.reset_conf.<locals>.<listcomp>TN)r¡  re   ©rK   r  r1   r1   r2   Ú
reset_conf«	  s   zController.reset_confc                    sê  t   ¡ }|rdndg}t|tƒrt| ¡ ƒ}|D ];\‰ }t|tƒr-| dˆ | ¡ f ¡ qt|tj	ƒr@| 
‡ fdd„|D ƒ¡ q|sH| ˆ ¡ qtdˆ |t|ƒjf ƒ‚d |¡}|  |¡}tj d|¡ | ¡ r”t d	|t   ¡ | f ¡ |  ¡ r’td
d„ |D ƒƒ}|  |d¡ |  t|ƒ¡ dS dS t d||j|jf ¡ dd„ |D ƒ}	|	r·tjdd t|	ƒ¡ |	d‚|jdkrà|j d¡rØ|jd|j dd¡… }
t |j|j|
g¡‚t |j|j¡‚|jdv rít |j|j¡‚t  d|j ¡‚)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
    Z	RESETCONFZSETCONFú%s="%s"c                    s   g | ]
}d ˆ |  ¡ f ‘qS )r¥  r•  r>  ©r  r1   r2   r[   è	  r.  z*Controller.set_options.<locals>.<listcomp>zGCannot set %s to %s since the value was a %s but we only accept stringsr  r‡  z%s (runtime: %0.4f)c                 s   s     | ]\}}|  ¡ d fV  qd S rI   rÙ   rÚ   r1   r1   r2   rÝ   ÷	  rÞ   z)Controller.set_options.<locals>.<genexpr>rá   z"%s (failed, code: %s, message: %s)c                 S   s*   g | ]\}}t jj |¡ ¡ tv r|‘qS r1   )r]   r^   r  r  rW   ÚIMMUTABLE_CONFIG_OPTIONSrÚ   r1   r1   r2   r[   ü	  s   * z(%s cannot be changed while tor's runningú, )r’   Z	argumentsÚ552z%Unrecognized option: Unknown option 'é%   ú')Z513Ú553z#Returned unexpected status code: %sN)!rµ   rŠ   re   r¶   rã   rd  r¡   rP  ÚcollectionsÚIterableÚextendrË   rq  r-   ra   r“   r]   rŽ   r  r‰  r   r  râ   rå   ræ   rŠ  r’   r:  ÚsortedrV   ÚfindÚInvalidRequestr‹   )rK   r  Úresetr  Z
query_compr¨   r<  rŽ   rç   Zimmutable_paramsrY   r1   r¦  r2   r¡  º	  sD   "



ü

zController.set_optionsc              
   C   sÌ  |   d¡}|durtrt d¡ |S t ¡ }z|  d¡}tj d|¡ t 	dt ¡ |  ¡ W n tj
yD } zt 	d| ¡ ‚ d}~ww tƒ }d}| ¡ D ]Ž\}}}	|	dkrXqNd	|	vr]qN|	 d	d
¡\}
}|
dkrr|}dg i||< qN|
dkrÖ| }}d}| ¡ s•| ¡ \}}| ¡ r|}n| dd
¡\}}tjj |¡s¥t d||	f ¡‚tjj |¡sµt d||	f ¡‚tjj |¡sÅt d||	f ¡‚|| d  t|ƒ|t|ƒf¡ qN||| |
< qN|  d|i¡ |S )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)r   ú=r?   ÚHiddenServiceDirÚHiddenServicePortrÇ   r3  z;GETCONF provided an invalid HiddenServicePort port (%s): %szEGETCONF provided an invalid HiddenServicePort target address (%s): %szBGETCONF provided an invalid HiddenServicePort target port (%s): %s)r  r  r   r  rµ   r“   r]   rŽ   r  r  r   r   r¿   r(  rM  r9  r^   rÉ   rÌ   r‹   rÊ   r¡   r7  rå   )rK   r@   Zservice_dir_mapr  rŽ   rj   Ú	directoryZstatus_codeZdividerr¿   rÛ   rÜ   rÏ   Útarget_portÚtarget_addressr²   r1   r1   r2   Úget_hidden_service_conf
  s\   
$



ÿ€þ"z"Controller.get_hidden_service_confc           
      C   sÐ   |s	|   d¡ dS g }|D ]S}| d|f¡ t||  ¡ ƒD ]A\}}|dkrV|D ],}t|tƒr6d||f }nt|tƒr<nt|tƒrM|\}}}	d|||	f }| d|f¡ q(q| |t|ƒf¡ qq|  |¡ dS )aO  
    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%s 127.0.0.1:%sz%s %s:%s)	r¤  r¡   r¶   rã   rŠ   r7  rd  Útupler¡  )
rK   r_   Zhidden_service_optionsr¸  rÛ   rÜ   r—  rÏ   rº  r¹  r1   r1   r2   Úset_hidden_service_confk
  s*   %




÷óz"Controller.set_hidden_service_confc                 C   s   t jj |¡std| ƒ‚|rt jj |¡std| ƒ‚|dur-t jj |¡s-td| ƒ‚|dvr7td| ƒ‚t|ƒ}|r?|nd}|du rG|nt|ƒ}|  ¡ }||v r`|||f|| d v r`dS | |t	ƒ ¡ dg ¡ 
|||f¡ |r„|r„d|d	 |¡f }||| d
< |D ]}d
|| v s”d|| v ršd|| d< q†|  |¡ di }	}
|  ¡ rHtj |d¡}tj |¡sËt jj |  d¡¡}|rËt jj ||¡}tj |¡rHt ¡ }tj |¡sòt ¡ | }|dkrçnt d¡ tj |¡rÜzQt|ƒB}| ¡  ¡ }	|r2d|	v r2|	 ¡ D ]'}d|v r0| ¡ d }| dd¡d }t|ƒdkr0| d¡r0||
|< q
W d  ƒ n	1 s=w   Y  W n   Y t||	|
|dS )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)NZbasicZstealthz,%s isn't a recognized type of authenticationrÇ   r·  z%s %sr%  ZHiddenServiceAuthorizeClientZRendPostPeriodÚ2ZHiddenServiceVersionr<   é   rÁ   Ú
z # client: r   r?   é   r}  r:   ) r]   r^   rÉ   rÌ   rË   rÊ   r7  r»  Ú
setdefaultr   r¡   ra   r½  r–   r`   r;   ÚisabsrJ  ÚcwdrI  Zexpand_pathrµ   rp  ÚsleeprN  rO  rP  r&  r(  rD   r8  r9   )rK   r;   rÏ   rº  r¹  Z	auth_typeZclient_namesr_   Zhsacr<   r=   Zhostname_pathrÅ  r  Z	wait_timeZhostname_filerŸ  r%   Zclientr1   r1   r2   Úcreate_hidden_service¬
  sv    "	€



ú

€ñ€üz Controller.create_hidden_servicec                    s¬   ˆ rt jj ˆ ¡stdˆ  ƒ‚ˆ rtˆ ƒnd‰ |  ¡ }||vr!dS ˆ s'||= n(‡ fdd„|| d D ƒ}|s8dS |D ]}|| d  |¡ q:|| d sO||= |  |¡ dS )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¾  NFc                    s   g | ]
}|d  ˆ kr|‘qS )r   r1   r–  ©rÏ   r1   r2   r[   =  r.  z4Controller.remove_hidden_service.<locals>.<listcomp>r·  T)	r]   r^   rÉ   rÌ   rË   r7  r»  r  r½  )rK   r;   rÏ   r_   Z	to_remover—  r1   rÈ  r2   Úremove_hidden_service"  s"   
z Controller.remove_hidden_servicec              
   C   sê   |   ¡ tjjjk rtjdtjjj d‚g }|rBz||  d¡ d¡7 }W n tjtj	fyA } zdt
|ƒvr7‚ W Y d}~nd}~ww |rnz||  d¡ d¡7 }W n tjtj	fym } zdt
|ƒvrc‚ W Y d}~nd}~ww dd	„ |D ƒS )
aF  
    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 %srl  zonions/currentrÁ  z(No onion services of the specified type.Nzonions/detachedc                 S   s   g | ]}|r|‘qS r1   r1   )rX   Úrr1   r1   r2   r[   ~  r  z=Controller.list_ephemeral_hidden_services.<locals>.<listcomp>)r  r]   r&   rR  Ú	ADD_ONIONrˆ  r  r(  r‹   r'  rd  )rK   r@   Zour_servicesÚdetachedr   rj   r1   r1   r2   Úlist_ephemeral_hidden_servicesK  s,   ÿ€ú	ÿ€ÿz)Controller.list_ephemeral_hidden_servicesÚNEWÚBESTc
              	      s  |   ¡ tjjjk rtjdtjjj d‚t ¡ d‰ }
t ¡ }|r.‡ fdd„}
|  	|
t
j¡ d||f }g }|r=| d¡ |rD| d¡ |dura|   ¡ tjjjk r\tjd	tjjj d‚| d
¡ |	dur~|   ¡ tjjjk rytjdtjjj d‚| d¡ |   ¡ tjjjkrœ|  dd¡dkrœ|  dd¡dkrœ| d¡ |r§|dd |¡ 7 }|	dur±|d|	 7 }t|tƒr½|d| 7 }n,t|tƒrÎ|D ]}|d| 7 }qÄnt|tƒrå| ¡ D ]\}}|d||f 7 }q×ntdƒ‚|dur	| ¡ D ]\}}|r|d||f 7 }qò|d| 7 }qò|  |¡}tj d|¡ |r‡g g }}zc	 tˆ ||ƒ}|jtjjkr;|j|j kr;| |j!¡ n<|jtjj"krJ|j!|v rJn/|jtjj#krw|j!|v rw| d|j!|j$f ¡ t%|ƒt%|ƒkrwtj&dd |¡ d‚qW |  '|
¡ |S |  '|
¡ w |S )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',
      })

    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.

    :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 this service
    :param int max_streams: maximum number of streams the hidden service will
      accept, unlimited if zero or not set

    :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Ê  rl  Nc                    r~  rI   r  rÖ   r€  r1   r2   r‚  í  rƒ  zDController.create_ephemeral_hidden_service.<locals>.hs_desc_listenerzADD_ONION %s:%sZ	DiscardPKZDetachzEBasic authentication support was added to ADD_ONION in tor version %sZ	BasicAuthz^Limitation of the maximum number of streams to accept was added to ADD_ONION in tor version %sZMaxStreamsCloseCircuitr   r!  r   ZNonAnonymousz	 Flags=%sr%  z MaxStreams=%sz Port=%sz Port=%s,%sz[The 'ports' argument of create_ephemeral_hidden_service() needs to be an int, list, or dictz ClientAuth=%s:%sz ClientAuth=%srÌ  Tz%s (%s)z4Failed to upload our hidden service descriptor to %sr¨  )(r  r]   r&   rR  rÌ  rˆ  rt   ru   rµ   rø   rù   r   r¡   ZADD_ONION_BASIC_AUTHZADD_ONION_MAX_STREAMSZADD_ONION_NON_ANONYMOUSr	  ra   rŠ   r7  r¶   re   rã   rË   r“   rŽ   r  rŒ  rë   r  ZUPLOADr%   Ú
service_idr  ZUPLOADEDrŽ  r  rD   r'  r‹  )rK   ZportsZkey_typeZkey_contentZdiscard_keyrÍ  Zawait_publicationr‘  Z
basic_authZmax_streamsr‚  r  r’  rX  rÏ   r²   Zclient_nameZclient_blobrŽ   Zdirectories_uploaded_toZfailuresri   r1   r€  r2   Úcreate_ephemeral_hidden_service€  s‚   f



 


ÿ
ÿ


õ
þz*Controller.create_ephemeral_hidden_servicec                 C   sn   |   ¡ tjjjk rtjdtjjj d‚|  d| ¡}tj d|¡ | 	¡ r(dS |j
dkr/dS t d|j
 ¡‚)	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Ê  rl  zDEL_ONION %sr‡  Tr©  Fz/DEL_ONION returned unexpected response code: %s)r  r]   r&   rR  rÌ  rˆ  r“   rŽ   r  r‰  rŠ  r‹   )rK   rÑ  rŽ   r1   r1   r2   Úremove_ephemeral_hidden_serviceB  s   
z*Controller.remove_ephemeral_hidden_servicec                 G   sÊ   | j X |  ¡ r)|D ]}tjjj |¡}|r(|  ¡ |jk r(t 	dd||jf ¡‚q
|D ]}| j
 |g ¡ |¡ q+|  ¡ d }t|ƒ t|ƒ¡}|rSt dd |¡ ¡‚W d  ƒ dS 1 s^w   Y  dS )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)%s event requires Tor version %s or laterr?   zSETEVENTS rejected %sr¨  N)ró   r†   r]   rŽ   ÚeventsZEVENT_TYPE_TO_CLASSrE   r  Z_VERSION_ADDEDr²  rò   rÃ  r¡   Ú_attach_listenersr°   Úintersectionr‹   ra   )rK   r¥   rÔ  Ú
event_typeÚfailed_eventsr1   r1   r2   rø   ^  s   &€ÿ"ïzController.add_event_listenerc                 C   s¶   | j N d}t| j ¡ ƒD ]\}}||v r&| |¡ t|ƒdkr&d}| j|= q|rA|  dd | j ¡ ¡ ¡}| 	¡ sIt
 d| ¡‚W d  ƒ dS W d  ƒ dS 1 sTw   Y  dS )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ò   rã   r  rD   r“   ra   rf   r‰  r]   r‹   )rK   r¥   Zevent_types_changedr×  Úevent_listenersrŽ   r1   r1   r2   r‹  ˜  s"   	
€üõ"òz Controller.remove_event_listenerc                 C   sf   | j & |  ¡ s	 W d  ƒ dS |rd||f n|}| j |d¡W  d  ƒ S 1 s,w   Y  dS )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ú%s.%s)rñ   râ   rï   rE   )rK   r  Ú	namespaceÚ	cache_keyr1   r1   r2   r  ²  s   
þ$ûzController._get_cachec                 C   sp   | j + i }|  ¡ r%|D ]}|rd||f n|}|| jv r$| j| ||< q|W  d  ƒ S 1 s1w   Y  dS )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ñ   râ   rï   )rK   r  rÜ  Zcached_valuesr  rÝ  r1   r1   r2   r
  Ã  s   

€$özController._get_cache_mapc                 C   s  | j { |  ¡ s	 W d  ƒ dS |du r5|r5t| j ¡ ƒD ]}| d| ¡r+| j|= q	 W d  ƒ dS |dkrI| ¡ }tD ]	}||v rH||= q?t| ¡ ƒD ]&\}}|r\d||f }n|}|du rp|t| j ¡ ƒv ro| j|= qO|| j|< qOW d  ƒ dS 1 sw   Y  dS )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.rá   rÛ  )	rñ   râ   r¶   rï   rf   rV   ÚcopyÚUNCACHEABLE_GETCONF_PARAMSrã   )rK   r  rÜ  rÝ  rY   r¨   r1   r1   r2   rå   Ù  s8   	þ€õ€€ö"ëzController._set_cachec                 C   s¬   | j I |  ¡ s	 W d  ƒ dS tdd„ | ¡ D ƒƒr#|  ddi¡ |  tdd„ tD ƒƒd¡ |  dd¡ |  d	di¡ |  d
di¡ W d  ƒ dS 1 sOw   Y  dS )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                 s   s    | ]	}d |  ¡ v V  qdS )ZhiddenNrÙ   r  r1   r1   r2   rÝ     rà   z=Controller._confchanged_cache_invalidation.<locals>.<genexpr>r´  c                 S   s   g | ]}|  ¡ d f‘qS rI   rÙ   rß   r1   r1   r2   r[     r˜  z>Controller._confchanged_cache_invalidation.<locals>.<listcomp>rê   r1  rž  ré   )rñ   râ   Úanyrf   rå   re   r  r£  r1   r1   r2   ræ     s   þ"òz*Controller._confchanged_cache_invalidationc                 C   rœ   )zz
    **True** if caching has been enabled, **False** otherwise.

    :returns: bool to indicate if caching is enabled
    )rî   r•   r1   r1   r2   râ     s   zController.is_caching_enabledc                 C   s   || _ | j s|  ¡  dS dS )z–
    Enables or disables caching of information retrieved from tor.

    :param bool enabled: **True** to enable caching, **False** to disable it
    N)rî   rÕ   )rK   Úenabledr1   r1   r2   Úset_caching$  s   ÿzController.set_cachingc                 C   s>   | j  i | _d| _d| _W d  ƒ dS 1 sw   Y  dS )z#
    Drops any cached results.
    rm   N)rñ   rï   rð   rõ   r•   r1   r1   r2   rÕ   0  s
   "ýzController.clear_cachec              
   C   s–   |   d| ¡}tj d|¡ |jdv r<|jdkr4|j d¡r4t |j|j|jd|j dd¡d … g¡‚t 	|j|j¡‚| 
¡ sIt d	t|ƒ ¡‚d
S )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 optionéF   Ú.r?   z)+LOADCONF Received unexpected response
%sN)r“   r]   rŽ   r  rŠ  r’   rV   r:  r±  r²  r‰  r‹   rd  )rK   Z
configtextrŽ   r1   r1   r2   Ú	load_conf:  s   

,ÿzController.load_confc                 C   sf   |   ¡ tjjjk rd}|  |rdnd¡}tj d|¡ | ¡ r!dS |j	dkr.t 
|j	|j¡‚t d¡‚)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 FORCEZSAVECONFr‡  TÚ551z*SAVECONF returned unexpected response code)r  r]   r&   rR  ZSAVECONF_FORCEr“   rŽ   r  r‰  rŠ  r'  r’   r‹   )rK   ZforcerŽ   r1   r1   r2   Ú	save_confN  s   

zController.save_confc                 C   sp   |  ¡ }|| jv rdS d}|dkrtjjj}n	|dkr tjjj}|r3|  d¡}|r3||kr3| j |¡ || jv S )a  
    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
    TNZEXTENDED_EVENTSZVERBOSE_NAMES)	Úupperrô   r]   r&   rR  ZFEATURE_EXTENDED_EVENTSZFEATURE_VERBOSE_NAMESr  r¡   )rK   ZfeatureZdefaulted_versionZour_versionr1   r1   r2   Úis_feature_enabledk  s   




zController.is_feature_enabledc                 C   s®   t j |¡r	|g}|  dd |¡ ¡}t j d|¡ | ¡ sI|jdkrAg }|j	 
d¡r8|j	d|j	 dd¡… g}t  |j|j	|¡‚t  d|j ¡‚|  jd	d
„ |D ƒ7  _dS )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Â  r2  z0USEFEATURE provided an invalid response code: %sc                 S   r   r1   )rè  r–  r1   r1   r2   r[   ®  r  z-Controller.enable_feature.<locals>.<listcomp>N)r]   r^   r  r“   ra   rŽ   r  r‰  rŠ  r’   rV   r±  r:  r‹   rô   )rK   ZfeaturesrŽ   Zinvalid_featurer1   r1   r2   Úenable_featureŠ  s   
zController.enable_featurec                 C   s,   |   ¡ D ]}|j|kr|  S qtd| ƒ‚)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ÚidrË   )rK   Ú
circuit_idr@   Úcircr1   r1   r2   Úget_circuit°  s
   
ÿzController.get_circuitc              	   C   óX   g }|   d¡}| ¡ D ]}tj t tjj 	d| ¡¡¡}tj
 d|¡ | |¡ q|S )aF  
    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]   rÍ   Zrecv_messagern  ro  r^   r  Z	_to_bytesrŽ   r  r¡   )rK   r@   ZcircuitsrŽ   rî  Zcirc_messager1   r1   r2   rë  É  s   
 zController.get_circuitsÚgeneralc                 C   s   |   d||||¡S )as  
    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)rK   r;   ÚpurposeÚawait_buildr‘  r1   r1   r2   Únew_circuitá  s   zController.new_circuitr   c              	      sº  t  ¡ d‰ }t ¡ }|r‡ fdd„}|  |tj¡ z¹t|ƒ}|du r:|dkr:tjj	j
}|  ¡ |ks:t dd| ¡‚|g}	tj |¡rF|g}|rP|	 d |¡¡ |rY|	 d| ¡ |  d	d
 |	¡ ¡}
tj d|
¡ |
jdv rwt |
j|
j¡‚|
 ¡ sƒt d|
j ¡‚|
j d¡st d|
¡‚|
j d
d¡d }|rÉ	 tˆ ||ƒ}|j|krÈ|jtjkr­n|jtjkr¼t  d|j! |¡‚|jtj"krÈt  d|¡‚q›|W |rÓ|  #|¡ S S |rÜ|  #|¡ w w )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                    r~  rI   r  rÖ   ©Z
circ_queuer1   r2   Úcirc_listener'  rƒ  z0Controller.extend_circuit.<locals>.circ_listenerr   i   z3EXTENDCIRCUIT requires the path prior to version %sr%  z
purpose=%szEXTENDCIRCUIT %sr  r‡  ©Z512r©  z3EXTENDCIRCUIT returned unexpected response code: %sz	EXTENDED z"EXTENDCIRCUIT response invalid:
%sr?   Tz Circuit failed to be created: %sz!Circuit was closed prior to build)$rt   ru   rµ   rø   rù   r   rd  r]   r&   rR  ZEXTENDCIRCUIT_PATH_OPTIONALr  r²  r^   r  r¡   ra   r“   rŽ   r  rŠ  r’   r‰  r‹   rV   r(  rŒ  rì  r6   r   ZBUILTrŽ  ZCircuitExtensionFailedr  r
   r‹  )rK   rí  r;   rõ  rö  r‘  rù  r  Zpath_opt_versionrB   rŽ   r÷  rî  r1   rø  r2   rô  ÷  sX   ,


÷ÿÿzController.extend_circuitc                 C   sV   |   d||f ¡}tj d|¡ | ¡ s)|jdkr!t |j|j¡‚t d|j ¡‚dS )ak  
    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 %s purpose=%sr‡  r©  z7SETCIRCUITPURPOSE returned unexpected response code: %sN)	r“   r]   rŽ   r  r‰  rŠ  r²  r’   r‹   )rK   rí  rõ  rŽ   r1   r1   r2   Úrepurpose_circuit_  s   
üzController.repurpose_circuitÚ c                 C   sv   |   d||f ¡}tj d|¡ | ¡ s9|jdv r1|j d¡r)t |j|j|g¡‚t 	|j|j¡‚t 
d|j ¡‚dS )a‘  
    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 %s %sr‡  rú  zUnknown circuit z2CLOSECIRCUIT returned unexpected response code: %sN)r“   r]   rŽ   r  r‰  rŠ  r’   rV   r:  r²  r‹   )rK   rí  ÚflagrŽ   r1   r1   r2   Úclose_circuitt  s   
úzController.close_circuitc              	   C   rð  )aH  
    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
rñ  rò  )rK   r@   ZstreamsrŽ   Ústreamr’   r1   r1   r2   Úget_streams‹  s   
 zController.get_streamsc                 C   sž   d||f }|r|d| 7 }|   |¡}tj d|¡ | ¡ sM|jdkr+t |j|j¡‚|jdkr8t |j|j¡‚|jdkrEt 	|j|j¡‚t 
d|j ¡‚dS )	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 %s %sz HOP=%sr‡  r©  ræ  Z555z2ATTACHSTREAM returned unexpected response code: %sN)r“   r]   rŽ   r  r‰  rŠ  r²  r’   r'  rˆ  r‹   )rK   Ú	stream_idrí  Zexiting_hopr<  rŽ   r1   r1   r2   Úattach_stream¤  s   



øzController.attach_streamc                 C   s¤   |   d|tj |¡d |f ¡}tj d|¡ | ¡ sP|jdv rH|j 	d¡r0t 
|j|j|g¡‚|j 	d¡r@t 
|j|j|g¡‚t |j|j¡‚t d|j ¡‚dS )	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 %s %s %sr?   r‡  rú  zUnknown stream zUnrecognized reason z1CLOSESTREAM returned unexpected response code: %sN)r“   r]   ÚRelayEndReasonZindex_ofrŽ   r  r‰  rŠ  r’   rV   r:  r²  r‹   )rK   r  r  rý  rŽ   r1   r1   r2   Úclose_streamÇ  s    
øzController.close_streamc                 C   sp   |   d| ¡}tj d|¡ | ¡ r!|tjjkrt ¡ | _dS dS |j	dkr0t 
|j	|j|g¡‚t d|j	 ¡‚)a  
    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   ZNEWNYMrµ   rð   rŠ  r:  r’   r‹   )rK   rÔ   rŽ   r1   r1   r2   rÔ   ä  s   ÿ
zController.signalc                 C   s   |   ¡ r
|  ¡ dkS dS )a   
    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
    rm   F)r‚   Úget_newnym_waitr•   r1   r1   r2   Úis_newnym_availableû  s   zController.is_newnym_availablec                 C   s   t d| jd t ¡  ƒS )a  
    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
    rm   é
   )r?  rð   rµ   r•   r1   r1   r2   r    s   zController.get_newnym_waitc                 C   sT   |sd}nd}d}|D ]}t |  |¡ƒ}|dkr| d¡rq|r%t||ƒn|}q|S )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
    )ZBandwidthRateZRelayBandwidthRateZMaxAdvertisedBandwidth)ZBandwidthBurstZRelayBandwidthBurstNr   ZRelay)r7  r	  rV   Úmin)rK   r@   ZburstZ
attributesr¨   ÚattrZ
attr_valuer1   r1   r2   Úget_effective_rate  s   zController.get_effective_ratec              
   C   sv   | j du r8z|  d¡ d| _ W | j S  tjy7 } zdt|ƒv r$d| _ nW Y d}~dS W Y d}~| j S d}~ww | j S )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   rd  )rK   rj   r1   r1   r2   r  @  s   

ú
þ€úzController.is_geoip_unavailablec                 C   s>   d  dd„ t| ¡ ƒD ƒ¡}|  d| ¡}tj d|¡ |jS )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  c                 S   s   g | ]
\}}d ||f ‘qS )z%s=%sr1   rÚ   r1   r1   r2   r[   r  r.  z*Controller.map_address.<locals>.<listcomp>zMAPADDRESS %sZ
MAPADDRESS)ra   r¶   rã   r“   r]   rŽ   r  r  )rK   ÚmappingZmapaddress_argrŽ   r1   r1   r2   Úmap_address_  s   zController.map_addressc                 C   s6   |   ¡ tjjjk rtjdtjjj d‚|  d¡ dS )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 %srl  Ú
DROPGUARDSN)r  r]   r&   rR  r  rˆ  r“   r•   r1   r1   r2   Údrop_guardsx  s   	zController.drop_guardsc                    s^  t t| ƒ ¡  | jJ z'|  ¡ d }|r1|D ]}| j|= qdd |¡ }t |tj	dd |¡ ¡ W n t
jyL } zt d| ¡ W Y d }~nd }~ww W d   ƒ n1 sWw   Y  |  dd ¡}|tt ¡ ƒkr«|  ¡ r­|  d¡}t
j d	|¡ | ¡ r¢z|  d¡ W d S  t
jy¡ } zt d
| ¡ W Y d }~d S d }~ww t d| ¡ d S d S d S )Nr?   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)Z__OwningControllerProcessZTAKEOWNERSHIPr‡  z…We were unable to reset tor's __OwningControllerProcess configuration. It will continue to periodically check if our pid exists. (%s)z—We 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ò   ra   r   Zlog_oncer   r]   r‹   rh   r	  rd  r`   Úgetpidr–   r“   rŽ   r  r‰  r¤  r   )rK   rØ  r×  Z
logging_idrj   Z
owning_pidrŽ   rú   r1   r2   r„   †  s:   
€€ÿ€õ
€ÿózController._post_authenticationc                 C   sî   zt j d|¡ |j}W n t jy* } zt d||f ¡ t}W Y d }~nd }~ww | j? t	| j
 ¡ ƒD ].\}}||krd|D ]#}z||ƒ W q@ tyc } zt d||f ¡ W Y d }~q@d }~ww q6W d   ƒ d S 1 spw   Y  d S )Nrñ  z#Tor sent a malformed event (%s): %sz4Event listener raised an uncaught exception (%s): %s)r]   rŽ   r  rq  r‹   r   Úerrorr   ró   r¶   rò   rã   rg   rh   )rK   r«   r×  rj   r+  rÚ  r¥   r1   r1   r2   r¬   ¬  s*   
€þ€ÿ€û"ÿzController._handle_eventc              	   C   sì   g g }}| j b |  ¡ rL|  dd | j ¡ ¡ ¡}| ¡ r&t| j ¡ ƒ}n0t| j ¡ ƒD ]2}|  dd ||g ¡ ¡}| ¡ rF| |¡ q-| |¡ q-W d  ƒ ||fS W d  ƒ ||fS W d  ƒ ||fS 1 smw   Y  ||fS )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
    rÙ  r  N)	ró   r†   r“   ra   rò   rf   r‰  r¶   r¡   )rK   Z
set_eventsrØ  rŽ   ri   r1   r1   r2   rÕ  ½  s,   

æ
ÿé
úø
ëãzController._attach_listeners)rÇ   r@   )rÑ   rÅ   )NNNNrI   )rÏ  rÐ  FFFNNN)Nró  FN)r   Nró  FN)rü  )Ur-   r.   r/   r0   ÚstaticmethodrÐ   rÓ   r‡   r‘   rü   rý   rT   r   r  r  r)  r0  r/  rC  rE  rF  rL  rI  rT  rU  rY  rk  rt  rx  ry  rv  rW  r|  r“  r	  r”  r›  r  rœ  r¢  r¤  r¡  r»  r½  rÇ  rÉ  rÎ  rÒ  rÓ  rø   r‹  r  r
  rå   ræ   râ   râ  rÕ   rå  rç  ré  rê  rï  rë  r÷  rô  rû  rþ  r   r  r]   r  ZMISCr  rÔ   r  r  r
  r  r  r  r„   r¬   rÕ  Ú__classcell__r1   r1   rú   r2   rÆ   å  sÐ    !1	{@$i+"72)9>D&:$c1v
Q_
A
v)
4 C:


*	

&

h

#'&rÆ   c              
   C   sL   | r$zdd„ |   d¡D ƒW S  tjy# } z	t d|| f ¡‚d}~ww g S )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
  c                 S   r=  r1   )Ú_parse_circ_entryr–  r1   r1   r2   r[     r  z$_parse_circ_path.<locals>.<listcomp>r%  z%s: %sN)r(  r]   r‹   )r;   rj   r1   r1   r2   Ú_parse_circ_pathé  s   !€þr  c                 C   s°   d| v r|   d¡\}}nd| v r|   d¡\}}n| d dkr$| d}}nd| }}|durBtjj |d¡s<t d| ¡‚|dd… }|durTtjj |¡sTt d	| ¡‚||fS )
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)r?   z.Nickname in the circuit path is malformed (%s))r(  r]   r^   ra  rb  r‹   rc  )r—  r(   Znicknamer1   r1   r2   r    s   
r  c                 C   st   | dur2t | tƒr!t|  ¡ ƒD ]\}}| ¡ | ¡ kr|  S qn| D ]}| ¡ | ¡ kr1|  S q#td|| f ƒ‚)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
  Nz"key '%s' doesn't exist in dict: %s)rŠ   re   r¶   rã   rW   rË   )r  rY   r@   rÛ   rÜ   r—  r1   r1   r2   r  9  s   
ÿÿÿr  c                 C   s`   |r,|t   ¡ |  }|dkrt d| ¡‚z|  d|¡W S  tjy+   t d| ¡‚w |  ¡ S )z6
  Pulls an item from a queue with a given timeout.
  r   z Reached our %0.1f second timeoutT)rµ   r]   ZTimeoutrE   rt   r   )Zevent_queuer‘  r  Z	time_leftr1   r1   r2   rŒ  U  s   ÿrŒ  rÅ   )Gr0   r@  r­  rO   rA   rn  r`   ro   rµ   r   ÚImportErrorZstem.util.ordereddictrt   ru   Zstem.descriptor.microdescriptorr]   Zstem.descriptor.readerZ#stem.descriptor.router_status_entryZ!stem.descriptor.server_descriptorZstem.exit_policyZstem.responseZstem.response.eventsZstem.socketZ	stem.utilZstem.util.confZstem.util.connectionZstem.util.enumZstem.util.str_toolsZstem.util.systemZstem.util.tor_toolsZstem.versionr   r   r   r   rÂ   r   r^   ÚenumÚEnumr¯   ZUppercaseEnumrù   r;  r°   Úmapr  r  rd  rW   r§  r  r™  r  r  rß  rw  r\   Ú
namedtupler+   r8   r9   rT   rk   Úobjectrl   rÆ   r  r  r  rŒ  r1   r1   r1   r2   Ú<module>   sÒ    wÿÿ$÷û
	
1   H                        +%